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