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