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