fixes; implement the Pins
[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 mailAddress = ['post+tuer'+'@'+'ralfj.de', 'vorstand@lists.hacksaar.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 = email.mime.text.MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8')
15         msg['Subject'] = subject
16         msg['Date'] = email.utils.formatdate(localtime=True)
17         msg['From'] = sender
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())
24         s.quit()
25
26 # logging function
27 class Logger:
28         def __init__ (self):
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))
33         
34         def _log (self, lvl, what):
35                 thestr = "%s[%d]: %s" % ("tuerd", os.getpid(), what)
36                 # console log
37                 print(thestr)
38                 # syslog
39                 self.syslog.log(lvl, thestr)
40                 # mail log
41                 if lvl >= mailLevel:
42                         sendeMail('Kritischer Türfehler', what, mailAddress)
43         
44         def debug(self, what):
45                 self._log(logging.DEBUG, what)
46         def info(self, 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)
54
55 logger = Logger()
56
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)
63                         if retcode is not 0:
64                                 logger.error("%sReturn code %d at command: %s" % (prefix,retcode,str(cmd)))
65         t = threading.Thread(target=_fire_and_forget)
66         t.start()
67
68 # Threaded callback class
69 class ThreadFunction():
70         _CALL = 0
71         _TERM = 1
72         
73         def __init__(self, f, name):
74                 self.name = name
75                 self._f = f
76                 self._q = queue.Queue()
77                 self._t = threading.Thread(target=self._thread_func)
78                 self._t.start()
79         
80         def _thread_func(self):
81                 while True:
82                         (cmd, data) = self._q.get()
83                         # run command
84                         if cmd == ThreadFunction._CALL:
85                                 try:
86                                         self._f(*data)
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:
91                                 assert data is None
92                                 break
93                         else:
94                                 logger.error("ThreadFunction: Command %d does not exist" % cmd)
95         
96         def __call__(self, *arg):
97                 self._q.put((ThreadFunction._CALL, arg))
98         
99         def stop(self):
100                 self._q.put((ThreadFunction._TERM, None))
101                 self._t.join()
102
103 # Thread timer-repeater class: Call a function every <sleep_time> seconds
104 class ThreadRepeater():
105         def __init__(self, f, sleep_time, name):
106                 self.name = name
107                 self._f = f
108                 self._stop = False
109                 self._sleep_time = sleep_time
110                 self._t = threading.Thread(target=self._thread_func)
111                 self._t.start()
112         
113         def _thread_func(self):
114                 while True:
115                         if self._stop:
116                                 break
117                         try:
118                                 self._f()
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)
123         
124         def stop(self):
125                 self._stop = True
126                 self._t.join()