]>
Commit | Line | Data |
---|---|---|
53478050 MT |
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 | ||
34 | def __str__(self): | |
35 | return self.__class__.__name__ | |
36 | ||
37 | def run(self): | |
38 | raise NotImplementedError | |
39 | ||
40 | ||
41 | class EventShell(Event): | |
42 | heartbeat = 0.1 | |
43 | timeout = 10 | |
44 | ||
45 | def __init__(self, interface, script): | |
46 | Event.__init__(self, interface) | |
47 | ||
48 | self.script = script | |
49 | ||
50 | def run(self): | |
51 | args = " ".join([self.script, self.interface.dev]) | |
52 | ||
53 | start = time.time() | |
54 | self.log.debug("Running: %s" % args) | |
55 | ||
56 | p = subprocess.Popen(args, | |
57 | close_fds=True, | |
58 | shell=True, | |
59 | stdin=open("/dev/null", "r"), | |
60 | stdout=subprocess.PIPE, | |
61 | stderr=subprocess.STDOUT) | |
62 | ||
63 | while p.poll() is None: | |
64 | time.sleep(self.heartbeat) | |
65 | if (time.time() - start) > self.timeout: | |
66 | try: | |
67 | os.killpg(p.pid, 9) | |
68 | except OSError: | |
69 | pass | |
70 | raise EventTimeout, "Script took too long to return" | |
71 | ||
72 | for line in p.stdout.read().splitlines(): | |
73 | if not line: continue | |
74 | self.log.debug(" %s" % line) | |
75 | ||
76 | self.cappie.log.debug("Child process returned with exit code: %s" % \ | |
77 | p.returncode) | |
78 | ||
79 | return p.returncode |