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