there can be more than one message on the socket; empty the queue when shutting down...
[saartuer.git] / libtuer.py
1 import logging, logging.handlers, os, time, queue, threading, subprocess
2 import traceback, smtplib
3 import email.mime.text, email.utils
4
5 # Logging configuration
6 syslogLevel = logging.INFO
7 mailLevel   = logging.CRITICAL # must be "larger" than syslog level!
8 from config import mailAddress
9 printLevel  = logging.DEBUG
10
11 # Mail logging handler
12 def sendeMail(subject, text, receivers, sender='sphinx@hacksaar.de', replyTo=None):
13         assert isinstance(receivers, list)
14         if not len(receivers): return # nothing to do
15         # construct content
16         msg = email.mime.text.MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8')
17         msg['Subject'] = subject
18         msg['Date'] = email.utils.formatdate(localtime=True)
19         msg['From'] = sender
20         msg['To'] = ', '.join(receivers)
21         if replyTo is not None:
22                 msg['Reply-To'] = replyTo
23         # put into envelope and send
24         s = smtplib.SMTP('localhost')
25         s.sendmail(sender, receivers, msg.as_string())
26         s.quit()
27
28 # logging function
29 class Logger:
30         def __init__ (self):
31                 self.syslog = logging.getLogger("tuerd")
32                 self.syslog.setLevel(logging.DEBUG)
33                 self.syslog.addHandler(logging.handlers.SysLogHandler(address = '/dev/log',
34                                                                                                                 facility = logging.handlers.SysLogHandler.LOG_LOCAL0))
35         
36         def _log (self, lvl, what):
37                 thestr = "%s[%d]: %s" % ("tuerd", os.getpid(), what)
38                 # console log
39                 if lvl >= printLevel:
40                         print(thestr)
41                 # syslog
42                 if lvl >= syslogLevel:
43                         self.syslog.log(lvl, thestr)
44                 # mail log
45                 if lvl >= mailLevel and mailAddress is not None:
46                         sendeMail('Kritischer Türfehler', what, mailAddress)
47         
48         def debug(self, what):
49                 self._log(logging.DEBUG, what)
50         def info(self, what):
51                 self._log(logging.INFO, what)
52         def warning(self, what):
53                 self._log(logging.WARNING, what)
54         def error(self, what):
55                 self._log(logging.ERROR, what)
56         def critical(self, what):
57                 self._log(logging.CRITICAL, what)
58
59 logger = Logger()
60
61 # run a Python command asynchronously
62 def fire_and_forget(f):
63         def _fire_and_forget():
64                 try:
65                         f()
66                 except Exception as e:
67                         logger.critical("fire_and_forget: Got exception out of callback: %s" % str(e))
68                         logger.debug(traceback.format_exc())
69         t = threading.Thread(target=_fire_and_forget)
70         t.start()
71
72 # run a command asynchronously and log the return value if not 0
73 # prefix must be a string identifying the code position where the call came from
74 def fire_and_forget_cmd (cmd, log, prefix):
75         def _fire_and_forget_cmd ():
76                 with open("/dev/null", "w") as fnull:
77                         retcode = subprocess.call(cmd, stdout=fnull, stderr=fnull)
78                         if retcode is not 0:
79                                 logger.error("%sReturn code %d at command: %s" % (prefix,retcode,str(cmd)))
80         fire_and_forget(_fire_and_forget_cmd)
81
82 # Threaded callback class
83 class ThreadFunction():
84         _CALL = 0
85         _TERM = 1
86         
87         def __init__(self, f, name):
88                 self.name = name
89                 self._f = f
90                 self._q = queue.Queue()
91                 self._t = threading.Thread(target=self._thread_func)
92                 self._t.start()
93         
94         def _thread_func(self):
95                 while True:
96                         (cmd, data) = self._q.get()
97                         # run command
98                         if cmd == ThreadFunction._CALL:
99                                 try:
100                                         self._f(*data)
101                                 except Exception as e:
102                                         logger.critical("ThreadFunction: Got exception out of handler thread %s: %s" % (self.name, str(e)))
103                                         logger.debug(traceback.format_exc())
104                         elif cmd == ThreadFunction._TERM:
105                                 assert data is None
106                                 break
107                         else:
108                                 logger.error("ThreadFunction: Command %d does not exist" % cmd)
109         
110         def __call__(self, *arg):
111                 self._q.put((ThreadFunction._CALL, arg))
112         
113         def stop(self):
114                 # empty the queue
115                 try:
116                         while True:
117                                 self._q.get_nowait()
118                 except queue.Empty:
119                         pass
120                 # now wait till the job-in-progress is done
121                 self._q.put((ThreadFunction._TERM, None))
122                 self._t.join()
123
124 # Thread timer-repeater class: Call a function every <sleep_time> seconds
125 class ThreadRepeater():
126         def __init__(self, f, sleep_time, name):
127                 self.name = name
128                 self._f = f
129                 self._stop = False
130                 self._sleep_time = sleep_time
131                 self._t = threading.Thread(target=self._thread_func)
132                 self._t.start()
133         
134         def _thread_func(self):
135                 while True:
136                         if self._stop:
137                                 break
138                         try:
139                                 self._f()
140                         except Exception as e:
141                                 logger.critical("ThreadRepeater: Got exception out of handler thread %s: %s" % (self.name, str(e)))
142                                 logger.debug(traceback.format_exc())
143                         time.sleep(self._sleep_time)
144         
145         def stop(self):
146                 self._stop = True
147                 self._t.join()