3 # Reboot specified nodes
9 import errno, time, traceback
12 import threading, popen2
18 from subprocess import PIPE, Popen
19 import ssh.pxssh as pxssh
20 import ssh.pexpect as pexpect
24 # Use our versions of telnetlib and pyssh
25 sys.path.insert(0, os.path.dirname(sys.argv[0]))
27 sys.path.insert(0, os.path.dirname(sys.argv[0]) + "/pyssh")
33 # Event class ID from pcu events
34 #NODE_POWER_CONTROL = 3
37 #MONITOR_USER_ID = 11142
40 logger = logging.getLogger("monitor")
44 class ExceptionNoTransport(Exception): pass
45 class ExceptionNotFound(Exception): pass
46 class ExceptionPassword(Exception): pass
47 class ExceptionTimeout(Exception): pass
48 class ExceptionPrompt(Exception): pass
49 class ExceptionSequence(Exception): pass
50 class ExceptionReset(Exception): pass
51 class ExceptionPort(Exception): pass
52 class ExceptionUsername(Exception): pass
54 def telnet_answer(telnet, expected, buffer):
57 output = telnet.read_until(expected, TELNET_TIMEOUT)
59 # logger.debug(output)
60 if output.find(expected) == -1:
61 raise ExceptionNotFound, "'%s' not found" % expected
63 telnet.write(buffer + "\r\n")
66 # PCU has model, host, preferred-port, user, passwd,
68 # This is an object derived directly form the PLCAPI DB fields
70 def __init__(self, plc_pcu_dict):
71 for field in ['username', 'password', 'site_id',
74 'node_ids', 'ports', ]:
75 if field in plc_pcu_dict:
76 self.__setattr__(field, plc_pcu_dict[field])
78 raise Exception("No such field %s in PCU object" % field)
80 # These are the convenience functions build around the PCU object.
82 def __init__(self, plc_pcu_dict):
83 PCU.__init__(self, plc_pcu_dict)
84 self.host = self.pcu_name()
87 if self.hostname is not None and self.hostname is not "":
89 elif self.ip is not None and self.ip is not "":
94 def nodeidToPort(self, node_id):
95 if node_id in self.node_ids:
96 for i in range(0, len(self.node_ids)):
97 if node_id == self.node_ids[i]:
100 raise Exception("No such Node ID: %d" % node_id)
102 # This class captures the observed pcu records from FindBadPCUs.py
104 def __init__(self, pcu_record_dict):
105 for field in ['nodenames', 'portstatus',
108 if field in pcu_record_dict:
109 if field == "reboot":
110 self.__setattr__("reboot_str", pcu_record_dict[field])
112 self.__setattr__(field, pcu_record_dict[field])
114 raise Exception("No such field %s in pcu record dict" % field)
124 def __init__(self, type, verbose):
126 self.verbose = verbose
127 self.transport = None
129 def open(self, host, username=None, password=None, prompt="User Name"):
132 if self.type == self.TELNET:
133 transport = telnetlib.Telnet(host, timeout=self.TELNET_TIMEOUT)
134 transport.set_debuglevel(self.verbose)
135 if username is not None:
136 self.transport = transport
137 self.ifThenSend(prompt, username, ExceptionUsername)
139 elif self.type == self.SSH:
140 if username is not None:
141 transport = pyssh.Ssh(username, host)
142 transport.set_debuglevel(self.verbose)
144 # TODO: have an ssh set_debuglevel() also...
146 raise Exception("Username cannot be None for ssh transport.")
147 elif self.type == self.HTTP:
148 self.url = "http://%s:%d/" % (host,80)
149 uri = "%s:%d" % (host,80)
152 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
153 authinfo.add_password (None, uri, username, password)
154 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
156 transport = urllib2.build_opener(authhandler)
159 raise Exception("Unknown transport type: %s" % self.type)
161 self.transport = transport
165 if self.type == self.TELNET:
166 self.transport.close()
167 elif self.type == self.SSH:
168 self.transport.close()
169 elif self.type == self.HTTP:
172 raise Exception("Unknown transport type %s" % self.type)
173 self.transport = None
175 def sendHTTP(self, resource, data):
177 print "POSTing '%s' to %s" % (data,self.url + resource)
180 f = self.transport.open(self.url + resource ,data)
185 except urllib2.URLError,err:
186 logger.info('Could not open http connection', err)
187 return "http transport error"
191 def sendPassword(self, password, prompt=None):
192 if self.type == self.TELNET:
194 self.ifThenSend("Password", password, ExceptionPassword)
196 self.ifThenSend(prompt, password, ExceptionPassword)
197 elif self.type == self.SSH:
198 self.ifThenSend("password:", password, ExceptionPassword)
199 elif self.type == self.HTTP:
202 raise Exception("Unknown transport type: %s" % self.type)
204 def ifThenSend(self, expected, buffer, ErrorClass=ExceptionPrompt):
206 if self.transport != None:
207 output = self.transport.read_until(expected, self.TELNET_TIMEOUT)
208 if output.find(expected) == -1:
209 raise ErrorClass, "'%s' not found" % expected
211 self.transport.write(buffer + "\r\n")
213 raise ExceptionNoTransport("transport object is type None")
215 def ifElse(self, expected, ErrorClass):
217 self.transport.read_until(expected, self.TELNET_TIMEOUT)
219 raise ErrorClass("Could not find '%s' within timeout" % expected)
222 class PCUControl(Transport,PCUModel,PCURecord):
223 def __init__(self, plc_pcu_record, verbose, supported_ports=[]):
224 PCUModel.__init__(self, plc_pcu_record)
225 PCURecord.__init__(self, plc_pcu_record)
228 if '22' in supported_ports and self.portstatus['22'] == "open":
230 elif '23' in supported_ports and self.portstatus['23'] == "open":
231 type = Transport.TELNET
232 elif '80' in supported_ports and self.portstatus['80'] == "open":
233 type = Transport.HTTP
234 elif '443' in supported_ports and self.portstatus['443'] == "open":
235 type = Transport.HTTP
236 elif '5869' in supported_ports and self.portstatus['5869'] == "open":
237 # For DRAC cards. Racadm opens this port.
238 type = Transport.HTTP
239 elif '9100' in supported_ports and self.portstatus['9100'] == "open":
240 type = Transport.IPAL
241 elif '16992' in supported_ports and self.portstatus['16992'] == "open":
242 type = Transport.HTTP
244 raise ExceptionPort("Unsupported Port: No transport from open ports")
246 raise Exception("No Portstatus: No transport because no open ports")
247 Transport.__init__(self, type, verbose)
249 def run(self, node_port, dryrun):
250 """ This function is to be defined by the specific PCU instance. """
253 def reboot(self, node_port, dryrun):
255 return self.run(node_port, dryrun)
256 except ExceptionNotFound, err:
257 return "error: " + str(err)
258 except ExceptionPassword, err:
259 return "password exception: " + str(err)
260 except ExceptionTimeout, err:
261 return "timeout exception: " + str(err)
262 except ExceptionUsername, err:
263 return "exception: no username prompt: " + str(err)
264 except ExceptionSequence, err:
265 return "sequence error: " + str(err)
266 except ExceptionPrompt, err:
267 return "prompt exception: " + str(err)
268 except ExceptionPort, err:
269 return "no ports exception: " + str(err)
270 except socket.error, err:
271 return "socket error: timeout: " + str(err)
272 except EOFError, err:
274 logger.debug("reboot: EOF")
276 self.transport.close()
278 traceback.print_exc()
279 return "EOF connection reset" + str(err)
281 class IPAL(PCUControl):
283 This now uses a proprietary format for communicating with the PCU. I
284 prefer it to Telnet, and Web access, since it's much lighter weight
285 and, more importantly, IT WORKS!! HHAHHHAHAHAHAHAHA!
288 def format_msg(self, data, cmd):
289 esc = chr(int('1b',16))
290 return "%c%s%c%s%c" % (esc, self.password, esc, data, cmd) # esc, 'q', chr(4))
292 def recv_noblock(self, s, count):
296 # TODO: make sleep backoff, before stopping.
298 ret = s.recv(count, socket.MSG_DONTWAIT)
299 except socket.error, e:
300 if e[0] == errno.EAGAIN:
301 raise Exception(e[1])
303 # TODO: not other exceptions.
307 def run(self, node_port, dryrun):
313 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
316 s.connect((self.host, 9100))
317 except socket.error, e:
319 if e[0] == errno.ECONNREFUSED:
320 # cannot connect to remote host
321 raise Exception(e[1])
323 # TODO: what other conditions are there?
327 print "Checking status"
328 s.send(self.format_msg("", 'O'))
329 ret = self.recv_noblock(s, 8)
330 print "Current status is '%s'" % ret
333 raise Exception("Status returned 'another session already open' %s : %s" % (node_port, ret))
336 if node_port < len(ret):
337 status = ret[node_port]
345 raise Exception("Unknown status for PCU socket %s : %s" % (node_port, ret))
347 raise Exception("Mismatch between configured port and PCU status: %s %s" % (node_port, ret))
352 print "Pulsing %s" % node_port
353 s.send(self.format_msg("%s" % node_port, 'P'))
355 # NOTE: turn power on ; do not pulse the port.
356 print "Power was off, so turning on ..."
357 s.send(self.format_msg("%s" % node_port, 'E'))
358 #s.send(self.format_msg("%s" % node_port, 'P'))
360 print "Receiving response."
361 ret = self.recv_noblock(s, 8)
362 print "Current status is '%s'" % ret
364 if node_port < len(ret):
365 status = ret[node_port]
373 raise Exception("Unknown status for PCU socket %s : %s" % (node_port, ret))
375 raise Exception("Mismatch between configured port and PCU status: %s %s" % (node_port, ret))
380 return "Failed Power On"
385 # TELNET version of protocol...
386 # #self.open(self.host)
387 # ## XXX Some iPals require you to hit Enter a few times first
388 # #self.ifThenSend("Password >", "\r\n\r\n", ExceptionNotFound)
390 # self.ifThenSend("Password >", self.password, ExceptionPassword)
391 # self.transport.write("\r\n\r\n")
392 # if not dryrun: # P# - Pulse relay
393 # print "node_port %s" % node_port
394 # self.ifThenSend("Enter >",
395 # "P7", # % node_port,
397 # print "send newlines"
398 # self.transport.write("\r\n\r\n")
399 # print "after new lines"
400 # # Get the next prompt
401 # print "wait for enter"
402 # self.ifElse("Enter >", ExceptionTimeout)
407 class APCEurope(PCUControl):
408 def run(self, node_port, dryrun):
409 self.open(self.host, self.username)
410 self.sendPassword(self.password)
412 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
413 self.ifThenSend("\r\n> ", "2")
414 self.ifThenSend("\r\n> ", str(node_port))
415 # 3- Immediate Reboot
416 self.ifThenSend("\r\n> ", "3")
419 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
423 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
424 "", ExceptionSequence)
425 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
430 class APCBrazil(PCUControl):
431 def run(self, node_port, dryrun):
432 self.open(self.host, self.username)
433 self.sendPassword(self.password)
435 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
436 self.ifThenSend("\r\n> ", str(node_port))
437 # 4- Immediate Reboot
438 self.ifThenSend("\r\n> ", "4")
441 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
445 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
446 "", ExceptionSequence)
447 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
452 class APCBerlin(PCUControl):
453 def run(self, node_port, dryrun):
454 self.open(self.host, self.username)
455 self.sendPassword(self.password)
457 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
458 self.ifThenSend("\r\n> ", "2")
459 self.ifThenSend("\r\n> ", "1")
460 self.ifThenSend("\r\n> ", str(node_port))
461 # 3- Immediate Reboot
462 self.ifThenSend("\r\n> ", "3")
465 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
469 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
470 "", ExceptionSequence)
471 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
476 class APCFolsom(PCUControl):
477 def run(self, node_port, dryrun):
478 self.open(self.host, self.username)
479 self.sendPassword(self.password)
481 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
482 self.ifThenSend("\r\n> ", "2")
483 self.ifThenSend("\r\n> ", "1")
484 self.ifThenSend("\r\n> ", str(node_port))
485 self.ifThenSend("\r\n> ", "1")
487 # 3- Immediate Reboot
488 self.ifThenSend("\r\n> ", "3")
491 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
495 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
496 "", ExceptionSequence)
497 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
502 class APCMaster(PCUControl):
503 def run(self, node_port, dryrun):
504 print "Rebooting %s" % self.host
505 self.open(self.host, self.username)
506 self.sendPassword(self.password)
509 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
510 # 3- Outlet Control/Config
511 self.ifThenSend("\r\n> ", "3")
513 self.ifThenSend("\r\n> ", str(node_port))
515 self.ifThenSend("\r\n> ", "1")
516 # 3- Immediate Reboot
517 self.ifThenSend("\r\n> ", "3")
520 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
524 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
525 "", ExceptionSequence)
526 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
531 class APC(PCUControl):
532 def __init__(self, plc_pcu_record, verbose):
533 PCUControl.__init__(self, plc_pcu_record, verbose)
535 self.master = APCMaster(plc_pcu_record, verbose)
536 self.folsom = APCFolsom(plc_pcu_record, verbose)
537 self.europe = APCEurope(plc_pcu_record, verbose)
539 def run(self, node_port, dryrun):
543 for pcu in [self.master, self.europe, self.folsom]:
546 print "-*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*"
549 time.sleep(sleep_time)
550 ret = pcu.reboot(node_port, dryrun)
551 except ExceptionSequence, err:
557 return "Unknown reboot sequence for APC PCU"
561 class IntelAMT(PCUControl):
562 def run(self, node_port, dryrun):
564 cmd = moncommands.CMD()
565 #[cmd_str = "IntelAMTSDK/Samples/RemoteControl/remoteControl"
566 cmd_str = "cmdamt/remoteControl"
569 # NOTE: -p checks the power state of the host.
570 # TODO: parse the output to find out if it's ok or not.
571 cmd_str += " -p http://%s:16992/RemoteControlService -user admin -pass '%s' " % (self.host, self.password )
573 cmd_str += " -A http://%s:16992/RemoteControlService -user admin -pass '%s' " % (self.host, self.password )
576 return cmd.system(cmd_str, self.TELNET_TIMEOUT)
578 class DRACRacAdm(PCUControl):
579 def run(self, node_port, dryrun):
581 print "trying racadm_reboot..."
582 racadm_reboot(self.host, self.username, self.password, node_port, dryrun)
586 class DRAC(PCUControl):
587 def run(self, node_port, dryrun):
588 self.open(self.host, self.username)
589 self.sendPassword(self.password)
591 print "logging in..."
592 self.transport.write("\r\n")
595 self.ifThenSend("[%s]#" % self.username, "getsysinfo")
598 self.ifThenSend("[%s]#" % self.username, "serveraction powercycle")
600 self.ifThenSend("[%s]#" % self.username, "exit")
605 class HPiLO(PCUControl):
606 def run(self, node_port, dryrun):
607 self.open(self.host, self.username)
608 self.sendPassword(self.password)
611 self.ifThenSend("</>hpiLO->", "cd system1")
613 # Reboot Outlet N (Y/N)?
615 self.ifThenSend("</system1>hpiLO->", "POWER")
618 self.ifThenSend("</system1>hpiLO->", "reset")
620 self.ifThenSend("</system1>hpiLO->", "exit")
626 class HPiLOHttps(PCUControl):
627 def run(self, node_port, dryrun):
629 locfg = moncommands.CMD()
630 cmd = "cmdhttps/locfg.pl -s %s -f %s -u %s -p '%s' | grep 'MESSAGE' | grep -v 'No error'" % (
631 self.host, "iloxml/Get_Network.xml",
632 self.username, self.password)
633 sout, serr = locfg.run_noexcept(cmd)
635 if sout.strip() != "":
636 print "sout: %s" % sout.strip()
640 locfg = moncommands.CMD()
641 cmd = "cmdhttps/locfg.pl -s %s -f %s -u %s -p '%s' | grep 'MESSAGE' | grep -v 'No error'" % (
642 self.host, "iloxml/Reset_Server.xml",
643 self.username, self.password)
644 sout, serr = locfg.run_noexcept(cmd)
646 if sout.strip() != "":
647 print "sout: %s" % sout.strip()
651 class BayTechAU(PCUControl):
652 def run(self, node_port, dryrun):
653 self.open(self.host, self.username, None, "Enter user name:")
654 self.sendPassword(self.password, "Enter Password:")
656 #self.ifThenSend("RPC-16>", "Status")
657 self.ifThenSend("RPC3-NC>", "Reboot %d" % node_port)
659 # Reboot Outlet N (Y/N)?
661 self.ifThenSend("(Y/N)?", "N")
663 self.ifThenSend("(Y/N)?", "Y")
664 self.ifThenSend("RPC3-NC>", "")
669 class BayTechGeorgeTown(PCUControl):
670 def run(self, node_port, dryrun):
671 self.open(self.host, self.username, None, "Enter user name:")
672 self.sendPassword(self.password, "Enter Password:")
674 #self.ifThenSend("RPC-16>", "Status")
676 self.ifThenSend("RPC-16>", "Reboot %d" % node_port)
678 # Reboot Outlet N (Y/N)?
680 self.ifThenSend("(Y/N)?", "N")
682 self.ifThenSend("(Y/N)?", "Y")
683 self.ifThenSend("RPC-16>", "")
688 class BayTechCtrlCUnibe(PCUControl):
690 For some reason, these units let you log in fine, but they hang
691 indefinitely, unless you send a Ctrl-C after the password. No idea
694 def run(self, node_port, dryrun):
695 print "BayTechCtrlC %s" % self.host
697 ssh_options="-o StrictHostKeyChecking=no -o PasswordAuthentication=yes -o PubkeyAuthentication=no"
699 if not s.login(self.host, self.username, self.password, ssh_options):
700 raise ExceptionPassword("Invalid Password")
701 # Otherwise, the login succeeded.
703 # Send a ctrl-c to the remote process.
704 print "sending ctrl-c"
707 # Control Outlets (5 ,1).........5
709 index = s.expect(["Enter Request :"])
714 index = s.expect(["DS-RPC>", "Enter user name:"])
716 s.send(self.username + "\r\n")
717 index = s.expect(["DS-RPC>"])
720 print "Reboot %d" % node_port
721 s.send("Reboot %d\r\n" % node_port)
723 index = s.expect(["(Y/N)?"])
732 #index = s.expect(["DS-RPC>"])
733 #print "got prompt back"
738 raise ExceptionPrompt("EOF before 'Enter Request' Prompt")
739 except pexpect.TIMEOUT:
740 raise ExceptionPrompt("Timeout before 'Enter Request' Prompt")
744 class BayTechCtrlC(PCUControl):
746 For some reason, these units let you log in fine, but they hang
747 indefinitely, unless you send a Ctrl-C after the password. No idea
750 def run(self, node_port, dryrun):
751 print "BayTechCtrlC %s" % self.host
753 ssh_options="-o StrictHostKeyChecking=no -o PasswordAuthentication=yes -o PubkeyAuthentication=no"
755 if not s.login(self.host, self.username, self.password, ssh_options):
756 raise ExceptionPassword("Invalid Password")
757 # Otherwise, the login succeeded.
759 # Send a ctrl-c to the remote process.
760 print "sending ctrl-c"
763 # Control Outlets (5 ,1).........5
765 index = s.expect(["Enter Request :"])
770 index = s.expect(["DS-RPC>", "Enter user name:"])
772 print "sending username"
773 s.send(self.username + "\r\n")
774 index = s.expect(["DS-RPC>"])
777 print "Reboot %d" % node_port
778 s.send("Reboot %d\r\n" % node_port)
780 index = s.expect(["(Y/N)?"])
789 index = s.expect(["DS-RPC>"])
790 #print "got prompt back"
795 raise ExceptionPrompt("EOF before 'Enter Request' Prompt")
796 except pexpect.TIMEOUT:
797 raise ExceptionPrompt("Timeout before Prompt")
801 class BayTech(PCUControl):
802 def run(self, node_port, dryrun):
803 self.open(self.host, self.username)
804 self.sendPassword(self.password)
806 # Control Outlets (5 ,1).........5
807 self.ifThenSend("Enter Request :", "5")
811 self.ifThenSend("DS-RPC>", "Reboot %d" % node_port, ExceptionNotFound)
812 except ExceptionNotFound, msg:
813 # one machine is configured to ask for a username,
814 # even after login...
815 print "msg: %s" % msg
816 self.transport.write(self.username + "\r\n")
817 self.ifThenSend("DS-RPC>", "Reboot %d" % node_port)
819 # Reboot Outlet N (Y/N)?
821 self.ifThenSend("(Y/N)?", "N")
823 self.ifThenSend("(Y/N)?", "Y")
824 self.ifThenSend("DS-RPC>", "")
829 class WTIIPS4(PCUControl):
830 def run(self, node_port, dryrun):
832 self.sendPassword(self.password, "Enter Password:")
834 self.ifThenSend("IPS> ", "/Boot %s" % node_port)
836 self.ifThenSend("Sure? (Y/N): ", "N")
838 self.ifThenSend("Sure? (Y/N): ", "Y")
840 self.ifThenSend("IPS> ", "")
845 class ePowerSwitchGood(PCUControl):
847 # The old code used Python's HTTPPasswordMgrWithDefaultRealm()
848 # For some reason this both doesn't work and in some cases, actually
849 # hangs the PCU. Definitely not what we want.
851 # The code below is much simpler. Just letting things fail first,
852 # and then, trying again with authentication string in the header.
854 def run(self, node_port, dryrun):
855 self.transport = None
856 self.url = "http://%s:%d/" % (self.host,80)
857 uri = "%s:%d" % (self.host,80)
859 req = urllib2.Request(self.url)
861 handle = urllib2.urlopen(req)
863 # NOTE: this is expected to fail initially
870 return "ERROR: not protected by HTTP authentication"
872 if not hasattr(e, 'code') or e.code != 401:
873 return "ERROR: failed for: %s" % str(e)
875 base64data = base64.encodestring("%s:%s" % (self.username, self.password))[:-1]
876 # NOTE: assuming basic realm authentication.
877 authheader = "Basic %s" % base64data
878 req.add_header("Authorization", authheader)
881 f = urllib2.urlopen(req)
883 # failing here means the User/passwd is wrong (hopefully)
884 raise ExceptionPassword("Incorrect username/password")
886 # NOTE: after verifying that the user/password is correct,
887 # actually reboot the given node.
890 data = urllib.urlencode({'P%d' % node_port : "r"})
891 req = urllib2.Request(self.url + "cmd.html")
892 req.add_header("Authorization", authheader)
893 # add data to handler,
894 f = urllib2.urlopen(req, data)
895 if self.verbose: print f.read()
897 import traceback; traceback.print_exc()
899 # fetch url one more time on cmd.html, econtrol.html or whatever.
902 if self.verbose: print f.read()
907 class CustomPCU(PCUControl):
908 def run(self, node_port, dryrun):
909 url = "https://www-itec.uni-klu.ac.at/plab-pcu/index.php"
912 # Turn host off, then on
913 formstr = "plab%s=off" % node_port
914 os.system("curl --user %s:%s --form '%s' --insecure %s" % (self.username, self.password, formstr, url))
916 formstr = "plab%s=on" % node_port
917 os.system("curl --user %s:%s --form '%s' --insecure %s" % (self.username, self.password, formstr, url))
919 os.system("curl --user %s:%s --insecure %s" % (self.username, self.password, url))
922 class ePowerSwitchOld(PCUControl):
923 def run(self, node_port, dryrun):
924 self.url = "http://%s:%d/" % (self.host,80)
925 uri = "%s:%d" % (self.host,80)
928 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
929 authinfo.add_password (None, uri, self.username, self.password)
930 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
932 # NOTE: it doesn't seem to matter whether this authinfo is here or not.
933 transport = urllib2.build_opener(authinfo)
934 f = transport.open(self.url)
935 if self.verbose: print f.read()
938 transport = urllib2.build_opener(authhandler)
939 f = transport.open(self.url + "cmd.html", "P%d=r" % node_port)
940 if self.verbose: print f.read()
945 class ePowerSwitch(PCUControl):
946 def run(self, node_port, dryrun):
947 self.url = "http://%s:%d/" % (self.host,80)
948 uri = "%s:%d" % (self.host,80)
950 # TODO: I'm still not sure what the deal is here.
951 # two independent calls appear to need to be made before the
952 # reboot will succeed. It doesn't seem to be possible to do
953 # this with a single call. I have no idea why.
956 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
957 authinfo.add_password (None, uri, self.username, self.password)
958 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
960 # NOTE: it doesn't seem to matter whether this authinfo is here or not.
961 transport = urllib2.build_opener()
962 f = transport.open(self.url + "elogin.html", "pwd=%s" % self.password)
963 if self.verbose: print f.read()
966 transport = urllib2.build_opener(authhandler)
967 f = transport.open(self.url + "econtrol.html", "P%d=r" % node_port)
968 if self.verbose: print f.read()
970 # data= "P%d=r" % node_port
971 #self.open(self.host, self.username, self.password)
972 #self.sendHTTP("elogin.html", "pwd=%s" % self.password)
973 #self.sendHTTP("econtrol.html", data)
974 #self.sendHTTP("cmd.html", data)
980 ### rebooting european BlackBox PSE boxes
981 # Thierry Parmentelat - May 11 2005
982 # tested on 4-ports models known as PSE505-FR
983 # uses http to POST a data 'P<port>=r'
984 # relies on basic authentication within http1.0
985 # first curl-based script was
986 # curl --http1.0 --basic --user <username>:<password> --data P<port>=r \
987 # http://<hostname>:<http_port>/cmd.html && echo OK
989 def bbpse_reboot (pcu_ip,username,password,port_in_pcu,http_port, dryrun):
993 url = "http://%s:%d/cmd.html" % (pcu_ip,http_port)
994 data= "P%d=r" % port_in_pcu
996 logger.debug("POSTing '%s' on %s" % (data,url))
998 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
999 uri = "%s:%d" % (pcu_ip,http_port)
1000 authinfo.add_password (None, uri, username, password)
1001 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
1003 opener = urllib2.build_opener(authhandler)
1004 urllib2.install_opener(opener)
1010 f = urllib2.urlopen(url,data)
1017 except urllib2.URLError,err:
1018 logger.info('Could not open http connection', err)
1019 return "bbpse error"
1021 ### rebooting x10toggle based systems addressed by port
1022 # Marc E. Fiuczynski - May 31 2005
1023 # tested on 4-ports models known as PSE505-FR
1024 # uses ssh and password to login to an account
1025 # that will cause the system to be powercycled.
1027 def x10toggle_reboot(ip, username, password, port, dryrun):
1032 ssh = pyssh.Ssh(username, ip)
1036 telnet_answer(ssh, "password:", password)
1040 telnet_answer(ssh, "x10toggle>", "A%d" % port)
1043 output = ssh.close()
1045 logger.debug(output)
1048 except Exception, err:
1052 output = ssh.close()
1054 logger.debug(output)
1055 return errno.ETIMEDOUT
1057 ### rebooting Dell systems via RAC card
1058 # Marc E. Fiuczynski - June 01 2005
1059 # tested with David Lowenthal's itchy/scratchy nodes at UGA
1062 def runcmd(command, args, username, password, timeout = None):
1065 result_ready = threading.Condition()
1069 result_ready.acquire()
1073 result_ready.notify()
1074 result_ready.release()
1076 def do_command(command, username, password):
1079 # Popen4 is a popen-type class that combines stdout and stderr
1080 p = popen2.Popen4(command)
1082 # read all output data
1083 p.tochild.write("%s\n" % username)
1084 p.tochild.write("%s\n" % password)
1086 data = p.fromchild.read()
1089 # might get interrupted by a signal in poll() or waitpid()
1092 set_result((retval, data))
1095 if ex.errno == errno.EINTR:
1098 except Exception, ex:
1102 command = " ".join([command] + args)
1104 worker = threading.Thread(target = do_command, args = (command, username, password, ))
1105 worker.setDaemon(True)
1106 result_ready.acquire()
1108 result_ready.wait(timeout)
1110 if result == [None]:
1111 raise Exception, "command timed-out: '%s'" % command
1113 result_ready.release()
1116 if isinstance(result, Exception):
1119 (retval, data) = result
1120 if os.WIFEXITED(retval) and os.WEXITSTATUS(retval) == 0:
1123 out = "system command ('%s') " % command
1124 if os.WIFEXITED(retval):
1125 out += "failed, rc = %d" % os.WEXITSTATUS(retval)
1127 out += "killed by signal %d" % os.WTERMSIG(retval)
1129 out += "; output follows:\n" + data
1130 raise Exception, out
1132 def racadm_reboot(host, username, password, port, dryrun):
1135 ip = socket.gethostbyname(host)
1137 cmd = "/usr/sbin/racadm"
1140 output = runcmd(cmd, ["-r %s -i serveraction powercycle" % ip],
1143 output = runcmd(cmd, ["-r %s -i getsysinfo" % ip],
1146 print "RUNCMD: %s" % output
1148 logger.debug(output)
1151 except Exception, err:
1152 logger.debug("runcmd raised exception %s" % err)
1158 if pcu['hostname'] is not None and pcu['hostname'] is not "":
1159 return pcu['hostname']
1160 elif pcu['ip'] is not None and pcu['ip'] is not "":
1166 fb =database.dbLoad("findbadpcus")
1168 def get_pcu_values(pcu_id):
1169 # TODO: obviously, this shouldn't be loaded each time...
1172 values = fb['nodes']["id_%s" % pcu_id]['values']
1178 def reboot(nodename):
1179 return reboot_policy(nodename, True, False)
1181 def reboot_policy(nodename, continue_probe, dryrun):
1184 pcu = plc.getpcu(nodename)
1186 logger.debug("no pcu for %s" % hostname)
1187 print "no pcu for %s" % hostname
1188 return False # "%s has no pcu" % nodename
1190 values = get_pcu_values(pcu['pcu_id'])
1192 logger.debug("No values for pcu probe %s" % hostname)
1193 print "No values for pcu probe %s" % hostname
1194 return False #"no info for pcu_id %s" % pcu['pcu_id']
1197 logger.debug("Trying PCU %s %s" % (pcu['hostname'], pcu['model']))
1199 ret = reboot_test(nodename, values, continue_probe, verbose, dryrun)
1208 def reboot_test(nodename, values, continue_probe, verbose, dryrun):
1212 # DataProbe iPal (many sites)
1213 if continue_probe and values['model'].find("IP-41x_IP-81x") >= 0:
1214 ipal = IPAL(values, verbose, ['23', '80', '9100'])
1215 rb_ret = ipal.reboot(values[nodename], dryrun)
1217 # APC Masterswitch (Berkeley)
1218 elif continue_probe and ( values['model'].find("AP79xx") >= 0 or \
1219 values['model'].find("Masterswitch") >= 0 ):
1222 # TODO: make a more robust version of APC
1223 if values['pcu_id'] in [1163,1055,1111,1231,1113,1127,1128,1148]:
1224 apc = APCEurope(values, verbose, ['22', '23'])
1225 rb_ret = apc.reboot(values[nodename], dryrun)
1227 elif values['pcu_id'] in [1110,86]:
1228 apc = APCBrazil(values, verbose, ['22', '23'])
1229 rb_ret = apc.reboot(values[nodename], dryrun)
1231 elif values['pcu_id'] in [1221,1225]:
1232 apc = APCBerlin(values, verbose, ['22', '23'])
1233 rb_ret = apc.reboot(values[nodename], dryrun)
1235 elif values['pcu_id'] in [1173,1221,1220]:
1236 apc = APCFolsom(values, verbose, ['22', '23'])
1237 rb_ret = apc.reboot(values[nodename], dryrun)
1240 apc = APCMaster(values, verbose, ['22', '23'])
1241 rb_ret = apc.reboot(values[nodename], dryrun)
1244 elif continue_probe and values['model'].find("DS4-RPC") >= 0:
1245 if values['pcu_id'] in [1237,1052,1209,1002,1008,1041,1013,1022]:
1246 # These require a 'ctrl-c' to be sent...
1247 baytech = BayTechCtrlC(values, verbose, ['22', '23'])
1248 rb_ret = baytech.reboot(values[nodename], dryrun)
1250 elif values['pcu_id'] in [93]:
1251 baytech = BayTechAU(values, verbose, ['22', '23'])
1252 rb_ret = baytech.reboot(values[nodename], dryrun)
1254 elif values['pcu_id'] in [1057]:
1255 # These require a 'ctrl-c' to be sent...
1256 baytech = BayTechCtrlCUnibe(values, verbose, ['22', '23'])
1257 rb_ret = baytech.reboot(values[nodename], dryrun)
1259 elif values['pcu_id'] in [1012]:
1260 # This pcu sometimes doesn't present the 'Username' prompt,
1261 # unless you immediately try again...
1263 baytech = BayTechGeorgeTown(values, verbose, ['22', '23'])
1264 rb_ret = baytech.reboot(values[nodename], dryrun)
1266 baytech = BayTechGeorgeTown(values, verbose, ['22', '23'])
1267 rb_ret = baytech.reboot(values[nodename], dryrun)
1269 baytech = BayTech(values, verbose, ['22', '23'])
1270 rb_ret = baytech.reboot(values[nodename], dryrun)
1273 elif continue_probe and values['model'].find("ilo") >= 0:
1275 hpilo = HPiLO(values, verbose, ['22'])
1276 rb_ret = hpilo.reboot(0, dryrun)
1278 hpilo = HPiLOHttps(values, verbose, ['443'])
1279 rb_ret = hpilo.reboot(0, dryrun)
1281 hpilo = HPiLOHttps(values, verbose, ['443'])
1282 rb_ret = hpilo.reboot(0, dryrun)
1285 elif continue_probe and values['model'].find("DRAC") >= 0:
1286 # TODO: I don't think DRACRacAdm will throw an exception for the
1287 # default method to catch...
1289 drac = DRACRacAdm(values, verbose, ['443', '5869'])
1290 rb_ret = drac.reboot(0, dryrun)
1292 drac = DRAC(values, verbose, ['22'])
1293 rb_ret = drac.reboot(0, dryrun)
1295 elif continue_probe and values['model'].find("WTI IPS-4") >= 0:
1296 wti = WTIIPS4(values, verbose, ['23'])
1297 rb_ret = wti.reboot(values[nodename], dryrun)
1299 elif continue_probe and values['model'].find("AMT") >= 0:
1300 amt = IntelAMT(values, verbose, ['16992'])
1301 rb_ret = amt.reboot(values[nodename], dryrun)
1303 # BlackBox PSExxx-xx (e.g. PSE505-FR)
1304 elif continue_probe and values['model'].find("ePowerSwitch") >=0:
1305 # TODO: allow a different port than http 80.
1306 if values['pcu_id'] in [1089, 1071, 1046, 1035, 1118]:
1307 eps = ePowerSwitchGood(values, verbose, ['80'])
1308 elif values['pcu_id'] in [1003]:
1311 eps = ePowerSwitch(values, verbose, ['80'])
1313 eps = ePowerSwitchGood(values, verbose, ['80'])
1315 rb_ret = eps.reboot(values[nodename], dryrun)
1316 elif continue_probe and values['pcu_id'] in [1122]:
1317 custom = CustomPCU(values, verbose, ['80', '443'])
1318 custom.reboot(values[nodename], dryrun)
1320 elif continue_probe:
1321 rb_ret = "Unsupported_PCU"
1323 elif continue_probe == False:
1324 if 'portstatus' in values:
1331 except ExceptionPort, err:
1336 #elif continue_probe and values['protocol'] == "racadm" and \
1337 # values['model'] == "RAC":
1338 # rb_ret = racadm_reboot(pcu_name(values),
1339 # values['username'],
1340 # values['password'],
1345 logger.setLevel(logging.DEBUG)
1346 ch = logging.StreamHandler()
1347 ch.setLevel(logging.DEBUG)
1348 formatter = logging.Formatter('LOGGER - %(message)s')
1349 ch.setFormatter(formatter)
1350 logger.addHandler(ch)
1353 if "test" in sys.argv:
1358 for node in sys.argv[1:]:
1359 if node == "test": continue
1361 print "Rebooting %s" % node
1362 if reboot_policy(node, True, dryrun):
1366 except Exception, err:
1367 import traceback; traceback.print_exc()
1370 if __name__ == '__main__':
1372 logger = logging.getLogger("monitor")