3 # Reboot specified nodes
9 import errno, time, traceback
12 import threading, popen2
16 from subprocess import PIPE, Popen
17 import ssh.pxssh as pxssh
18 import ssh.pexpect as pexpect
22 # Use our versions of telnetlib and pyssh
23 sys.path.insert(0, os.path.dirname(sys.argv[0]))
25 sys.path.insert(0, os.path.dirname(sys.argv[0]) + "/pyssh")
31 # Event class ID from pcu events
32 #NODE_POWER_CONTROL = 3
35 #MONITOR_USER_ID = 11142
38 logger = logging.getLogger("monitor")
42 class ExceptionNoTransport(Exception): pass
43 class ExceptionNotFound(Exception): pass
44 class ExceptionPassword(Exception): pass
45 class ExceptionTimeout(Exception): pass
46 class ExceptionPrompt(Exception): pass
47 class ExceptionSequence(Exception): pass
48 class ExceptionReset(Exception): pass
49 class ExceptionPort(Exception): pass
50 class ExceptionUsername(Exception): pass
52 def telnet_answer(telnet, expected, buffer):
55 output = telnet.read_until(expected, TELNET_TIMEOUT)
57 # logger.debug(output)
58 if output.find(expected) == -1:
59 raise ExceptionNotFound, "'%s' not found" % expected
61 telnet.write(buffer + "\r\n")
64 # PCU has model, host, preferred-port, user, passwd,
66 # This is an object derived directly form the PLCAPI DB fields
68 def __init__(self, plc_pcu_dict):
69 for field in ['username', 'password', 'site_id',
72 'node_ids', 'ports', ]:
73 if field in plc_pcu_dict:
74 self.__setattr__(field, plc_pcu_dict[field])
76 raise Exception("No such field %s in PCU object" % field)
78 # These are the convenience functions build around the PCU object.
80 def __init__(self, plc_pcu_dict):
81 PCU.__init__(self, plc_pcu_dict)
82 self.host = self.pcu_name()
85 if self.hostname is not None and self.hostname is not "":
87 elif self.ip is not None and self.ip is not "":
92 def nodeidToPort(self, node_id):
93 if node_id in self.node_ids:
94 for i in range(0, len(self.node_ids)):
95 if node_id == self.node_ids[i]:
98 raise Exception("No such Node ID: %d" % node_id)
100 # This class captures the observed pcu records from FindBadPCUs.py
102 def __init__(self, pcu_record_dict):
103 for field in ['nodenames', 'portstatus',
106 if field in pcu_record_dict:
107 if field == "reboot":
108 self.__setattr__("reboot_str", pcu_record_dict[field])
110 self.__setattr__(field, pcu_record_dict[field])
112 raise Exception("No such field %s in pcu record dict" % field)
122 def __init__(self, type, verbose):
124 self.verbose = verbose
125 self.transport = None
127 def open(self, host, username=None, password=None, prompt="User Name"):
130 if self.type == self.TELNET:
131 transport = telnetlib.Telnet(host, timeout=self.TELNET_TIMEOUT)
132 transport.set_debuglevel(self.verbose)
133 if username is not None:
134 self.transport = transport
135 self.ifThenSend(prompt, username, ExceptionUsername)
137 elif self.type == self.SSH:
138 if username is not None:
139 transport = pyssh.Ssh(username, host)
140 transport.set_debuglevel(self.verbose)
142 # TODO: have an ssh set_debuglevel() also...
144 raise Exception("Username cannot be None for ssh transport.")
145 elif self.type == self.HTTP:
146 self.url = "http://%s:%d/" % (host,80)
147 uri = "%s:%d" % (host,80)
150 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
151 authinfo.add_password (None, uri, username, password)
152 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
154 transport = urllib2.build_opener(authhandler)
157 raise Exception("Unknown transport type: %s" % self.type)
159 self.transport = transport
163 if self.type == self.TELNET:
164 self.transport.close()
165 elif self.type == self.SSH:
166 self.transport.close()
167 elif self.type == self.HTTP:
170 raise Exception("Unknown transport type %s" % self.type)
171 self.transport = None
173 def sendHTTP(self, resource, data):
175 print "POSTing '%s' to %s" % (data,self.url + resource)
178 f = self.transport.open(self.url + resource ,data)
183 except urllib2.URLError,err:
184 logger.info('Could not open http connection', err)
185 return "http transport error"
189 def sendPassword(self, password, prompt=None):
190 if self.type == self.TELNET:
192 self.ifThenSend("Password", password, ExceptionPassword)
194 self.ifThenSend(prompt, password, ExceptionPassword)
195 elif self.type == self.SSH:
196 self.ifThenSend("password:", password, ExceptionPassword)
197 elif self.type == self.HTTP:
200 raise Exception("Unknown transport type: %s" % self.type)
202 def ifThenSend(self, expected, buffer, ErrorClass=ExceptionPrompt):
204 if self.transport != None:
205 output = self.transport.read_until(expected, self.TELNET_TIMEOUT)
206 if output.find(expected) == -1:
207 raise ErrorClass, "'%s' not found" % expected
209 self.transport.write(buffer + "\r\n")
211 raise ExceptionNoTransport("transport object is type None")
213 def ifElse(self, expected, ErrorClass):
215 self.transport.read_until(expected, self.TELNET_TIMEOUT)
217 raise ErrorClass("Could not find '%s' within timeout" % expected)
220 class PCUControl(Transport,PCUModel,PCURecord):
221 def __init__(self, plc_pcu_record, verbose, supported_ports=[]):
222 PCUModel.__init__(self, plc_pcu_record)
223 PCURecord.__init__(self, plc_pcu_record)
226 if '22' in supported_ports and self.portstatus['22'] == "open":
228 elif '23' in supported_ports and self.portstatus['23'] == "open":
229 type = Transport.TELNET
230 elif '80' in supported_ports and self.portstatus['80'] == "open":
231 type = Transport.HTTP
232 elif '443' in supported_ports and self.portstatus['443'] == "open":
233 type = Transport.HTTP
234 elif '5869' in supported_ports and self.portstatus['5869'] == "open":
235 # For DRAC cards. Racadm opens this port.
236 type = Transport.HTTP
237 elif '9100' in supported_ports and self.portstatus['9100'] == "open":
238 type = Transport.IPAL
239 elif '16992' in supported_ports and self.portstatus['16992'] == "open":
240 type = Transport.HTTP
242 raise ExceptionPort("Unsupported Port: No transport from open ports")
244 raise Exception("No Portstatus: No transport because no open ports")
245 Transport.__init__(self, type, verbose)
247 def run(self, node_port, dryrun):
248 """ This function is to be defined by the specific PCU instance. """
251 def reboot(self, node_port, dryrun):
253 return self.run(node_port, dryrun)
254 except ExceptionNotFound, err:
255 return "error: " + str(err)
256 except ExceptionPassword, err:
257 return "password exception: " + str(err)
258 except ExceptionTimeout, err:
259 return "timeout exception: " + str(err)
260 except ExceptionUsername, err:
261 return "exception: no username prompt: " + str(err)
262 except ExceptionSequence, err:
263 return "sequence error: " + str(err)
264 except ExceptionPrompt, err:
265 return "prompt exception: " + str(err)
266 except ExceptionPort, err:
267 return "no ports exception: " + str(err)
268 except socket.error, err:
269 return "socket error: timeout: " + str(err)
270 except EOFError, err:
272 logger.debug("reboot: EOF")
274 self.transport.close()
276 traceback.print_exc()
277 return "EOF connection reset" + str(err)
279 from nodecommon import email_exception
281 raise Exception('unknown')
283 class IPAL(PCUControl):
285 This now uses a proprietary format for communicating with the PCU. I
286 prefer it to Telnet, and Web access, since it's much lighter weight
287 and, more importantly, IT WORKS!! HHAHHHAHAHAHAHAHA!
290 def format_msg(self, data, cmd):
291 esc = chr(int('1b',16))
292 return "%c%s%c%s%c" % (esc, self.password, esc, data, cmd) # esc, 'q', chr(4))
294 def recv_noblock(self, s, count):
298 # TODO: make sleep backoff, before stopping.
300 ret = s.recv(count, socket.MSG_DONTWAIT)
301 except socket.error, e:
302 if e[0] == errno.EAGAIN:
303 raise Exception(e[1])
305 # TODO: not other exceptions.
309 def run(self, node_port, dryrun):
315 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
318 s.connect((self.host, 9100))
319 except socket.error, e:
321 if e[0] == errno.ECONNREFUSED:
322 # cannot connect to remote host
323 raise Exception(e[1])
325 # TODO: what other conditions are there?
329 print "Checking status"
330 s.send(self.format_msg("", 'O'))
331 ret = self.recv_noblock(s, 8)
332 print "Current status is '%s'" % ret
335 raise Exception("Status returned 'another session already open' on %s %s : %s" % (self.host, node_port, ret))
338 if node_port < len(ret):
339 status = ret[node_port]
347 raise ExceptionPort("IPAL reported 'Cable Error' on %s socket %s : %s" % (self.host, node_port, ret))
349 raise Exception("Unknown status for PCU %s socket %s : %s" % (self.host, node_port, ret))
351 raise Exception("Mismatch between configured port and PCU %s status: %s %s" % (self.host, node_port, ret))
356 print "Pulsing %s" % node_port
357 s.send(self.format_msg("%s" % node_port, 'P'))
359 # NOTE: turn power on ; do not pulse the port.
360 print "Power was off, so turning on ..."
361 s.send(self.format_msg("%s" % node_port, 'E'))
362 #s.send(self.format_msg("%s" % node_port, 'P'))
364 print "Receiving response."
365 ret = self.recv_noblock(s, 8)
366 print "Current status is '%s'" % ret
368 if node_port < len(ret):
369 status = ret[node_port]
377 raise ExceptionPort("IPAL reported 'Cable Error' on %s socket %s : %s" % (self.host, node_port, ret))
379 raise Exception("Unknown status for PCU %s socket %s : %s" % (self.host, node_port, ret))
381 raise Exception("Mismatch between configured port and PCU %s status: %s %s" % (self.host, node_port, ret))
386 return "Failed Power On"
391 # TELNET version of protocol...
392 # #self.open(self.host)
393 # ## XXX Some iPals require you to hit Enter a few times first
394 # #self.ifThenSend("Password >", "\r\n\r\n", ExceptionNotFound)
396 # self.ifThenSend("Password >", self.password, ExceptionPassword)
397 # self.transport.write("\r\n\r\n")
398 # if not dryrun: # P# - Pulse relay
399 # print "node_port %s" % node_port
400 # self.ifThenSend("Enter >",
401 # "P7", # % node_port,
403 # print "send newlines"
404 # self.transport.write("\r\n\r\n")
405 # print "after new lines"
406 # # Get the next prompt
407 # print "wait for enter"
408 # self.ifElse("Enter >", ExceptionTimeout)
413 class APCEurope(PCUControl):
414 def run(self, node_port, dryrun):
415 self.open(self.host, self.username)
416 self.sendPassword(self.password)
418 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
419 self.ifThenSend("\r\n> ", "2")
420 self.ifThenSend("\r\n> ", str(node_port))
421 # 3- Immediate Reboot
422 self.ifThenSend("\r\n> ", "3")
425 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
429 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
430 "", ExceptionSequence)
431 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
436 class APCBrazil(PCUControl):
437 def run(self, node_port, dryrun):
438 self.open(self.host, self.username)
439 self.sendPassword(self.password)
441 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
442 self.ifThenSend("\r\n> ", str(node_port))
443 # 4- Immediate Reboot
444 self.ifThenSend("\r\n> ", "4")
447 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
451 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
452 "", ExceptionSequence)
453 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
458 class APCBerlin(PCUControl):
459 def run(self, node_port, dryrun):
460 self.open(self.host, self.username)
461 self.sendPassword(self.password)
463 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
464 self.ifThenSend("\r\n> ", "2")
465 self.ifThenSend("\r\n> ", "1")
466 self.ifThenSend("\r\n> ", str(node_port))
467 # 3- Immediate Reboot
468 self.ifThenSend("\r\n> ", "3")
471 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
475 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
476 "", ExceptionSequence)
477 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
482 class APCFolsom(PCUControl):
483 def run(self, node_port, dryrun):
484 self.open(self.host, self.username)
485 self.sendPassword(self.password)
487 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
488 self.ifThenSend("\r\n> ", "2")
489 self.ifThenSend("\r\n> ", "1")
490 self.ifThenSend("\r\n> ", str(node_port))
491 self.ifThenSend("\r\n> ", "1")
493 # 3- Immediate Reboot
494 self.ifThenSend("\r\n> ", "3")
497 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
501 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
502 "", ExceptionSequence)
503 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
508 class APCMaster(PCUControl):
509 def run(self, node_port, dryrun):
510 print "Rebooting %s" % self.host
511 self.open(self.host, self.username)
512 self.sendPassword(self.password)
515 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
516 # 3- Outlet Control/Config
517 self.ifThenSend("\r\n> ", "3")
519 self.ifThenSend("\r\n> ", str(node_port))
521 self.ifThenSend("\r\n> ", "1")
522 # 3- Immediate Reboot
523 self.ifThenSend("\r\n> ", "3")
526 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
530 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
531 "", ExceptionSequence)
532 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
537 class APC(PCUControl):
538 def __init__(self, plc_pcu_record, verbose):
539 PCUControl.__init__(self, plc_pcu_record, verbose)
541 self.master = APCMaster(plc_pcu_record, verbose)
542 self.folsom = APCFolsom(plc_pcu_record, verbose)
543 self.europe = APCEurope(plc_pcu_record, verbose)
545 def run(self, node_port, dryrun):
549 for pcu in [self.master, self.europe, self.folsom]:
552 print "-*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*"
555 time.sleep(sleep_time)
556 ret = pcu.reboot(node_port, dryrun)
557 except ExceptionSequence, err:
563 return "Unknown reboot sequence for APC PCU"
567 class IntelAMT(PCUControl):
568 def run(self, node_port, dryrun):
570 cmd = moncommands.CMD()
571 #[cmd_str = "IntelAMTSDK/Samples/RemoteControl/remoteControl"
572 cmd_str = "cmdamt/remoteControl"
575 # NOTE: -p checks the power state of the host.
576 # TODO: parse the output to find out if it's ok or not.
577 cmd_str += " -p http://%s:16992/RemoteControlService -user admin -pass '%s' " % (self.host, self.password )
579 cmd_str += " -A http://%s:16992/RemoteControlService -user admin -pass '%s' " % (self.host, self.password )
582 return cmd.system(cmd_str, self.TELNET_TIMEOUT)
584 class DRACRacAdm(PCUControl):
585 def run(self, node_port, dryrun):
587 print "trying racadm_reboot..."
588 racadm_reboot(self.host, self.username, self.password, node_port, dryrun)
592 class DRAC(PCUControl):
593 def run(self, node_port, dryrun):
594 self.open(self.host, self.username)
595 self.sendPassword(self.password)
597 print "logging in..."
598 self.transport.write("\r\n")
601 self.ifThenSend("[%s]#" % self.username, "getsysinfo")
604 self.ifThenSend("[%s]#" % self.username, "serveraction powercycle")
606 self.ifThenSend("[%s]#" % self.username, "exit")
611 class HPiLO(PCUControl):
612 def run(self, node_port, dryrun):
613 self.open(self.host, self.username)
614 self.sendPassword(self.password)
617 self.ifThenSend("</>hpiLO->", "cd system1")
619 # Reboot Outlet N (Y/N)?
621 self.ifThenSend("</system1>hpiLO->", "POWER")
624 self.ifThenSend("</system1>hpiLO->", "reset")
626 self.ifThenSend("</system1>hpiLO->", "exit")
632 class HPiLOHttps(PCUControl):
633 def run(self, node_port, dryrun):
635 locfg = moncommands.CMD()
636 cmd = "cmdhttps/locfg.pl -s %s -f %s -u %s -p '%s' | grep 'MESSAGE' | grep -v 'No error'" % (
637 self.host, "iloxml/Get_Network.xml",
638 self.username, self.password)
639 sout, serr = locfg.run_noexcept(cmd)
641 if sout.strip() != "":
642 print "sout: %s" % sout.strip()
646 locfg = moncommands.CMD()
647 cmd = "cmdhttps/locfg.pl -s %s -f %s -u %s -p '%s' | grep 'MESSAGE' | grep -v 'No error'" % (
648 self.host, "iloxml/Reset_Server.xml",
649 self.username, self.password)
650 sout, serr = locfg.run_noexcept(cmd)
652 if sout.strip() != "":
653 print "sout: %s" % sout.strip()
657 class BayTechAU(PCUControl):
658 def run(self, node_port, dryrun):
659 self.open(self.host, self.username, None, "Enter user name:")
660 self.sendPassword(self.password, "Enter Password:")
662 #self.ifThenSend("RPC-16>", "Status")
663 self.ifThenSend("RPC3-NC>", "Reboot %d" % node_port)
665 # Reboot Outlet N (Y/N)?
667 self.ifThenSend("(Y/N)?", "N")
669 self.ifThenSend("(Y/N)?", "Y")
670 self.ifThenSend("RPC3-NC>", "")
675 class BayTechGeorgeTown(PCUControl):
676 def run(self, node_port, dryrun):
677 # this initial open/close is to prevent things from raising an
678 # exception. the pcu always is weird during the first connection, and
679 # even if it's not, what does it matter to open a second connection
681 self.open(self.host, self.username, None, "Enter user name:")
684 self.open(self.host, self.username, None, "Enter user name:")
685 self.sendPassword(self.password, "Enter Password:")
687 #self.ifThenSend("RPC-16>", "Status")
689 self.ifThenSend("RPC-16>", "Reboot %d" % node_port)
691 # Reboot Outlet N (Y/N)?
693 self.ifThenSend("(Y/N)?", "N")
695 self.ifThenSend("(Y/N)?", "Y")
696 self.ifThenSend("RPC-16>", "")
701 class BayTechCtrlCUnibe(PCUControl):
703 For some reason, these units let you log in fine, but they hang
704 indefinitely, unless you send a Ctrl-C after the password. No idea
707 def run(self, node_port, dryrun):
708 print "BayTechCtrlC %s" % self.host
710 ssh_options="-o StrictHostKeyChecking=no -o PasswordAuthentication=yes -o PubkeyAuthentication=no"
712 if not s.login(self.host, self.username, self.password, ssh_options):
713 raise ExceptionPassword("Invalid Password")
714 # Otherwise, the login succeeded.
716 # Send a ctrl-c to the remote process.
717 print "sending ctrl-c"
720 # Control Outlets (5 ,1).........5
722 #index = s.expect("Enter Request")
723 index = s.expect(["Enter Request :"])
728 index = s.expect(["DS-RPC>", "Enter user name:"])
730 s.send(self.username + "\r\n")
731 index = s.expect(["DS-RPC>"])
734 print "Reboot %d" % node_port
735 s.send("Reboot %d\r\n" % node_port)
738 index = s.expect(["\(Y/N\)\?", "Port in use", "DS-RPC>"])
747 raise ExceptionPrompt("PCU Reported 'Port in use.'")
749 raise ExceptionSequence("Issued command 'Reboot' failed.")
752 index = s.expect(["DS-RPC>"])
753 #print "got prompt back"
758 raise ExceptionPrompt("EOF before expected Prompt")
759 except pexpect.TIMEOUT:
760 raise ExceptionPrompt("Timeout before expected Prompt")
764 class BayTechCtrlC(PCUControl):
766 For some reason, these units let you log in fine, but they hang
767 indefinitely, unless you send a Ctrl-C after the password. No idea
770 def run(self, node_port, dryrun):
771 print "BayTechCtrlC %s" % self.host
773 ssh_options="-o StrictHostKeyChecking=no -o PasswordAuthentication=yes -o PubkeyAuthentication=no"
775 if not s.login(self.host, self.username, self.password, ssh_options):
776 raise ExceptionPassword("Invalid Password")
777 # Otherwise, the login succeeded.
779 # Send a ctrl-c to the remote process.
780 print "SENDING ctrl-c"
783 # Control Outlets (5 ,1).........5
785 print "EXPECTING: ", "Enter Request :"
786 index = s.expect(["Enter Request :"])
791 print "EXPECTING: ", "DS-RPC>"
792 index = s.expect(["DS-RPC>", "Enter user name:", "Port in use."])
794 print "sending username"
795 s.send(self.username + "\r\n")
796 index = s.expect(["DS-RPC>"])
798 raise ExceptionPrompt("PCU Reported 'Port in use.'")
801 print "SENDING: Reboot %d" % node_port
802 s.send("Reboot %d\r\n" % node_port)
806 print "EXPECTING: ", "Y/N?"
807 index = s.expect(["\(Y/N\)\?", "Port in use", "DS-RPC>"])
816 raise ExceptionPrompt("PCU Reported 'Port in use.'")
818 raise ExceptionSequence("Issued command 'Reboot' failed.")
820 # NOTE: for some reason, the script times out with the
821 # following line. In manual tests, it works correctly, but
822 # with automated tests, evidently it fails.
825 #print "TOTAL--", s.allstr, "--EOT"
826 index = s.expect(["DS-RPC>"])
827 print "got prompt back"
832 raise ExceptionPrompt("EOF before 'Enter Request' Prompt")
833 except pexpect.TIMEOUT:
834 raise ExceptionPrompt("Timeout before Prompt")
838 class BayTech(PCUControl):
839 def run(self, node_port, dryrun):
840 self.open(self.host, self.username)
841 self.sendPassword(self.password)
843 # Control Outlets (5 ,1).........5
844 self.ifThenSend("Enter Request :", "5")
848 self.ifThenSend("DS-RPC>", "Reboot %d" % node_port, ExceptionNotFound)
849 except ExceptionNotFound, msg:
850 # one machine is configured to ask for a username,
851 # even after login...
852 print "msg: %s" % msg
853 self.transport.write(self.username + "\r\n")
855 self.ifThenSend("DS-RPC>", "Reboot %d" % node_port)
857 # Reboot Outlet N (Y/N)?
859 self.ifThenSend("(Y/N)?", "N")
861 self.ifThenSend("(Y/N)?", "Y")
863 self.ifThenSend("DS-RPC>", "")
868 class WTIIPS4(PCUControl):
869 def run(self, node_port, dryrun):
871 self.sendPassword(self.password, "Enter Password:")
873 self.ifThenSend("IPS> ", "/Boot %s" % node_port)
875 self.ifThenSend("Sure? (Y/N): ", "N")
877 self.ifThenSend("Sure? (Y/N): ", "Y")
879 self.ifThenSend("IPS> ", "")
884 class ePowerSwitchGood(PCUControl):
886 # The old code used Python's HTTPPasswordMgrWithDefaultRealm()
887 # For some reason this both doesn't work and in some cases, actually
888 # hangs the PCU. Definitely not what we want.
890 # The code below is much simpler. Just letting things fail first,
891 # and then, trying again with authentication string in the header.
893 def run(self, node_port, dryrun):
894 self.transport = None
895 self.url = "http://%s:%d/" % (self.host,80)
896 uri = "%s:%d" % (self.host,80)
898 req = urllib2.Request(self.url)
900 handle = urllib2.urlopen(req)
902 # NOTE: this is expected to fail initially
909 return "ERROR: not protected by HTTP authentication"
911 if not hasattr(e, 'code') or e.code != 401:
912 return "ERROR: failed for: %s" % str(e)
914 base64data = base64.encodestring("%s:%s" % (self.username, self.password))[:-1]
915 # NOTE: assuming basic realm authentication.
916 authheader = "Basic %s" % base64data
917 req.add_header("Authorization", authheader)
920 f = urllib2.urlopen(req)
922 # failing here means the User/passwd is wrong (hopefully)
923 raise ExceptionPassword("Incorrect username/password")
925 # NOTE: after verifying that the user/password is correct,
926 # actually reboot the given node.
929 data = urllib.urlencode({'P%d' % node_port : "r"})
930 req = urllib2.Request(self.url + "cmd.html")
931 req.add_header("Authorization", authheader)
932 # add data to handler,
933 f = urllib2.urlopen(req, data)
934 if self.verbose: print f.read()
936 import traceback; traceback.print_exc()
937 from nodecommon import email_exception
940 # fetch url one more time on cmd.html, econtrol.html or whatever.
943 if self.verbose: print f.read()
948 class CustomPCU(PCUControl):
949 def run(self, node_port, dryrun):
950 url = "https://www-itec.uni-klu.ac.at/plab-pcu/index.php"
953 # Turn host off, then on
954 formstr = "plab%s=off" % node_port
955 os.system("curl --user %s:%s --form '%s' --insecure %s" % (self.username, self.password, formstr, url))
957 formstr = "plab%s=on" % node_port
958 os.system("curl --user %s:%s --form '%s' --insecure %s" % (self.username, self.password, formstr, url))
960 os.system("curl --user %s:%s --insecure %s" % (self.username, self.password, url))
963 class ePowerSwitchOld(PCUControl):
964 def run(self, node_port, dryrun):
965 self.url = "http://%s:%d/" % (self.host,80)
966 uri = "%s:%d" % (self.host,80)
969 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
970 authinfo.add_password (None, uri, self.username, self.password)
971 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
973 # NOTE: it doesn't seem to matter whether this authinfo is here or not.
974 transport = urllib2.build_opener(authinfo)
975 f = transport.open(self.url)
976 if self.verbose: print f.read()
979 transport = urllib2.build_opener(authhandler)
980 f = transport.open(self.url + "cmd.html", "P%d=r" % node_port)
981 if self.verbose: print f.read()
986 class ePowerSwitch(PCUControl):
987 def run(self, node_port, dryrun):
988 self.url = "http://%s:%d/" % (self.host,80)
989 uri = "%s:%d" % (self.host,80)
991 # TODO: I'm still not sure what the deal is here.
992 # two independent calls appear to need to be made before the
993 # reboot will succeed. It doesn't seem to be possible to do
994 # this with a single call. I have no idea why.
997 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
998 authinfo.add_password (None, uri, self.username, self.password)
999 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
1001 # NOTE: it doesn't seem to matter whether this authinfo is here or not.
1002 transport = urllib2.build_opener()
1003 f = transport.open(self.url + "elogin.html", "pwd=%s" % self.password)
1004 if self.verbose: print f.read()
1007 transport = urllib2.build_opener(authhandler)
1008 f = transport.open(self.url + "econtrol.html", "P%d=r" % node_port)
1009 if self.verbose: print f.read()
1011 # data= "P%d=r" % node_port
1012 #self.open(self.host, self.username, self.password)
1013 #self.sendHTTP("elogin.html", "pwd=%s" % self.password)
1014 #self.sendHTTP("econtrol.html", data)
1015 #self.sendHTTP("cmd.html", data)
1021 ### rebooting european BlackBox PSE boxes
1022 # Thierry Parmentelat - May 11 2005
1023 # tested on 4-ports models known as PSE505-FR
1024 # uses http to POST a data 'P<port>=r'
1025 # relies on basic authentication within http1.0
1026 # first curl-based script was
1027 # curl --http1.0 --basic --user <username>:<password> --data P<port>=r \
1028 # http://<hostname>:<http_port>/cmd.html && echo OK
1030 def bbpse_reboot (pcu_ip,username,password,port_in_pcu,http_port, dryrun):
1034 url = "http://%s:%d/cmd.html" % (pcu_ip,http_port)
1035 data= "P%d=r" % port_in_pcu
1037 logger.debug("POSTing '%s' on %s" % (data,url))
1039 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
1040 uri = "%s:%d" % (pcu_ip,http_port)
1041 authinfo.add_password (None, uri, username, password)
1042 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
1044 opener = urllib2.build_opener(authhandler)
1045 urllib2.install_opener(opener)
1051 f = urllib2.urlopen(url,data)
1058 except urllib2.URLError,err:
1059 logger.info('Could not open http connection', err)
1060 return "bbpse error"
1062 ### rebooting x10toggle based systems addressed by port
1063 # Marc E. Fiuczynski - May 31 2005
1064 # tested on 4-ports models known as PSE505-FR
1065 # uses ssh and password to login to an account
1066 # that will cause the system to be powercycled.
1068 def x10toggle_reboot(ip, username, password, port, dryrun):
1073 ssh = pyssh.Ssh(username, ip)
1077 telnet_answer(ssh, "password:", password)
1081 telnet_answer(ssh, "x10toggle>", "A%d" % port)
1084 output = ssh.close()
1086 logger.debug(output)
1089 except Exception, err:
1093 output = ssh.close()
1095 logger.debug(output)
1096 return errno.ETIMEDOUT
1098 ### rebooting Dell systems via RAC card
1099 # Marc E. Fiuczynski - June 01 2005
1100 # tested with David Lowenthal's itchy/scratchy nodes at UGA
1103 def runcmd(command, args, username, password, timeout = None):
1106 result_ready = threading.Condition()
1110 result_ready.acquire()
1114 result_ready.notify()
1115 result_ready.release()
1117 def do_command(command, username, password):
1120 # Popen4 is a popen-type class that combines stdout and stderr
1121 p = popen2.Popen4(command)
1123 # read all output data
1124 p.tochild.write("%s\n" % username)
1125 p.tochild.write("%s\n" % password)
1127 data = p.fromchild.read()
1130 # might get interrupted by a signal in poll() or waitpid()
1133 set_result((retval, data))
1136 if ex.errno == errno.EINTR:
1139 except Exception, ex:
1143 command = " ".join([command] + args)
1145 worker = threading.Thread(target = do_command, args = (command, username, password, ))
1146 worker.setDaemon(True)
1147 result_ready.acquire()
1149 result_ready.wait(timeout)
1151 if result == [None]:
1152 raise Exception, "command timed-out: '%s'" % command
1154 result_ready.release()
1157 if isinstance(result, Exception):
1160 (retval, data) = result
1161 if os.WIFEXITED(retval) and os.WEXITSTATUS(retval) == 0:
1164 out = "system command ('%s') " % command
1165 if os.WIFEXITED(retval):
1166 out += "failed, rc = %d" % os.WEXITSTATUS(retval)
1168 out += "killed by signal %d" % os.WTERMSIG(retval)
1170 out += "; output follows:\n" + data
1171 raise Exception, out
1173 def racadm_reboot(host, username, password, port, dryrun):
1176 ip = socket.gethostbyname(host)
1178 cmd = "/usr/sbin/racadm"
1181 output = runcmd(cmd, ["-r %s -i serveraction powercycle" % ip],
1184 output = runcmd(cmd, ["-r %s -i getsysinfo" % ip],
1187 print "RUNCMD: %s" % output
1189 logger.debug(output)
1192 except Exception, err:
1193 logger.debug("runcmd raised exception %s" % err)
1199 if pcu['hostname'] is not None and pcu['hostname'] is not "":
1200 return pcu['hostname']
1201 elif pcu['ip'] is not None and pcu['ip'] is not "":
1207 from monitor import database
1210 def get_pcu_values(pcu_id):
1213 # this shouldn't be loaded each time...
1214 fb = database.dbLoad("findbadpcus")
1217 values = fb['nodes']["id_%s" % pcu_id]['values']
1223 def reboot(nodename):
1224 return reboot_policy(nodename, True, False)
1226 def reboot_policy(nodename, continue_probe, dryrun):
1229 pcu = plc.getpcu(nodename)
1231 logger.debug("no pcu for %s" % nodename)
1232 print "no pcu for %s" % nodename
1233 return False # "%s has no pcu" % nodename
1235 values = get_pcu_values(pcu['pcu_id'])
1237 logger.debug("No values for pcu probe %s" % nodename)
1238 print "No values for pcu probe %s" % nodename
1239 return False #"no info for pcu_id %s" % pcu['pcu_id']
1242 logger.debug("Trying PCU %s %s" % (pcu['hostname'], pcu['model']))
1244 ret = reboot_test(nodename, values, continue_probe, verbose, dryrun)
1253 def reboot_test(nodename, values, continue_probe, verbose, dryrun):
1257 # DataProbe iPal (many sites)
1258 if continue_probe and values['model'].find("IP-41x_IP-81x") >= 0:
1259 ipal = IPAL(values, verbose, ['23', '80', '9100'])
1260 rb_ret = ipal.reboot(values[nodename], dryrun)
1262 # APC Masterswitch (Berkeley)
1263 elif continue_probe and ( values['model'].find("AP79xx") >= 0 or \
1264 values['model'].find("Masterswitch") >= 0 ):
1267 # TODO: make a more robust version of APC
1268 if values['pcu_id'] in [1102,1163,1055,1111,1231,1113,1127,1128,1148]:
1269 apc = APCEurope(values, verbose, ['22', '23'])
1270 rb_ret = apc.reboot(values[nodename], dryrun)
1272 elif values['pcu_id'] in [1110,86]:
1273 apc = APCBrazil(values, verbose, ['22', '23'])
1274 rb_ret = apc.reboot(values[nodename], dryrun)
1276 elif values['pcu_id'] in [1221,1225,1220]:
1277 apc = APCBerlin(values, verbose, ['22', '23'])
1278 rb_ret = apc.reboot(values[nodename], dryrun)
1280 elif values['pcu_id'] in [1173,1240,47]:
1281 apc = APCFolsom(values, verbose, ['22', '23'])
1282 rb_ret = apc.reboot(values[nodename], dryrun)
1285 apc = APCMaster(values, verbose, ['22', '23'])
1286 rb_ret = apc.reboot(values[nodename], dryrun)
1289 elif continue_probe and values['model'].find("DS4-RPC") >= 0:
1290 if values['pcu_id'] in [1056,1237,1052,1209,1002,1008,1041,1013,1022]:
1291 # These require a 'ctrl-c' to be sent...
1292 baytech = BayTechCtrlC(values, verbose, ['22', '23'])
1293 rb_ret = baytech.reboot(values[nodename], dryrun)
1295 elif values['pcu_id'] in [93]:
1296 baytech = BayTechAU(values, verbose, ['22', '23'])
1297 rb_ret = baytech.reboot(values[nodename], dryrun)
1299 elif values['pcu_id'] in [1057]:
1300 # These require a 'ctrl-c' to be sent...
1301 baytech = BayTechCtrlCUnibe(values, verbose, ['22', '23'])
1302 rb_ret = baytech.reboot(values[nodename], dryrun)
1304 elif values['pcu_id'] in [1012]:
1305 # This pcu sometimes doesn't present the 'Username' prompt,
1306 # unless you immediately try again...
1308 baytech = BayTechGeorgeTown(values, verbose, ['22', '23'])
1309 rb_ret = baytech.reboot(values[nodename], dryrun)
1311 baytech = BayTechGeorgeTown(values, verbose, ['22', '23'])
1312 rb_ret = baytech.reboot(values[nodename], dryrun)
1314 baytech = BayTech(values, verbose, ['22', '23'])
1315 rb_ret = baytech.reboot(values[nodename], dryrun)
1318 elif continue_probe and values['model'].find("ilo") >= 0:
1320 hpilo = HPiLO(values, verbose, ['22'])
1321 rb_ret = hpilo.reboot(0, dryrun)
1323 hpilo = HPiLOHttps(values, verbose, ['443'])
1324 rb_ret = hpilo.reboot(0, dryrun)
1326 hpilo = HPiLOHttps(values, verbose, ['443'])
1327 rb_ret = hpilo.reboot(0, dryrun)
1330 elif continue_probe and values['model'].find("DRAC") >= 0:
1331 # TODO: I don't think DRACRacAdm will throw an exception for the
1332 # default method to catch...
1334 if values['pcu_id'] in [1402]:
1335 drac = DRAC(values, verbose, ['22'])
1336 rb_ret = drac.reboot(0, dryrun)
1338 drac = DRACRacAdm(values, verbose, ['443', '5869'])
1339 rb_ret = drac.reboot(0, dryrun)
1341 drac = DRAC(values, verbose, ['22'])
1342 rb_ret = drac.reboot(0, dryrun)
1344 elif continue_probe and values['model'].find("WTI IPS-4") >= 0:
1345 wti = WTIIPS4(values, verbose, ['23'])
1346 rb_ret = wti.reboot(values[nodename], dryrun)
1348 elif continue_probe and values['model'].find("AMT") >= 0:
1349 amt = IntelAMT(values, verbose, ['16992'])
1350 rb_ret = amt.reboot(values[nodename], dryrun)
1352 # BlackBox PSExxx-xx (e.g. PSE505-FR)
1353 elif continue_probe and values['model'].find("ePowerSwitch") >=0:
1354 # TODO: allow a different port than http 80.
1355 if values['pcu_id'] in [1089, 1071, 1046, 1035, 1118]:
1356 eps = ePowerSwitchGood(values, verbose, ['80'])
1357 elif values['pcu_id'] in [1003]:
1360 eps = ePowerSwitch(values, verbose, ['80'])
1362 eps = ePowerSwitchGood(values, verbose, ['80'])
1364 rb_ret = eps.reboot(values[nodename], dryrun)
1365 elif continue_probe and values['pcu_id'] in [1122]:
1366 custom = CustomPCU(values, verbose, ['80', '443'])
1367 custom.reboot(values[nodename], dryrun)
1369 elif continue_probe:
1370 rb_ret = "Unsupported_PCU"
1372 elif continue_probe == False:
1373 if 'portstatus' in values:
1380 except ExceptionPort, err:
1385 #elif continue_probe and values['protocol'] == "racadm" and \
1386 # values['model'] == "RAC":
1387 # rb_ret = racadm_reboot(pcu_name(values),
1388 # values['username'],
1389 # values['password'],
1394 logger.setLevel(logging.DEBUG)
1395 ch = logging.StreamHandler()
1396 ch.setLevel(logging.DEBUG)
1397 formatter = logging.Formatter('LOGGER - %(message)s')
1398 ch.setFormatter(formatter)
1399 logger.addHandler(ch)
1402 if "test" in sys.argv:
1407 for node in sys.argv[1:]:
1408 if node == "test": continue
1410 print "Rebooting %s" % node
1411 if reboot_policy(node, True, dryrun):
1415 except Exception, err:
1416 import traceback; traceback.print_exc()
1417 from nodecommon import email_exception
1421 if __name__ == '__main__':
1423 logger = logging.getLogger("monitor")