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