]> git.ipfire.org Git - oddments/cappie.git/blob - cappie/events.py
Add shortcut to database instance from Event class.
[oddments/cappie.git] / cappie / events.py
1 #!/usr/bin/python
2 ###############################################################################
3 # #
4 # Cappie #
5 # Copyright (C) 2010 Michael Tremer #
6 # #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
11 # #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
16 # #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
19 # #
20 ###############################################################################
21
22 import os
23 import subprocess
24 import time
25
26 from errors import *
27
28 class Event(object):
29 def __init__(self, interface):
30 self.cappie = interface.cappie
31 self.interface = interface
32 self.log = interface.log
33 self.db = self.cappie.db
34
35 def __str__(self):
36 return self.__class__.__name__
37
38 def addEvent(self, event):
39 return self.cappie.queue.add(event)
40
41 def run(self):
42 raise NotImplementedError
43
44
45 class EventShell(Event):
46 heartbeat = 0.1
47 timeout = 10
48
49 def __init__(self, interface, script):
50 Event.__init__(self, interface)
51
52 self.script = script
53
54 def run(self):
55 args = " ".join([self.script, self.interface.dev])
56
57 start = time.time()
58 self.log.debug("Running: %s" % args)
59
60 p = subprocess.Popen(args,
61 close_fds=True,
62 shell=True,
63 stdin=open("/dev/null", "r"),
64 stdout=subprocess.PIPE,
65 stderr=subprocess.STDOUT)
66
67 while p.poll() is None:
68 time.sleep(self.heartbeat)
69 if (time.time() - start) > self.timeout:
70 try:
71 os.killpg(p.pid, 9)
72 except OSError:
73 pass
74 raise EventTimeout, "Script took too long to return"
75
76 for line in p.stdout.read().splitlines():
77 if not line: continue
78 self.log.debug(" %s" % line)
79
80 self.cappie.log.debug("Child process returned with exit code: %s" % \
81 p.returncode)
82
83 return p.returncode