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