1 import logging, logging.handlers, os, time, queue, threading, subprocess
2 import traceback, smtplib
3 import email.mime.text, email.utils
5 # Logging configuration
6 syslogLevel = logging.INFO
7 mailLevel = logging.CRITICAL # must be "larger" than syslog level!
8 mailAddress = ['post+tuer'+'@'+'ralfj.de', 'vorstand@lists.hacksaar.de']
9 printLevel = logging.DEBUG
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
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)
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())
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))
36 def _log (self, lvl, what):
37 thestr = "%s[%d]: %s" % ("tuerd", os.getpid(), what)
42 if lvl >= syslogLevel:
43 self.syslog.log(lvl, thestr)
45 if lvl >= mailLevel and mailAddress is not None:
46 sendeMail('Kritischer Türfehler', what, mailAddress)
48 def debug(self, what):
49 self._log(logging.DEBUG, 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)
61 # run a command asynchronously and log the return value if not 0
62 # prefix must be a string identifying the code position where the call came from
63 def fire_and_forget (cmd, log, prefix):
64 def _fire_and_forget ():
65 with open("/dev/null", "w") as fnull:
66 retcode = subprocess.call(cmd, stdout=fnull, stderr=fnull)
68 logger.error("%sReturn code %d at command: %s" % (prefix,retcode,str(cmd)))
69 t = threading.Thread(target=_fire_and_forget)
72 # Threaded callback class
73 class ThreadFunction():
77 def __init__(self, f, name):
80 self._q = queue.Queue()
81 self._t = threading.Thread(target=self._thread_func)
84 def _thread_func(self):
86 (cmd, data) = self._q.get()
88 if cmd == ThreadFunction._CALL:
91 except Exception as e:
92 logger.critical("ThreadFunction: Got exception out of handler thread %s: %s" % (self.name, str(e)))
93 logger.debug(traceback.format_exc())
94 elif cmd == ThreadFunction._TERM:
98 logger.error("ThreadFunction: Command %d does not exist" % cmd)
100 def __call__(self, *arg):
101 self._q.put((ThreadFunction._CALL, arg))
104 self._q.put((ThreadFunction._TERM, None))
107 # Thread timer-repeater class: Call a function every <sleep_time> seconds
108 class ThreadRepeater():
109 def __init__(self, f, sleep_time, name):
113 self._sleep_time = sleep_time
114 self._t = threading.Thread(target=self._thread_func)
117 def _thread_func(self):
123 except Exception as e:
124 logger.critical("ThreadRepeater: Got exception out of handler thread %s: %s" % (self.name, str(e)))
125 logger.debug(traceback.format_exc())
126 time.sleep(self._sleep_time)