typo. Missed a shell=True arg to Popen.
[monitor.git] / reboot.py
1 #!/usr/bin/python
2 #
3 # Reboot specified nodes
4 #
5
6 import getpass, getopt
7 import os, sys
8 import xml, xmlrpclib
9 import errno, time, traceback
10 import urllib2
11 import threading, popen2
12 import array, struct
13 #from socket import *
14 import socket
15 import plc
16 import base64
17 from subprocess import PIPE, Popen
18
19 plc_lock = threading.Lock()
20
21 # Use our versions of telnetlib and pyssh
22 sys.path.insert(0, os.path.dirname(sys.argv[0]))
23 import telnetlib
24 sys.path.insert(0, os.path.dirname(sys.argv[0]) + "/pyssh")    
25 import pyssh
26
27 # Timeouts in seconds
28 TELNET_TIMEOUT = 30
29
30 # Event class ID from pcu events
31 #NODE_POWER_CONTROL = 3
32
33 # Monitor user ID
34 #MONITOR_USER_ID = 11142
35
36 import logging
37 logger = logging.getLogger("monitor")
38 verbose = 1
39 #dryrun = 0;
40
41 class ExceptionNoTransport(Exception): pass
42 class ExceptionNotFound(Exception): pass
43 class ExceptionPassword(Exception): pass
44 class ExceptionTimeout(Exception): pass
45 class ExceptionPrompt(Exception): pass
46 class ExceptionSequence(Exception): pass
47 class ExceptionReset(Exception): pass
48 class ExceptionPort(Exception): pass
49 class ExceptionUsername(Exception): pass
50
51 def telnet_answer(telnet, expected, buffer):
52         global verbose
53
54         output = telnet.read_until(expected, TELNET_TIMEOUT)
55         #if verbose:
56         #       logger.debug(output)
57         if output.find(expected) == -1:
58                 raise ExceptionNotFound, "'%s' not found" % expected
59         else:
60                 telnet.write(buffer + "\r\n")
61
62
63 # PCU has model, host, preferred-port, user, passwd, 
64
65 # This is an object derived directly form the PLCAPI DB fields
66 class PCU(object):
67         def __init__(self, plc_pcu_dict):
68                 for field in ['username', 'password', 'site_id', 
69                                                 'hostname', 'ip', 
70                                                 'pcu_id', 'model', 
71                                                 'node_ids', 'ports', ]:
72                         if field in plc_pcu_dict:
73                                 self.__setattr__(field, plc_pcu_dict[field])
74                         else:
75                                 raise Exception("No such field %s in PCU object" % field)
76
77 # These are the convenience functions build around the PCU object.
78 class PCUModel(PCU):
79         def __init__(self, plc_pcu_dict):
80                 PCU.__init__(self, plc_pcu_dict)
81                 self.host = self.pcu_name()
82
83         def pcu_name(self):
84                 if self.hostname is not None and self.hostname is not "":
85                         return self.hostname
86                 elif self.ip is not None and self.ip is not "":
87                         return self.ip
88                 else:
89                         return None
90
91         def nodeidToPort(self, node_id):
92                 if node_id in self.node_ids:
93                         for i in range(0, len(self.node_ids)):
94                                 if node_id == self.node_ids[i]:
95                                         return self.ports[i]
96
97                 raise Exception("No such Node ID: %d" % node_id)
98
99 # This class captures the observed pcu records from FindBadPCUs.py
100 class PCURecord:
101         def __init__(self, pcu_record_dict):
102                 for field in ['nodenames', 'portstatus', 
103                                                 'dnsmatch', 
104                                                 'complete_entry', ]:
105                         if field in pcu_record_dict:
106                                 if field == "reboot":
107                                         self.__setattr__("reboot_str", pcu_record_dict[field])
108                                 else:
109                                         self.__setattr__(field, pcu_record_dict[field])
110                         else:
111                                 raise Exception("No such field %s in pcu record dict" % field)
112
113 class Transport:
114         TELNET = 1
115         SSH    = 2
116         HTTP   = 3
117
118         TELNET_TIMEOUT = 60
119
120         def __init__(self, type, verbose):
121                 self.type = type
122                 self.verbose = verbose
123                 self.transport = None
124
125 #       def __del__(self):
126 #               if self.transport:
127 #                       self.close()
128
129         def open(self, host, username=None, password=None, prompt="User Name"):
130                 transport = None
131
132                 if self.type == self.TELNET:
133                         transport = telnetlib.Telnet(host, timeout=self.TELNET_TIMEOUT)
134                         transport.set_debuglevel(self.verbose)
135                         if username is not None:
136                                 self.transport = transport
137                                 self.ifThenSend(prompt, username, ExceptionUsername)
138
139                 elif self.type == self.SSH:
140                         if username is not None:
141                                 transport = pyssh.Ssh(username, host)
142                                 transport.set_debuglevel(self.verbose)
143                                 transport.open()
144                                 # TODO: have an ssh set_debuglevel() also...
145                         else:
146                                 raise Exception("Username cannot be None for ssh transport.")
147                 elif self.type == self.HTTP:
148                         self.url = "http://%s:%d/" % (host,80)
149                         uri = "%s:%d" % (host,80)
150
151                         # create authinfo
152                         authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
153                         authinfo.add_password (None, uri, username, password)
154                         authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
155
156                         transport = urllib2.build_opener(authhandler)
157
158                 else:
159                         raise Exception("Unknown transport type: %s" % self.type)
160
161                 self.transport = transport
162                 return True
163
164         def close(self):
165                 if self.type == self.TELNET:
166                         self.transport.close() 
167                 elif self.type == self.SSH:
168                         self.transport.close() 
169                 elif self.type == self.HTTP:
170                         pass
171                 else:
172                         raise Exception("Unknown transport type %s" % self.type)
173                 self.transport = None
174
175         def sendHTTP(self, resource, data):
176                 if self.verbose:
177                         print "POSTing '%s' to %s" % (data,self.url + resource)
178
179                 try:
180                         f = self.transport.open(self.url + resource ,data)
181                         r = f.read()
182                         if self.verbose:
183                                 print r
184
185                 except urllib2.URLError,err:
186                         logger.info('Could not open http connection', err)
187                         return "http transport error"
188
189                 return 0
190
191         def sendPassword(self, password, prompt=None):
192                 if self.type == self.TELNET:
193                         if prompt == None:
194                                 self.ifThenSend("Password", password, ExceptionPassword)
195                         else:
196                                 self.ifThenSend(prompt, password, ExceptionPassword)
197                 elif self.type == self.SSH:
198                         self.ifThenSend("password:", password, ExceptionPassword)
199                 elif self.type == self.HTTP:
200                         pass
201                 else:
202                         raise Exception("Unknown transport type: %s" % self.type)
203
204         def ifThenSend(self, expected, buffer, ErrorClass=ExceptionPrompt):
205
206                 if self.transport != None:
207                         output = self.transport.read_until(expected, self.TELNET_TIMEOUT)
208                         if output.find(expected) == -1:
209                                 raise ErrorClass, "'%s' not found" % expected
210                         else:
211                                 self.transport.write(buffer + "\r\n")
212                 else:
213                         raise ExceptionNoTransport("transport object is type None")
214
215         def ifElse(self, expected, ErrorClass):
216                 try:
217                         self.transport.read_until(expected, self.TELNET_TIMEOUT)
218                 except:
219                         raise ErrorClass("Could not find '%s' within timeout" % expected)
220                         
221
222 class PCUControl(Transport,PCUModel,PCURecord):
223         def __init__(self, plc_pcu_record, verbose, supported_ports=[]):
224                 PCUModel.__init__(self, plc_pcu_record)
225                 PCURecord.__init__(self, plc_pcu_record)
226                 if self.portstatus:
227                         if '22' in supported_ports and self.portstatus['22'] == "open":
228                                 type = Transport.SSH
229                         elif '23' in supported_ports and self.portstatus['23'] == "open":
230                                 type = Transport.TELNET
231                         elif '80' in supported_ports and self.portstatus['80'] == "open":
232                                 type = Transport.HTTP
233                         elif '443' in supported_ports and self.portstatus['443'] == "open":
234                                 type = Transport.HTTP
235                         elif '5869' in supported_ports and self.portstatus['5869'] == "open":
236                                 # For DRAC cards.  not sure how much it's used in the
237                                 # protocol.. but racadm opens this port.
238                                 type = Transport.HTTP
239                         else:
240                                 raise ExceptionPort("Unsupported Port: No transport from open ports")
241                 Transport.__init__(self, type, verbose)
242
243         def run(self, node_port, dryrun):
244                 """ This function is to be defined by the specific PCU instance.  """
245                 pass
246                 
247         def reboot(self, node_port, dryrun):
248                 try:
249                         return self.run(node_port, dryrun)
250                 except ExceptionNotFound, err:
251                         return "error: " + str(err)
252                 except ExceptionPassword, err:
253                         return "password exception: " + str(err)
254                 except ExceptionTimeout, err:
255                         return "timeout exception: " + str(err)
256                 except ExceptionUsername, err:
257                         return "exception: no username prompt: " + str(err)
258                 except ExceptionSequence, err:
259                         return "sequence error: " + str(err)
260                 except ExceptionPrompt, err:
261                         return "prompt exception: " + str(err)
262                 except ExceptionPort, err:
263                         return "no ports exception: " + str(err)
264                 except socket.error, err:
265                         return "socket error: timeout: " + str(err)
266                 except EOFError, err:
267                         if self.verbose:
268                                 logger.debug("reboot: EOF")
269                                 logger.debug(err)
270                         self.transport.close()
271                         import traceback
272                         traceback.print_exc()
273                         return "EOF connection reset" + str(err)
274                 #except Exception, err:
275                 #       if self.verbose:
276                 #               logger.debug("reboot: Exception")
277                 #               logger.debug(err)
278                 #       if self.transport:
279                 #               self.transport.close()
280                 #       import traceback
281                 #       traceback.print_exc()
282                 #       return  "generic exception; unknown problem."
283
284                 
285 class IPAL(PCUControl):
286         def run(self, node_port, dryrun):
287                 self.open(self.host)
288
289                 # XXX Some iPals require you to hit Enter a few times first
290                 self.ifThenSend("Password >", "\r\n\r\n", ExceptionNotFound)
291
292                 # Login
293                 self.ifThenSend("Password >", self.password, ExceptionPassword)
294                 self.transport.write("\r\n\r\n")
295
296                 if not dryrun: # P# - Pulse relay
297                         self.ifThenSend("Enter >", 
298                                                         "P%d" % node_port, 
299                                                         ExceptionNotFound)
300                 # Get the next prompt
301                 self.ifElse("Enter >", ExceptionTimeout)
302
303                 self.close()
304                 return 0
305
306 def ipal_reboot(ip, password, port, dryrun):
307         global verbose
308         global plc_lock
309         telnet = None
310
311         try:
312                 #plc_lock.acquire()
313                 #print "lock acquired"
314
315                 #try:
316                         #telnet = telnetlib.Telnet(ip) # , timeout=TELNET_TIMEOUT)
317                 telnet = telnetlib.Telnet(ip, timeout=TELNET_TIMEOUT)
318                 #except:
319                 #       import traceback
320                 #       traceback.print_exc()
321
322
323                 telnet.set_debuglevel(verbose)
324
325                 # XXX Some iPals require you to hit Enter a few times first
326                 telnet_answer(telnet, "Password >", "\r\n\r\n")
327
328                 # Login
329                 telnet_answer(telnet, "Password >", password)
330
331                 # XXX Some iPals require you to hit Enter a few times first
332                 telnet.write("\r\n\r\n")
333
334                 # P# - Pulse relay
335                 if not dryrun:
336                         telnet_answer(telnet, "Enter >", "P%d" % port)
337
338                 telnet.read_until("Enter >", TELNET_TIMEOUT)
339
340                 # Close
341                 telnet.close()
342
343                 #print "lock released"
344                 #plc_lock.release()
345                 return 0
346
347         except EOFError, err:
348                 if verbose:
349                         logger.debug("ipal_reboot: EOF")
350                         logger.debug(err)
351                 telnet.close()
352                 import traceback
353                 traceback.print_exc()
354                 #print "lock released"
355                 #plc_lock.release()
356                 return errno.ECONNRESET
357         except socket.error, err:
358                 logger.debug("ipal_reboot: Socket Error")
359                 logger.debug(err)
360                 import traceback
361                 traceback.print_exc()
362
363                 return errno.ETIMEDOUT
364                 
365         except Exception, err:
366                 if verbose:
367                         logger.debug("ipal_reboot: Exception")
368                         logger.debug(err)
369                 if telnet:
370                         telnet.close()
371                 import traceback
372                 traceback.print_exc()
373                 #print "lock released"
374                 #plc_lock.release()
375                 return  "ipal error"
376
377 class APCEurope(PCUControl):
378         def run(self, node_port, dryrun):
379                 self.open(self.host, self.username)
380                 self.sendPassword(self.password)
381
382                 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
383                 self.ifThenSend("\r\n> ", "2")
384                 self.ifThenSend("\r\n> ", str(node_port))
385                 # 3- Immediate Reboot             
386                 self.ifThenSend("\r\n> ", "3")
387
388                 if not dryrun:
389                         self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel", 
390                                                         "YES\r\n",
391                                                         ExceptionSequence)
392                 else:
393                         self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel", 
394                                                         "", ExceptionSequence)
395                 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
396
397                 self.close()
398                 return 0
399
400 class APCFolsom(PCUControl):
401         def run(self, node_port, dryrun):
402                 self.open(self.host, self.username)
403                 self.sendPassword(self.password)
404
405                 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
406                 self.ifThenSend("\r\n> ", "2")
407                 self.ifThenSend("\r\n> ", "1")
408                 self.ifThenSend("\r\n> ", str(node_port))
409                 self.ifThenSend("\r\n> ", "1")
410
411                 # 3- Immediate Reboot             
412                 self.ifThenSend("\r\n> ", "3")
413
414                 if not dryrun:
415                         self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel", 
416                                                         "YES\r\n",
417                                                         ExceptionSequence)
418                 else:
419                         self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel", 
420                                                         "", ExceptionSequence)
421                 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
422
423                 self.close()
424                 return 0
425
426 class APCMaster(PCUControl):
427         def run(self, node_port, dryrun):
428                 self.open(self.host, self.username)
429                 self.sendPassword(self.password)
430
431                 # 1- Device Manager
432                 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
433                 # 3- Outlet Control/Config
434                 self.ifThenSend("\r\n> ", "3")
435                 # n- Outlet n
436                 self.ifThenSend("\r\n> ", str(node_port))
437                 # 1- Control Outlet
438                 self.ifThenSend("\r\n> ", "1")
439                 # 3- Immediate Reboot             
440                 self.ifThenSend("\r\n> ", "3")
441
442                 if not dryrun:
443                         self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel", 
444                                                         "YES\r\n",
445                                                         ExceptionSequence)
446                 else:
447                         self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel", 
448                                                         "", ExceptionSequence)
449                 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
450
451                 self.close()
452                 return 0
453
454 class APC(PCUControl):
455         def __init__(self, plc_pcu_record, verbose):
456                 PCUControl.__init__(self, plc_pcu_record, verbose)
457
458                 self.master = APCMaster(plc_pcu_record, verbose)
459                 self.folsom = APCFolsom(plc_pcu_record, verbose)
460                 self.europe = APCEurope(plc_pcu_record, verbose)
461
462         def run(self, node_port, dryrun):
463                 try_again = True
464                 sleep_time = 1
465
466                 for pcu in [self.master, self.europe, self.folsom]:
467                         if try_again:
468                                 try:
469                                         print "-*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*"
470                                         try_again = False
471                                         print "sleeping 5"
472                                         time.sleep(sleep_time)
473                                         ret = pcu.reboot(node_port, dryrun)
474                                 except ExceptionSequence, err:
475                                         del pcu
476                                         sleep_time = 130
477                                         try_again = True
478
479                 if try_again:
480                         return "Unknown reboot sequence for APC PCU"
481                 else:
482                         return ret
483
484 class DRACRacAdm(PCUControl):
485         def run(self, node_port, dryrun):
486
487                 print "trying racadm_reboot..."
488                 racadm_reboot(self.host, self.username, self.password, node_port, dryrun)
489
490                 return 0
491
492 class DRAC(PCUControl):
493         def run(self, node_port, dryrun):
494                 self.open(self.host, self.username)
495                 self.sendPassword(self.password)
496
497                 print "logging in..."
498                 self.transport.write("\r\n")
499                 # Testing Reboot ?
500                 if dryrun:
501                         self.ifThenSend("[%s]#" % self.username, "getsysinfo")
502                 else:
503                         # Reset this machine
504                         self.ifThenSend("[%s]#" % self.username, "serveraction powercycle")
505
506                 self.ifThenSend("[%s]#" % self.username, "exit")
507
508                 self.close()
509                 return 0
510
511 class HPiLO(PCUControl):
512         def run(self, node_port, dryrun):
513                 self.open(self.host, self.username)
514                 self.sendPassword(self.password)
515
516                 # </>hpiLO-> 
517                 self.ifThenSend("</>hpiLO->", "cd system1")
518
519                 # Reboot Outlet  N        (Y/N)?
520                 if dryrun:
521                         self.ifThenSend("</system1>hpiLO->", "POWER")
522                 else:
523                         # Reset this machine
524                         self.ifThenSend("</system1>hpiLO->", "reset")
525
526                 self.ifThenSend("</system1>hpiLO->", "exit")
527
528                 self.close()
529                 return 0
530
531                 
532 class HPiLOHttps(PCUControl):
533         def run(self, node_port, dryrun):
534
535                 cmd = "cmdhttps/locfg.pl -s %s -f %s -u %s -p %s" % (
536                                         self.host, "iloxml/Get_Network.xml", 
537                                         self.username, self.password)
538                 p_ilo  = Popen(cmd, stdout=PIPE, shell=True)
539                 cmd2 = "/bin/grep 'MESSAGE' | /bin/grep -v 'No error'"
540                 p_grep = Popen(cmd2, stdin=p_ilo.stdout, stdout=PIPE, stderr=PIPE, shell=True)
541                 sout, serr = p_grep.communicate()
542
543                 p_ilo.wait()
544                 p_grep.wait()
545                 if sout.strip() != "":
546                         print "sout: %s" % sout.strip()
547                         return sout.strip()
548
549                 if not dryrun:
550                         cmd = "cmdhttps/locfg.pl -s %s -f %s -u %s -p %s" % (
551                                         self.host, "iloxml/Reset_Server.xml", 
552                                         self.username, self.password)
553                         print cmd
554                         p_ilo = Popen(cmd, stdin=PIPE, stdout=PIPE, shell=True)
555                         cmd2 = "/bin/grep 'MESSAGE' | /bin/grep -v 'No error'"
556                         print cmd2
557                         p_grep = Popen(cmd2, stdin=p_ilo.stdout, stdout=PIPE, stderr=PIPE, shell=True)
558                         sout, serr = p_grep.communicate()
559                         p_ilo.wait()
560                         p_grep.wait()
561
562                         if sout.strip() != "":
563                                 print "sout: %s" % sout.strip()
564                                 return sout.strip()
565
566                 return 0
567
568 class BayTechGeorgeTown(PCUControl):
569         def run(self, node_port, dryrun):
570                 self.open(self.host, self.username, None, "Enter user name:")
571                 self.sendPassword(self.password, "Enter Password:")
572
573                 #self.ifThenSend("RPC-16>", "Status")
574
575                 self.ifThenSend("RPC-16>", "Reboot %d" % node_port)
576
577                 # Reboot Outlet  N        (Y/N)?
578                 if dryrun:
579                         self.ifThenSend("(Y/N)?", "N")
580                 else:
581                         self.ifThenSend("(Y/N)?", "Y")
582                 self.ifThenSend("RPC-16>", "")
583
584                 self.close()
585                 return 0
586
587 class BayTechCtrlC(PCUControl):
588         """
589                 For some reason, these units let you log in fine, but they hang
590                 indefinitely, unless you send a Ctrl-C after the password.  No idea
591                 why.
592         """
593         def run(self, node_port, dryrun):
594                 print "BayTechCtrlC %s" % self.host
595                 self.open(self.host, self.username)
596                 self.sendPassword(self.password)
597
598                 #self.transport.write('\ 3')
599                 self.transport.write("\r\n")
600                 self.transport.write(pyssh.CTRL_C)
601                 #self.transport.write(chr(3))
602                 #self.transport.write(chr(24))
603                 #self.transport.write(chr(26))
604                 #self.transport.write('\18')
605                 # Control Outlets  (5 ,1).........5
606                 self.ifThenSend("Enter Request :", "5")
607
608                 # Reboot N
609                 try:
610                         self.ifThenSend("DS-RPC>", "Reboot %d" % node_port)
611                 except ExceptionNotFound, msg:
612                         # one machine is configured to ask for a username,
613                         # even after login...
614                         print "msg: %s" % msg
615                         self.transport.write(self.username + "\r\n")
616                         self.ifThenSend("DS-RPC>", "Reboot %d" % node_port)
617                         
618
619                 # Reboot Outlet  N        (Y/N)?
620                 if dryrun:
621                         self.ifThenSend("(Y/N)?", "N")
622                 else:
623                         self.ifThenSend("(Y/N)?", "Y")
624                 self.ifThenSend("DS-RPC>", "")
625
626                 self.close()
627                 return 0
628
629 class BayTech(PCUControl):
630         def run(self, node_port, dryrun):
631                 self.open(self.host, self.username)
632                 self.sendPassword(self.password)
633
634                 # Control Outlets  (5 ,1).........5
635                 self.ifThenSend("Enter Request :", "5")
636
637                 # Reboot N
638                 try:
639                         self.ifThenSend("DS-RPC>", "Reboot %d" % node_port)
640                 except ExceptionNotFound, msg:
641                         # one machine is configured to ask for a username,
642                         # even after login...
643                         print "msg: %s" % msg
644                         self.transport.write(self.username + "\r\n")
645                         self.ifThenSend("DS-RPC>", "Reboot %d" % node_port)
646                         
647
648                 # Reboot Outlet  N        (Y/N)?
649                 if dryrun:
650                         self.ifThenSend("(Y/N)?", "N")
651                 else:
652                         self.ifThenSend("(Y/N)?", "Y")
653                 self.ifThenSend("DS-RPC>", "")
654
655                 self.close()
656                 return 0
657
658 class ePowerSwitchGood(PCUControl):
659         # NOTE:
660         #               The old code used Python's HTTPPasswordMgrWithDefaultRealm()
661         #               For some reason this both doesn't work and in some cases, actually
662         #               hangs the PCU.  Definitely not what we want.
663         #               
664         #               The code below is much simpler.  Just letting things fail first,
665         #               and then, trying again with authentication string in the header.
666         #               
667         def run(self, node_port, dryrun):
668                 self.transport = None
669                 self.url = "http://%s:%d/" % (self.host,80)
670                 uri = "%s:%d" % (self.host,80)
671
672                 req = urllib2.Request(self.url)
673                 try:
674                         handle = urllib2.urlopen(req)
675                 except IOError, e:
676                         # NOTE: this is expected to fail initially
677                         pass
678                 else:
679                         print self.url
680                         print "-----------"
681                         print handle.read()
682                         print "-----------"
683                         return "ERROR: not protected by HTTP authentication"
684
685                 if not hasattr(e, 'code') or e.code != 401:
686                         return "ERROR: failed for: %s" % str(e)
687
688                 base64data = base64.encodestring("%s:%s" % (self.username, self.password))[:-1]
689                 # NOTE: assuming basic realm authentication.
690                 authheader = "Basic %s" % base64data
691                 req.add_header("Authorization", authheader)
692
693                 try:
694                         f = urllib2.urlopen(req)
695                 except IOError, e:
696                         # failing here means the User/passwd is wrong (hopefully)
697                         raise ExceptionPassword("Incorrect username/password")
698
699                 # TODO: after verifying that the user/password is correct, we should
700                 # actually reboot the given node.
701
702                 if not dryrun:
703                         # add data to handler,
704                         # fetch url one more time on cmd.html, econtrol.html or whatever.
705                         pass
706
707                 if self.verbose: print f.read()
708
709                 self.close()
710                 return 0
711
712
713 class ePowerSwitchOld(PCUControl):
714         def run(self, node_port, dryrun):
715                 self.url = "http://%s:%d/" % (self.host,80)
716                 uri = "%s:%d" % (self.host,80)
717
718                 # create authinfo
719                 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
720                 authinfo.add_password (None, uri, self.username, self.password)
721                 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
722
723                 # NOTE: it doesn't seem to matter whether this authinfo is here or not.
724                 transport = urllib2.build_opener(authinfo)
725                 f = transport.open(self.url)
726                 if self.verbose: print f.read()
727
728                 if not dryrun:
729                         transport = urllib2.build_opener(authhandler)
730                         f = transport.open(self.url + "cmd.html", "P%d=r" % node_port)
731                         if self.verbose: print f.read()
732
733                 self.close()
734                 return 0
735
736 class ePowerSwitch(PCUControl):
737         def run(self, node_port, dryrun):
738                 self.url = "http://%s:%d/" % (self.host,80)
739                 uri = "%s:%d" % (self.host,80)
740
741                 # TODO: I'm still not sure what the deal is here.
742                 #               two independent calls appear to need to be made before the
743                 #               reboot will succeed.  It doesn't seem to be possible to do
744                 #               this with a single call.  I have no idea why.
745
746                 # create authinfo
747                 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
748                 authinfo.add_password (None, uri, self.username, self.password)
749                 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
750
751                 # NOTE: it doesn't seem to matter whether this authinfo is here or not.
752                 transport = urllib2.build_opener()
753                 f = transport.open(self.url + "elogin.html", "pwd=%s" % self.password)
754                 if self.verbose: print f.read()
755
756                 if not dryrun:
757                         transport = urllib2.build_opener(authhandler)
758                         f = transport.open(self.url + "econtrol.html", "P%d=r" % node_port)
759                         if self.verbose: print f.read()
760
761                 #       data= "P%d=r" % node_port
762                 #self.open(self.host, self.username, self.password)
763                 #self.sendHTTP("elogin.html", "pwd=%s" % self.password)
764                 #self.sendHTTP("econtrol.html", data)
765                 #self.sendHTTP("cmd.html", data)
766
767                 self.close()
768                 return 0
769                 
770
771 ### rebooting european BlackBox PSE boxes
772 # Thierry Parmentelat - May 11 2005
773 # tested on 4-ports models known as PSE505-FR
774 # uses http to POST a data 'P<port>=r'
775 # relies on basic authentication within http1.0
776 # first curl-based script was
777 # curl --http1.0 --basic --user <username>:<password> --data P<port>=r \
778 #       http://<hostname>:<http_port>/cmd.html && echo OK
779
780 def bbpse_reboot (pcu_ip,username,password,port_in_pcu,http_port, dryrun):
781
782         global verbose
783
784         url = "http://%s:%d/cmd.html" % (pcu_ip,http_port)
785         data= "P%d=r" % port_in_pcu
786         if verbose:
787                 logger.debug("POSTing '%s' on %s" % (data,url))
788
789         authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
790         uri = "%s:%d" % (pcu_ip,http_port)
791         authinfo.add_password (None, uri, username, password)
792         authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
793
794         opener = urllib2.build_opener(authhandler)
795         urllib2.install_opener(opener)
796
797         if (dryrun):
798                 return 0
799
800         try:
801                 f = urllib2.urlopen(url,data)
802
803                 r= f.read()
804                 if verbose:
805                         logger.debug(r)
806                 return 0
807
808         except urllib2.URLError,err:
809                 logger.info('Could not open http connection', err)
810                 return "bbpse error"
811
812 ### rebooting x10toggle based systems addressed by port
813 # Marc E. Fiuczynski - May 31 2005
814 # tested on 4-ports models known as PSE505-FR
815 # uses ssh and password to login to an account
816 # that will cause the system to be powercycled.
817
818 def x10toggle_reboot(ip, username, password, port, dryrun):
819         global verbose
820
821         ssh = None
822         try:
823                 ssh = pyssh.Ssh(username, ip)
824                 ssh.open()
825
826                 # Login
827                 telnet_answer(ssh, "password:", password)
828
829                 if not dryrun:
830                         # Reboot
831                         telnet_answer(ssh, "x10toggle>", "A%d" % port)
832
833                 # Close
834                 output = ssh.close()
835                 if verbose:
836                         logger.debug(output)
837                 return 0
838
839         except Exception, err:
840                 if verbose:
841                         logger.debug(err)
842                 if ssh:
843                         output = ssh.close()
844                         if verbose:
845                                 logger.debug(output)
846                 return errno.ETIMEDOUT
847
848 ### rebooting Dell systems via RAC card
849 # Marc E. Fiuczynski - June 01 2005
850 # tested with David Lowenthal's itchy/scratchy nodes at UGA
851 #
852
853 def runcmd(command, args, username, password, timeout = None):
854
855         result = [None]
856         result_ready = threading.Condition()
857
858         def set_result(x):
859
860                 result_ready.acquire()
861                 try:
862                         result[0] = x
863                 finally:
864                         result_ready.notify()
865                         result_ready.release()
866
867         def do_command(command, username, password):
868
869                 try:
870                         # Popen4 is a popen-type class that combines stdout and stderr
871                         p = popen2.Popen4(command)
872
873                         # read all output data
874                         p.tochild.write("%s\n" % username)
875                         p.tochild.write("%s\n" % password)
876                         p.tochild.close()
877                         data = p.fromchild.read()
878
879                         while True:
880                                 # might get interrupted by a signal in poll() or waitpid()
881                                 try:
882                                         retval = p.wait()
883                                         set_result((retval, data))
884                                         break
885                                 except OSError, ex:
886                                         if ex.errno == errno.EINTR:
887                                                 continue
888                                         raise ex
889                 except Exception, ex:
890                         set_result(ex)
891
892         if args:
893                 command = " ".join([command] + args)
894
895         worker = threading.Thread(target = do_command, args = (command, username, password, ))
896         worker.setDaemon(True)
897         result_ready.acquire()
898         worker.start()
899         result_ready.wait(timeout)
900         try:
901                 if result == [None]:
902                         raise Exception, "command timed-out: '%s'" % command
903         finally:
904                 result_ready.release()
905         result = result[0]
906
907         if isinstance(result, Exception):
908                 raise result
909         else:
910                 (retval, data) = result
911                 if os.WIFEXITED(retval) and os.WEXITSTATUS(retval) == 0:
912                         return data
913                 else:
914                         out = "system command ('%s') " % command
915                         if os.WIFEXITED(retval):
916                                 out += "failed, rc = %d" % os.WEXITSTATUS(retval)
917                         else:
918                                 out += "killed by signal %d" % os.WTERMSIG(retval)
919                         if data:
920                                 out += "; output follows:\n" + data
921                         raise Exception, out
922
923 def racadm_reboot(ip, username, password, port, dryrun):
924         global verbose
925
926         try:
927                 cmd = "/usr/sbin/racadm"
928                 os.stat(cmd)
929                 if not dryrun:
930                         output = runcmd(cmd, ["-r %s -i serveraction powercycle" % ip],
931                                 username, password)
932                 else:
933                         output = runcmd(cmd, ["-r %s -i getsysinfo" % ip],
934                                 username, password)
935
936                 print "RUNCMD: %s" % output
937                 if verbose:
938                         logger.debug(output)
939                 return 0
940
941         except Exception, err:
942                 logger.debug("runcmd raised exception %s" % err)
943                 if verbose:
944                         logger.debug(err)
945                 return -1
946
947 def pcu_name(pcu):
948         if pcu['hostname'] is not None and pcu['hostname'] is not "":
949                 return pcu['hostname']
950         elif pcu['ip'] is not None and pcu['ip'] is not "":
951                 return pcu['ip']
952         else:
953                 return None
954
955 def get_pcu_values(pcu_id):
956         # TODO: obviously, this shouldn't be loaded each time...
957         import soltesz
958         fb =soltesz.dbLoad("findbadpcus")
959
960         try:
961                 values = fb['nodes']["id_%s" % pcu_id]['values']
962         except:
963                 values = None
964
965         return values
966
967 def check_open_port(values, port_list):
968         ret = False
969
970         if 'portstatus' in values:
971                 for port in port_list:
972                         if      port in values['portstatus'] and \
973                                 values['portstatus'][port] == "open":
974
975                                 ret = True
976         
977         return ret
978
979 def reboot(nodename):
980         return reboot_policy(nodename, True, False)
981         
982 def reboot_policy(nodename, continue_probe, dryrun):
983         global verbose
984
985         pcu = plc.getpcu(nodename)
986         if not pcu:
987                 return False # "%s has no pcu" % nodename
988
989         values = get_pcu_values(pcu['pcu_id'])
990         if values == None:
991                 return False #"no info for pcu_id %s" % pcu['pcu_id']
992         
993         # Try the PCU first
994         logger.debug("Trying PCU %s %s" % (pcu['hostname'], pcu['model']))
995
996         ret = reboot_test(nodename, values, continue_probe, verbose, dryrun)
997         print ret
998
999         if ret != 0:
1000                 return False
1001         else:
1002                 return True
1003
1004 def reboot_test(nodename, values, continue_probe, verbose, dryrun):
1005         rb_ret = ""
1006
1007         try:
1008                 # DataProbe iPal (many sites)
1009                 if  continue_probe and values['model'].find("Dataprobe IP-41x/IP-81x") >= 0:
1010                         ipal = IPAL(values, verbose, ['23'])
1011                         rb_ret = ipal.reboot(values[nodename], dryrun)
1012                                 
1013                 # APC Masterswitch (Berkeley)
1014                 elif continue_probe and values['model'].find("APC AP79xx/Masterswitch") >= 0:
1015
1016                         # TODO: make a more robust version of APC
1017                         if values['pcu_id'] in [1163,1055,1111,1231,1113,1127,1128,1148]:
1018                                 apc = APCEurope(values, verbose, ['22', '23'])
1019                                 rb_ret = apc.reboot(values[nodename], dryrun)
1020
1021                         elif values['pcu_id'] in [1173,1221,1220,1225]:
1022                                 apc = APCFolsom(values, verbose, ['22', '23'])
1023                                 rb_ret = apc.reboot(values[nodename], dryrun)
1024
1025                         else:
1026                                 apc = APCMaster(values, verbose, ['22', '23'])
1027                                 rb_ret = apc.reboot(values[nodename], dryrun)
1028
1029                 # BayTech DS4-RPC
1030                 elif continue_probe and values['model'].find("Baytech DS4-RPC") >= 0:
1031                         if values['pcu_id'] in [1041,1209,1025,1052,1057]:
1032                                 # These  require a 'ctrl-c' to be sent... 
1033                                 baytech = BayTechCtrlC(values, verbose, ['22', '23'])
1034                                 rb_ret = baytech.reboot(values[nodename], dryrun)
1035
1036                         elif values['pcu_id'] in [1012]:
1037                                 # This pcu sometimes doesn't present the 'Username' prompt,
1038                                 # unless you immediately try again...
1039                                 try:
1040                                         baytech = BayTechGeorgeTown(values, verbose, ['22', '23'])
1041                                         rb_ret = baytech.reboot(values[nodename], dryrun)
1042                                 except:
1043                                         baytech = BayTechGeorgeTown(values, verbose, ['22', '23'])
1044                                         rb_ret = baytech.reboot(values[nodename], dryrun)
1045                         else:
1046                                 baytech = BayTech(values, verbose, ['22', '23'])
1047                                 rb_ret = baytech.reboot(values[nodename], dryrun)
1048
1049                 # iLO
1050                 elif continue_probe and values['model'].find("HP iLO") >= 0:
1051                         try:
1052                                 hpilo = HPiLO(values, verbose, ['22'])
1053                                 rb_ret = hpilo.reboot(0, dryrun)
1054                                 if rb_ret != 0:
1055                                         hpilo = HPiLOHttps(values, verbose, ['443'])
1056                                         rb_ret = hpilo.reboot(0, dryrun)
1057                         except:
1058                                 hpilo = HPiLOHttps(values, verbose, ['443'])
1059                                 rb_ret = hpilo.reboot(0, dryrun)
1060
1061                 # DRAC ssh
1062                 elif continue_probe and values['model'].find("Dell RAC") >= 0:
1063                         # TODO: I don't think DRACRacAdm will throw an exception for the
1064                         # default method to catch...
1065                         try:
1066                                 drac = DRACRacAdm(values, verbose, ['443', '5869'])
1067                                 rb_ret = drac.reboot(0, dryrun)
1068                         except:
1069                                 drac = DRAC(values, verbose, ['22'])
1070                                 rb_ret = drac.reboot(0, dryrun)
1071
1072                 # BlackBox PSExxx-xx (e.g. PSE505-FR)
1073                 elif continue_probe and \
1074                         (values['model'].find("BlackBox PS5xx") >= 0 or
1075                          values['model'].find("ePowerSwitch 1/4/8x") >=0 ):
1076
1077                         # TODO: allow a different port than http 80.
1078                         if values['pcu_id'] in [1089, 1071, 1046, 1035, 1118]:
1079                                 eps = ePowerSwitchGood(values, verbose, ['80'])
1080                         elif values['pcu_id'] in [1003]:
1081                                 eps = ePowerSwitch(values, verbose, ['80'])
1082                         else:
1083                                 eps = ePowerSwitchGood(values, verbose, ['80'])
1084
1085                         rb_ret = eps.reboot(values[nodename], dryrun)
1086
1087                 elif continue_probe:
1088                         rb_ret = "Unsupported_PCU"
1089
1090                 elif continue_probe == False:
1091                         if 'portstatus' in values:
1092                                 rb_ret = "NetDown"
1093                         else:
1094                                 rb_ret = "Not_Run"
1095                 else:
1096                         rb_ret = -1
1097
1098         except ExceptionPort, err:
1099                 rb_ret = str(err)
1100
1101         return rb_ret
1102         # ????
1103         #elif continue_probe and values['protocol'] == "racadm" and \
1104         #               values['model'] == "RAC":
1105         #       rb_ret = racadm_reboot(pcu_name(values),
1106         #                                                                 values['username'],
1107         #                                                                 values['password'],
1108         #                                                                 pcu[nodename],
1109         #                                                                 dryrun)
1110
1111 # Returns true if rebooted via PCU
1112 def reboot_old(nodename, dryrun):
1113         pcu = plc.getpcu(nodename)
1114         if not pcu:
1115                 plc.nodePOD(nodename)
1116                 return False
1117         # Try the PCU first
1118         logger.debug("Trying PCU %s %s" % (pcu['hostname'], pcu['model']))
1119
1120         # APC Masterswitch (Berkeley)
1121         if pcu['model'] == "APC Masterswitch":
1122                 err = apc_reboot(pcu['ip'], pcu['username'],pcu['password'], 
1123                                 pcu[nodename], pcu['protocol'], dryrun)
1124
1125         # DataProbe iPal (many sites)
1126         elif pcu['protocol'] == "telnet" and pcu['model'].find("IP-4") >= 0:
1127                 err = ipal_reboot(pcu['ip'],pcu['password'], pcu[nodename], dryrun)
1128
1129         # BayTech DS4-RPC
1130         elif pcu['protocol'] == "ssh" and \
1131         (pcu['model'].find("Baytech") >= 0 or pcu['model'].find("DS4") >= 0):
1132                 err = baytech_reboot(pcu['ip'], pcu['username'],pcu['password'], pcu[nodename], dryrun)
1133
1134         # BlackBox PSExxx-xx (e.g. PSE505-FR)
1135         elif pcu['protocol'] == "http" and (pcu['model'] == "bbpse"):
1136                 err = bbpse_reboot(pcu['ip'], pcu['username'], pcu['password'], pcu[nodename],80, dryrun)
1137
1138         # x10toggle
1139         elif pcu['protocol'] == "ssh" and (pcu['model'] == "x10toggle"):
1140                 err = x10toggle_reboot(pcu['ip'], pcu['username'],pcu['password'], pcu[nodename], dryrun)
1141
1142         # 
1143         elif pcu['protocol'] == "racadm" and (pcu['model'] == "RAC"):
1144                 err = racadm_reboot(pcu['ip'], pcu['username'],pcu['password'], pcu_[nodename], dryrun)
1145
1146         # Unknown or unsupported
1147         else:
1148                 err = errno.EPROTONOSUPPORT
1149                 return False
1150         return True 
1151
1152
1153 def main():
1154         logger.setLevel(logging.DEBUG)
1155         ch = logging.StreamHandler()
1156         ch.setLevel(logging.DEBUG)
1157         formatter = logging.Formatter('LOGGER - %(message)s')
1158         ch.setFormatter(formatter)
1159         logger.addHandler(ch)
1160
1161         try:
1162                 reboot("planetlab2.cs.uchicago.edu")
1163                 reboot("alice.cs.princeton.edu")
1164         except Exception, err:
1165                 print err
1166
1167 if __name__ == '__main__':
1168         import plc
1169         logger = logging.getLogger("monitor")
1170         main()