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']
10 # Mail logging handler
11 def sendeMail(subject, text, receivers, sender='sphinx@hacksaar.de', replyTo=None):
12 if not isinstance(type(receivers), list): receivers = [receivers]
14 msg = email.mime.text.MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8')
15 msg['Subject'] = subject
16 msg['Date'] = email.utils.formatdate(localtime=True)
18 msg['To'] = ', '.join(receivers)
19 if replyTo is not None:
20 msg['Reply-To'] = replyTo
21 # put into envelope and send
22 s = smtplib.SMTP('localhost')
23 s.sendmail(sender, receivers, msg.as_string())
29 self.syslog = logging.getLogger("tuerd")
30 self.syslog.setLevel(syslogLevel)
31 self.syslog.addHandler(logging.handlers.SysLogHandler(address = '/dev/log',
32 facility = logging.handlers.SysLogHandler.LOG_LOCAL0))
34 def _log (self, lvl, what):
35 thestr = "%s[%d]: %s" % ("tuerd", os.getpid(), what)
39 self.syslog.log(lvl, thestr)
42 sendeMail('Kritischer Türfehler', what, mailAddress)
44 def debug(self, what):
45 self._log(logging.DEBUG, what)
47 self._log(logging.INFO, what)
48 def warning(self, what):
49 self._log(logging.WARNING, what)
50 def error(self, what):
51 self._log(logging.ERROR, what)
52 def critical(self, what):
53 self._log(logging.CRITICAL, what)
57 # run a command asynchronously and log the return value if not 0
58 # prefix must be a string identifying the code position where the call came from
59 def fire_and_forget (cmd, log, prefix):
60 def _fire_and_forget ():
61 with open("/dev/null", "w") as fnull:
62 retcode = subprocess.call(cmd, stdout=fnull, stderr=fnull)
64 logger.error("%sReturn code %d at command: %s" % (prefix,retcode,str(cmd)))
65 t = threading.Thread(target=_fire_and_forget)
68 # Threaded callback class
69 class ThreadFunction():
73 def __init__(self, f, name):
76 self._q = queue.Queue()
77 self._t = threading.Thread(target=self._thread_func)
80 def _thread_func(self):
82 (cmd, data) = self._q.get()
84 if cmd == ThreadFunction._CALL:
87 except Exception as e:
88 logger.critical("ThreadFunction: Got exception out of handler thread %s: %s" % (self.name, str(e)))
89 logger.debug(traceback.format_exc())
90 elif cmd == ThreadFunction._TERM:
94 logger.error("ThreadFunction: Command %d does not exist" % cmd)
96 def __call__(self, *arg):
97 self._q.put((ThreadFunction._CALL, arg))
100 self._q.put((ThreadFunction._TERM, None))
103 # Thread timer-repeater class: Call a function every <sleep_time> seconds
104 class ThreadRepeater():
105 def __init__(self, f, sleep_time, name):
109 self._sleep_time = sleep_time
110 self._t = threading.Thread(target=self._thread_func)
113 def _thread_func(self):
119 except Exception as e:
120 logger.critical("ThreadRepeater: Got exception out of handler thread %s: %s" % (self.name, str(e)))
121 logger.debug(traceback.format_exc())
122 time.sleep(self._sleep_time)