tweaks
[monitor.git] / moncommands.py
1 import os
2
3 DEBUG= 0
4
5 class ExceptionTimeout(Exception): pass
6 COMMAND_TIMEOUT = 60
7 ssh_options = { 'StrictHostKeyChecking':'no', 
8                                 'BatchMode':'yes', 
9                                 'PasswordAuthentication':'no',
10                                 'ConnectTimeout':'%s' % COMMAND_TIMEOUT}
11 from select import select 
12 import subprocess
13 import signal
14
15 class Sopen(subprocess.Popen):
16         def kill(self, signal = signal.SIGTERM):
17                 os.kill(self.pid, signal)
18
19 def read_t(stream, count, timeout=COMMAND_TIMEOUT*2):
20         lin, lout, lerr = select([stream], [], [], timeout)
21         if len(lin) == 0:
22                 raise ExceptionTimeout("TIMEOUT Running: %s" % cmd)
23
24         return stream.read(count)
25
26 class CMD:
27         def __init__(self):
28                 pass
29
30         def run_noexcept(self, cmd, timeout=COMMAND_TIMEOUT*2):
31
32                 #print "CMD.run_noexcept(%s)" % cmd
33                 try:
34                         return CMD.run(self,cmd,timeout)
35                 except ExceptionTimeout:
36                         import traceback; print traceback.print_exc()
37                         return ("", "SCRIPTTIMEOUT")
38                         
39         def system(self, cmd, timeout=COMMAND_TIMEOUT*2):
40                 (o,e) = self.run(cmd, timeout)
41                 self.output = o
42                 self.error = e
43                 if self.s.returncode is None:
44                         self.s.wait()
45                 return self.s.returncode
46
47         def run(self, cmd, timeout=COMMAND_TIMEOUT*2):
48
49                 #print "CMD.run(%s)" % cmd
50                 s = Sopen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
51                 self.s = s
52                 (f_in, f_out, f_err) = (s.stdin, s.stdout, s.stderr)
53                 #print "calling select(%s)" % timeout
54                 lout, lin, lerr = select([f_out], [], [f_err], timeout)
55                 #print "TIMEOUT!!!!!!!!!!!!!!!!!!!"
56                 if len(lin) == 0 and len(lout) == 0 and len(lerr) == 0:
57                         # Reached a timeout!  Nuke process so it does not hang.
58                         #print "KILLING"
59                         s.kill(signal.SIGKILL)
60                         raise ExceptionTimeout("TIMEOUT Running: %s" % cmd)
61                 else:
62                         #print "RETURNING"
63                         #print len(lin), len(lout), len(lerr)
64                         pass
65
66                 o_value = ""
67                 e_value = ""
68
69                 #print "reading from f_out"
70                 if len(lout) > 0: o_value = f_out.read()
71                 #print "reading from f_err"
72                 if len(lerr) > 0: e_value = f_err.read()
73
74                 #print "striping output"
75                 o_value = o_value.strip()
76                 e_value = e_value.strip()
77
78                 #print "OUTPUT", o_value, e_value
79
80                 #print "closing files"
81                 f_out.close()
82                 f_in.close()
83                 f_err.close()
84                 try:
85                         #print "s.kill()"
86                         s.kill()
87                         #print "after s.kill()"
88                 except OSError:
89                         # no such process, due to it already exiting...
90                         pass
91
92                 #print o_value, e_value
93                 return (o_value, e_value)
94
95         def runargs(self, args, timeout=COMMAND_TIMEOUT*2):
96
97                 #print "CMD.run(%s)" % " ".join(args)
98                 s = Sopen(args, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
99                 self.s = s
100                 (f_in, f_out, f_err) = (s.stdin, s.stdout, s.stderr)
101                 lout, lin, lerr = select([f_out], [], [f_err], timeout)
102                 if len(lin) == 0 and len(lout) == 0 and len(lerr) == 0:
103                         # Reached a timeout!  Nuke process so it does not hang.
104                         s.kill(signal.SIGKILL)
105                         raise ExceptionTimeout("TIMEOUT Running: %s" % cmd)
106                 o_value = f_out.read()
107                 e_value = ""
108                 if o_value == "":       # An error has occured
109                         e_value = f_err.read()
110
111                 o_value = o_value.strip()
112                 e_value = e_value.strip()
113
114                 f_out.close()
115                 f_in.close()
116                 f_err.close()
117                 try:
118                         s.kill()
119                 except OSError:
120                         # no such process, due to it already exiting...
121                         pass
122
123                 return (o_value, e_value)
124
125
126 class SSH(CMD):
127         def __init__(self, user, host, port=22, options = ssh_options):
128                 self.options = options
129                 self.user = user
130                 self.host = host
131                 self.port = port
132                 return
133
134         def __options_to_str(self):
135                 options = ""
136                 for o,v in self.options.iteritems():
137                         options = options + "-o %s=%s " % (o,v)
138                 return options
139
140         def run(self, cmd, timeout=COMMAND_TIMEOUT*2):
141                 cmd = "ssh -p %s %s %s@%s '%s'" % (self.port, self.__options_to_str(), 
142                                                                         self.user, self.host, cmd)
143                 #print "SSH.run(%s)" % cmd
144                 return CMD.run(self, cmd, timeout)
145
146         def get_file(self, rmt_filename, local_filename=None):
147                 if local_filename == None:
148                         local_filename = "./"
149                 cmd = "scp -P %s -B %s %s@%s:%s %s" % (self.port, self.__options_to_str(), 
150                                                                         self.user, self.host, 
151                                                                         rmt_filename, local_filename)
152                 # output :
153                 #       errors will be on stderr,
154                 #   success will have a blank stderr...
155                 return CMD.run_noexcept(self, cmd)
156
157         def run_noexcept(self, cmd):
158                 cmd = "ssh -p %s %s %s@%s '%s'" % (self.port, self.__options_to_str(), 
159                                                                         self.user, self.host, cmd)
160                 #print "SSH.run_noexcept(%s)" % cmd
161                 return CMD.run_noexcept(self, cmd)
162
163         def run_noexcept2(self, cmd, timeout=COMMAND_TIMEOUT*2):
164                 cmd = "ssh -p %s %s %s@%s %s" % (self.port, self.__options_to_str(), 
165                                                                         self.user, self.host, cmd)
166                 #print "SSH.run_noexcept2(%s)" % cmd
167                 r = CMD.run_noexcept(self, cmd, timeout)
168
169                 # XXX: this may be resulting in deadlocks... not sure.
170                 #if self.s.returncode is None:
171                 #       #self.s.kill()
172                 #       self.s.kill(signal.SIGKILL)
173                 #       self.s.wait()
174                 #       self.ret = self.s.returncode
175                 self.ret = -1
176
177                 return r
178
179         def system2(self, cmd, timeout=COMMAND_TIMEOUT*2):
180                 cmd = "ssh -p %s %s %s@%s %s" % (self.port, self.__options_to_str(), 
181                                                                         self.user, self.host, cmd)
182                 #print "SSH.system2(%s)" % cmd
183                 return CMD.system(self, cmd, timeout)
184
185         def runE(self, cmd):
186                 cmd = "ssh -p %s %s %s@%s '%s'" % (self.port, self.__options_to_str(), 
187                                                                         self.user, self.host, cmd)
188                 if ( DEBUG == 1 ):
189                         print cmd,
190                 (f_in, f_out, f_err) = os.popen3(cmd)
191
192                 value = f_out.read()
193                 if value == "": # An error has occured
194                         value = f_err.read()
195                         value = value.strip()
196
197                 if ( DEBUG == 1 ):
198                         print " == %s" % value
199                 f_out.close()
200                 f_in.close()
201                 f_err.close()
202                 return value.strip()
203                 
204 import time
205 class MyTimer:
206         def __init__(self):
207                 self.start = time.time()
208
209         def end(self):
210                 self.end = time.time()
211                 t = self.end-self.start
212                 return t
213
214         def diff(self):
215                 self.end = time.time()
216                 t = self.end-self.start
217                 self.start = self.end
218                 return t