e31ce2728497f1c2dab8bfadad7d3b7a153ec41c
[saartuer.git] / libtuer.py
1 import logging, logging.handlers, os, time, queue, threading, subprocess, multiprocessing
2
3 # logging function
4 class Logger:
5         def __init__ (self):
6                 import __main__ as main
7                 self.name = os.path.basename(main.__file__)
8                 self.logger = logging.getLogger(self.name)
9                 self.logger.setLevel(logging.INFO)
10                 self.handler = logging.handlers.SysLogHandler(address = '/dev/log', facility = logging.handlers.SysLogHandler.LOG_LOCAL0)
11                 self.logger.addHandler(self.handler)
12         
13         def log (self, lvl, what):
14                 thestr = "%s[%d]: %s" % (self.name,os.getpid(),what)
15                 print (thestr)
16                 self.logger.log(lvl, thestr)
17         
18         def debug(self, what):
19                 self.log(logging.DEBUG, what)
20         def info(self, what):
21                 self.log(logging.INFO, what)
22         def warning(self, what):
23                 self.log(logging.WARNING, what)
24         def error(self, what):
25                 self.log(logging.ERROR, what)
26         def critical(self, what):
27                 self.log(logging.CRITICAL, what)
28
29 logger = Logger()
30
31 # run a command asynchronously and log the return value if not 0
32 # prefix must be a string identifying the code position where the call came from
33 def fire_and_forget (cmd, log, prefix):
34         def _fire_and_forget (cmd, log, prefix):
35                 with open("/dev/null", "w") as fnull:
36                         retcode = subprocess.call(cmd, stdout=fnull, stderr=fnull)
37                         if retcode is not 0:
38                                 log("%sReturn code %d at command: %s" % (prefix,retcode,str(cmd)))
39         p = multiprocessing.Process(target=_fire_and_forget, args=(cmd,log,prefix))
40         p.start()
41
42 # Threaded callback class
43 class ThreadFunction():
44         _CALL = 0
45         _TERM = 1
46         
47         def __init__(self, f):
48                 self._f = f
49                 self._q = queue.Queue()
50                 self._t = threading.Thread(target=self._thread_func)
51                 self._t.start()
52         
53         def _thread_func(self):
54                 while True:
55                         (cmd, data) = self._q.get()
56                         # run command
57                         if cmd == _CALL:
58                                 try:
59                                         self._f(*data)
60                                 except Exception:
61                                         logger.error("ThreadFunction: Got exception out of handler thread: %s" % str(e))
62                         elif cmd == _TERM:
63                                 assert data is None
64                                 break
65                         else:
66                                 logger.error("ThreadFunction: Command %d does not exist" % cmd)
67         
68         def __call__(self, *arg):
69                 self._q.put((self._CALL, arg))
70         
71         def stop(self):
72                 self._q.put((_TERM, None))
73                 self._t.join()
74
75 # Thread timer-repeater class: Call a function every <sleep_time> seconds
76 class ThreadRepeater():
77         def __init__(self, f, sleep_time):
78                 self._f = f
79                 self._stop = False
80                 self._sleep_time = sleep_time
81                 self._t = threading.Thread(target=self._thread_func)
82                 self._t.start()
83         
84         def _thread_func():
85                 while True:
86                         if self._stop:
87                                 break
88                         self._f()
89                         time.sleep(sleep_time)
90         
91         def stop(self):
92                 self._stop = True
93                 self._t.join()