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 class IPAL(PCUControl):
281 This now uses a proprietary format for communicating with the PCU. I
282 prefer it to Telnet, and Web access, since it's much lighter weight
283 and, more importantly, IT WORKS!! HHAHHHAHAHAHAHAHA!
286 def format_msg(self, data, cmd):
287 esc = chr(int('1b',16))
288 return "%c%s%c%s%c" % (esc, self.password, esc, data, cmd) # esc, 'q', chr(4))
290 def recv_noblock(self, s, count):
294 # TODO: make sleep backoff, before stopping.
296 ret = s.recv(count, socket.MSG_DONTWAIT)
297 except socket.error, e:
298 if e[0] == errno.EAGAIN:
299 raise Exception(e[1])
301 # TODO: not other exceptions.
305 def run(self, node_port, dryrun):
311 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
314 s.connect((self.host, 9100))
315 except socket.error, e:
317 if e[0] == errno.ECONNREFUSED:
318 # cannot connect to remote host
319 raise Exception(e[1])
321 # TODO: what other conditions are there?
325 print "Checking status"
326 s.send(self.format_msg("", 'O'))
327 ret = self.recv_noblock(s, 8)
328 print "Current status is '%s'" % ret
331 raise Exception("Status returned 'another session already open' %s : %s" % (node_port, ret))
334 if node_port < len(ret):
335 status = ret[node_port]
343 raise Exception("Unknown status for PCU socket %s : %s" % (node_port, ret))
345 raise Exception("Mismatch between configured port and PCU status: %s %s" % (node_port, ret))
350 print "Pulsing %s" % node_port
351 s.send(self.format_msg("%s" % node_port, 'P'))
353 # NOTE: turn power on ; do not pulse the port.
354 print "Power was off, so turning on ..."
355 s.send(self.format_msg("%s" % node_port, 'E'))
356 #s.send(self.format_msg("%s" % node_port, 'P'))
358 print "Receiving response."
359 ret = self.recv_noblock(s, 8)
360 print "Current status is '%s'" % ret
362 if node_port < len(ret):
363 status = ret[node_port]
371 raise Exception("Unknown status for PCU socket %s : %s" % (node_port, ret))
373 raise Exception("Mismatch between configured port and PCU status: %s %s" % (node_port, ret))
378 return "Failed Power On"
383 # TELNET version of protocol...
384 # #self.open(self.host)
385 # ## XXX Some iPals require you to hit Enter a few times first
386 # #self.ifThenSend("Password >", "\r\n\r\n", ExceptionNotFound)
388 # self.ifThenSend("Password >", self.password, ExceptionPassword)
389 # self.transport.write("\r\n\r\n")
390 # if not dryrun: # P# - Pulse relay
391 # print "node_port %s" % node_port
392 # self.ifThenSend("Enter >",
393 # "P7", # % node_port,
395 # print "send newlines"
396 # self.transport.write("\r\n\r\n")
397 # print "after new lines"
398 # # Get the next prompt
399 # print "wait for enter"
400 # self.ifElse("Enter >", ExceptionTimeout)
405 class APCEurope(PCUControl):
406 def run(self, node_port, dryrun):
407 self.open(self.host, self.username)
408 self.sendPassword(self.password)
410 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
411 self.ifThenSend("\r\n> ", "2")
412 self.ifThenSend("\r\n> ", str(node_port))
413 # 3- Immediate Reboot
414 self.ifThenSend("\r\n> ", "3")
417 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
421 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
422 "", ExceptionSequence)
423 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
428 class APCBrazil(PCUControl):
429 def run(self, node_port, dryrun):
430 self.open(self.host, self.username)
431 self.sendPassword(self.password)
433 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
434 self.ifThenSend("\r\n> ", str(node_port))
435 # 4- Immediate Reboot
436 self.ifThenSend("\r\n> ", "4")
439 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
443 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
444 "", ExceptionSequence)
445 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
450 class APCBerlin(PCUControl):
451 def run(self, node_port, dryrun):
452 self.open(self.host, self.username)
453 self.sendPassword(self.password)
455 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
456 self.ifThenSend("\r\n> ", "2")
457 self.ifThenSend("\r\n> ", "1")
458 self.ifThenSend("\r\n> ", str(node_port))
459 # 3- Immediate Reboot
460 self.ifThenSend("\r\n> ", "3")
463 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
467 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
468 "", ExceptionSequence)
469 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
474 class APCFolsom(PCUControl):
475 def run(self, node_port, dryrun):
476 self.open(self.host, self.username)
477 self.sendPassword(self.password)
479 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
480 self.ifThenSend("\r\n> ", "2")
481 self.ifThenSend("\r\n> ", "1")
482 self.ifThenSend("\r\n> ", str(node_port))
483 self.ifThenSend("\r\n> ", "1")
485 # 3- Immediate Reboot
486 self.ifThenSend("\r\n> ", "3")
489 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
493 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
494 "", ExceptionSequence)
495 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
500 class APCMaster(PCUControl):
501 def run(self, node_port, dryrun):
502 print "Rebooting %s" % self.host
503 self.open(self.host, self.username)
504 self.sendPassword(self.password)
507 self.ifThenSend("\r\n> ", "1", ExceptionPassword)
508 # 3- Outlet Control/Config
509 self.ifThenSend("\r\n> ", "3")
511 self.ifThenSend("\r\n> ", str(node_port))
513 self.ifThenSend("\r\n> ", "1")
514 # 3- Immediate Reboot
515 self.ifThenSend("\r\n> ", "3")
518 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
522 self.ifThenSend("Enter 'YES' to continue or <ENTER> to cancel",
523 "", ExceptionSequence)
524 self.ifThenSend("Press <ENTER> to continue...", "", ExceptionSequence)
529 class APC(PCUControl):
530 def __init__(self, plc_pcu_record, verbose):
531 PCUControl.__init__(self, plc_pcu_record, verbose)
533 self.master = APCMaster(plc_pcu_record, verbose)
534 self.folsom = APCFolsom(plc_pcu_record, verbose)
535 self.europe = APCEurope(plc_pcu_record, verbose)
537 def run(self, node_port, dryrun):
541 for pcu in [self.master, self.europe, self.folsom]:
544 print "-*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*"
547 time.sleep(sleep_time)
548 ret = pcu.reboot(node_port, dryrun)
549 except ExceptionSequence, err:
555 return "Unknown reboot sequence for APC PCU"
559 class IntelAMT(PCUControl):
560 def run(self, node_port, dryrun):
562 cmd = moncommands.CMD()
563 #[cmd_str = "IntelAMTSDK/Samples/RemoteControl/remoteControl"
564 cmd_str = "cmdamt/remoteControl"
567 # NOTE: -p checks the power state of the host.
568 # TODO: parse the output to find out if it's ok or not.
569 cmd_str += " -p http://%s:16992/RemoteControlService -user admin -pass '%s' " % (self.host, self.password )
571 cmd_str += " -A http://%s:16992/RemoteControlService -user admin -pass '%s' " % (self.host, self.password )
574 return cmd.system(cmd_str, self.TELNET_TIMEOUT)
576 class DRACRacAdm(PCUControl):
577 def run(self, node_port, dryrun):
579 print "trying racadm_reboot..."
580 racadm_reboot(self.host, self.username, self.password, node_port, dryrun)
584 class DRAC(PCUControl):
585 def run(self, node_port, dryrun):
586 self.open(self.host, self.username)
587 self.sendPassword(self.password)
589 print "logging in..."
590 self.transport.write("\r\n")
593 self.ifThenSend("[%s]#" % self.username, "getsysinfo")
596 self.ifThenSend("[%s]#" % self.username, "serveraction powercycle")
598 self.ifThenSend("[%s]#" % self.username, "exit")
603 class HPiLO(PCUControl):
604 def run(self, node_port, dryrun):
605 self.open(self.host, self.username)
606 self.sendPassword(self.password)
609 self.ifThenSend("</>hpiLO->", "cd system1")
611 # Reboot Outlet N (Y/N)?
613 self.ifThenSend("</system1>hpiLO->", "POWER")
616 self.ifThenSend("</system1>hpiLO->", "reset")
618 self.ifThenSend("</system1>hpiLO->", "exit")
624 class HPiLOHttps(PCUControl):
625 def run(self, node_port, dryrun):
627 locfg = moncommands.CMD()
628 cmd = "cmdhttps/locfg.pl -s %s -f %s -u %s -p '%s' | grep 'MESSAGE' | grep -v 'No error'" % (
629 self.host, "iloxml/Get_Network.xml",
630 self.username, self.password)
631 sout, serr = locfg.run_noexcept(cmd)
633 if sout.strip() != "":
634 print "sout: %s" % sout.strip()
638 locfg = moncommands.CMD()
639 cmd = "cmdhttps/locfg.pl -s %s -f %s -u %s -p '%s' | grep 'MESSAGE' | grep -v 'No error'" % (
640 self.host, "iloxml/Reset_Server.xml",
641 self.username, self.password)
642 sout, serr = locfg.run_noexcept(cmd)
644 if sout.strip() != "":
645 print "sout: %s" % sout.strip()
649 class BayTechAU(PCUControl):
650 def run(self, node_port, dryrun):
651 self.open(self.host, self.username, None, "Enter user name:")
652 self.sendPassword(self.password, "Enter Password:")
654 #self.ifThenSend("RPC-16>", "Status")
655 self.ifThenSend("RPC3-NC>", "Reboot %d" % node_port)
657 # Reboot Outlet N (Y/N)?
659 self.ifThenSend("(Y/N)?", "N")
661 self.ifThenSend("(Y/N)?", "Y")
662 self.ifThenSend("RPC3-NC>", "")
667 class BayTechGeorgeTown(PCUControl):
668 def run(self, node_port, dryrun):
669 self.open(self.host, self.username, None, "Enter user name:")
670 self.sendPassword(self.password, "Enter Password:")
672 #self.ifThenSend("RPC-16>", "Status")
674 self.ifThenSend("RPC-16>", "Reboot %d" % node_port)
676 # Reboot Outlet N (Y/N)?
678 self.ifThenSend("(Y/N)?", "N")
680 self.ifThenSend("(Y/N)?", "Y")
681 self.ifThenSend("RPC-16>", "")
686 class BayTechCtrlCUnibe(PCUControl):
688 For some reason, these units let you log in fine, but they hang
689 indefinitely, unless you send a Ctrl-C after the password. No idea
692 def run(self, node_port, dryrun):
693 print "BayTechCtrlC %s" % self.host
695 ssh_options="-o StrictHostKeyChecking=no -o PasswordAuthentication=yes -o PubkeyAuthentication=no"
697 if not s.login(self.host, self.username, self.password, ssh_options):
698 raise ExceptionPassword("Invalid Password")
699 # Otherwise, the login succeeded.
701 # Send a ctrl-c to the remote process.
702 print "sending ctrl-c"
705 # Control Outlets (5 ,1).........5
708 print "Enter Request" in s.before
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 # NOTE: for some reason, the script times out with the
790 # following line. In manual tests, it works correctly, but
791 # with automated tests, evidently it fails.
792 #index = s.expect(["DS-RPC>"])
793 #print "got prompt back"
798 raise ExceptionPrompt("EOF before 'Enter Request' Prompt")
799 except pexpect.TIMEOUT:
800 raise ExceptionPrompt("Timeout before Prompt")
804 class BayTech(PCUControl):
805 def run(self, node_port, dryrun):
806 self.open(self.host, self.username)
807 self.sendPassword(self.password)
809 # Control Outlets (5 ,1).........5
810 self.ifThenSend("Enter Request :", "5")
814 self.ifThenSend("DS-RPC>", "Reboot %d" % node_port, ExceptionNotFound)
815 except ExceptionNotFound, msg:
816 # one machine is configured to ask for a username,
817 # even after login...
818 print "msg: %s" % msg
819 self.transport.write(self.username + "\r\n")
820 self.ifThenSend("DS-RPC>", "Reboot %d" % node_port)
822 # Reboot Outlet N (Y/N)?
824 self.ifThenSend("(Y/N)?", "N")
826 self.ifThenSend("(Y/N)?", "Y")
827 self.ifThenSend("DS-RPC>", "")
832 class WTIIPS4(PCUControl):
833 def run(self, node_port, dryrun):
835 self.sendPassword(self.password, "Enter Password:")
837 self.ifThenSend("IPS> ", "/Boot %s" % node_port)
839 self.ifThenSend("Sure? (Y/N): ", "N")
841 self.ifThenSend("Sure? (Y/N): ", "Y")
843 self.ifThenSend("IPS> ", "")
848 class ePowerSwitchGood(PCUControl):
850 # The old code used Python's HTTPPasswordMgrWithDefaultRealm()
851 # For some reason this both doesn't work and in some cases, actually
852 # hangs the PCU. Definitely not what we want.
854 # The code below is much simpler. Just letting things fail first,
855 # and then, trying again with authentication string in the header.
857 def run(self, node_port, dryrun):
858 self.transport = None
859 self.url = "http://%s:%d/" % (self.host,80)
860 uri = "%s:%d" % (self.host,80)
862 req = urllib2.Request(self.url)
864 handle = urllib2.urlopen(req)
866 # NOTE: this is expected to fail initially
873 return "ERROR: not protected by HTTP authentication"
875 if not hasattr(e, 'code') or e.code != 401:
876 return "ERROR: failed for: %s" % str(e)
878 base64data = base64.encodestring("%s:%s" % (self.username, self.password))[:-1]
879 # NOTE: assuming basic realm authentication.
880 authheader = "Basic %s" % base64data
881 req.add_header("Authorization", authheader)
884 f = urllib2.urlopen(req)
886 # failing here means the User/passwd is wrong (hopefully)
887 raise ExceptionPassword("Incorrect username/password")
889 # NOTE: after verifying that the user/password is correct,
890 # actually reboot the given node.
893 data = urllib.urlencode({'P%d' % node_port : "r"})
894 req = urllib2.Request(self.url + "cmd.html")
895 req.add_header("Authorization", authheader)
896 # add data to handler,
897 f = urllib2.urlopen(req, data)
898 if self.verbose: print f.read()
900 import traceback; traceback.print_exc()
902 # fetch url one more time on cmd.html, econtrol.html or whatever.
905 if self.verbose: print f.read()
910 class CustomPCU(PCUControl):
911 def run(self, node_port, dryrun):
912 url = "https://www-itec.uni-klu.ac.at/plab-pcu/index.php"
915 # Turn host off, then on
916 formstr = "plab%s=off" % node_port
917 os.system("curl --user %s:%s --form '%s' --insecure %s" % (self.username, self.password, formstr, url))
919 formstr = "plab%s=on" % node_port
920 os.system("curl --user %s:%s --form '%s' --insecure %s" % (self.username, self.password, formstr, url))
922 os.system("curl --user %s:%s --insecure %s" % (self.username, self.password, url))
925 class ePowerSwitchOld(PCUControl):
926 def run(self, node_port, dryrun):
927 self.url = "http://%s:%d/" % (self.host,80)
928 uri = "%s:%d" % (self.host,80)
931 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
932 authinfo.add_password (None, uri, self.username, self.password)
933 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
935 # NOTE: it doesn't seem to matter whether this authinfo is here or not.
936 transport = urllib2.build_opener(authinfo)
937 f = transport.open(self.url)
938 if self.verbose: print f.read()
941 transport = urllib2.build_opener(authhandler)
942 f = transport.open(self.url + "cmd.html", "P%d=r" % node_port)
943 if self.verbose: print f.read()
948 class ePowerSwitch(PCUControl):
949 def run(self, node_port, dryrun):
950 self.url = "http://%s:%d/" % (self.host,80)
951 uri = "%s:%d" % (self.host,80)
953 # TODO: I'm still not sure what the deal is here.
954 # two independent calls appear to need to be made before the
955 # reboot will succeed. It doesn't seem to be possible to do
956 # this with a single call. I have no idea why.
959 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
960 authinfo.add_password (None, uri, self.username, self.password)
961 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
963 # NOTE: it doesn't seem to matter whether this authinfo is here or not.
964 transport = urllib2.build_opener()
965 f = transport.open(self.url + "elogin.html", "pwd=%s" % self.password)
966 if self.verbose: print f.read()
969 transport = urllib2.build_opener(authhandler)
970 f = transport.open(self.url + "econtrol.html", "P%d=r" % node_port)
971 if self.verbose: print f.read()
973 # data= "P%d=r" % node_port
974 #self.open(self.host, self.username, self.password)
975 #self.sendHTTP("elogin.html", "pwd=%s" % self.password)
976 #self.sendHTTP("econtrol.html", data)
977 #self.sendHTTP("cmd.html", data)
983 ### rebooting european BlackBox PSE boxes
984 # Thierry Parmentelat - May 11 2005
985 # tested on 4-ports models known as PSE505-FR
986 # uses http to POST a data 'P<port>=r'
987 # relies on basic authentication within http1.0
988 # first curl-based script was
989 # curl --http1.0 --basic --user <username>:<password> --data P<port>=r \
990 # http://<hostname>:<http_port>/cmd.html && echo OK
992 def bbpse_reboot (pcu_ip,username,password,port_in_pcu,http_port, dryrun):
996 url = "http://%s:%d/cmd.html" % (pcu_ip,http_port)
997 data= "P%d=r" % port_in_pcu
999 logger.debug("POSTing '%s' on %s" % (data,url))
1001 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
1002 uri = "%s:%d" % (pcu_ip,http_port)
1003 authinfo.add_password (None, uri, username, password)
1004 authhandler = urllib2.HTTPBasicAuthHandler( authinfo )
1006 opener = urllib2.build_opener(authhandler)
1007 urllib2.install_opener(opener)
1013 f = urllib2.urlopen(url,data)
1020 except urllib2.URLError,err:
1021 logger.info('Could not open http connection', err)
1022 return "bbpse error"
1024 ### rebooting x10toggle based systems addressed by port
1025 # Marc E. Fiuczynski - May 31 2005
1026 # tested on 4-ports models known as PSE505-FR
1027 # uses ssh and password to login to an account
1028 # that will cause the system to be powercycled.
1030 def x10toggle_reboot(ip, username, password, port, dryrun):
1035 ssh = pyssh.Ssh(username, ip)
1039 telnet_answer(ssh, "password:", password)
1043 telnet_answer(ssh, "x10toggle>", "A%d" % port)
1046 output = ssh.close()
1048 logger.debug(output)
1051 except Exception, err:
1055 output = ssh.close()
1057 logger.debug(output)
1058 return errno.ETIMEDOUT
1060 ### rebooting Dell systems via RAC card
1061 # Marc E. Fiuczynski - June 01 2005
1062 # tested with David Lowenthal's itchy/scratchy nodes at UGA
1065 def runcmd(command, args, username, password, timeout = None):
1068 result_ready = threading.Condition()
1072 result_ready.acquire()
1076 result_ready.notify()
1077 result_ready.release()
1079 def do_command(command, username, password):
1082 # Popen4 is a popen-type class that combines stdout and stderr
1083 p = popen2.Popen4(command)
1085 # read all output data
1086 p.tochild.write("%s\n" % username)
1087 p.tochild.write("%s\n" % password)
1089 data = p.fromchild.read()
1092 # might get interrupted by a signal in poll() or waitpid()
1095 set_result((retval, data))
1098 if ex.errno == errno.EINTR:
1101 except Exception, ex:
1105 command = " ".join([command] + args)
1107 worker = threading.Thread(target = do_command, args = (command, username, password, ))
1108 worker.setDaemon(True)
1109 result_ready.acquire()
1111 result_ready.wait(timeout)
1113 if result == [None]:
1114 raise Exception, "command timed-out: '%s'" % command
1116 result_ready.release()
1119 if isinstance(result, Exception):
1122 (retval, data) = result
1123 if os.WIFEXITED(retval) and os.WEXITSTATUS(retval) == 0:
1126 out = "system command ('%s') " % command
1127 if os.WIFEXITED(retval):
1128 out += "failed, rc = %d" % os.WEXITSTATUS(retval)
1130 out += "killed by signal %d" % os.WTERMSIG(retval)
1132 out += "; output follows:\n" + data
1133 raise Exception, out
1135 def racadm_reboot(host, username, password, port, dryrun):
1138 ip = socket.gethostbyname(host)
1140 cmd = "/usr/sbin/racadm"
1143 output = runcmd(cmd, ["-r %s -i serveraction powercycle" % ip],
1146 output = runcmd(cmd, ["-r %s -i getsysinfo" % ip],
1149 print "RUNCMD: %s" % output
1151 logger.debug(output)
1154 except Exception, err:
1155 logger.debug("runcmd raised exception %s" % err)
1161 if pcu['hostname'] is not None and pcu['hostname'] is not "":
1162 return pcu['hostname']
1163 elif pcu['ip'] is not None and pcu['ip'] is not "":
1169 from monitor import database
1172 def get_pcu_values(pcu_id):
1175 # this shouldn't be loaded each time...
1176 fb = database.dbLoad("findbadpcus")
1179 values = fb['nodes']["id_%s" % pcu_id]['values']
1185 def reboot(nodename):
1186 return reboot_policy(nodename, True, False)
1188 def reboot_policy(nodename, continue_probe, dryrun):
1191 pcu = plc.getpcu(nodename)
1193 logger.debug("no pcu for %s" % hostname)
1194 print "no pcu for %s" % hostname
1195 return False # "%s has no pcu" % nodename
1197 values = get_pcu_values(pcu['pcu_id'])
1199 logger.debug("No values for pcu probe %s" % hostname)
1200 print "No values for pcu probe %s" % hostname
1201 return False #"no info for pcu_id %s" % pcu['pcu_id']
1204 logger.debug("Trying PCU %s %s" % (pcu['hostname'], pcu['model']))
1206 ret = reboot_test(nodename, values, continue_probe, verbose, dryrun)
1215 def reboot_test(nodename, values, continue_probe, verbose, dryrun):
1219 # DataProbe iPal (many sites)
1220 if continue_probe and values['model'].find("IP-41x_IP-81x") >= 0:
1221 ipal = IPAL(values, verbose, ['23', '80', '9100'])
1222 rb_ret = ipal.reboot(values[nodename], dryrun)
1224 # APC Masterswitch (Berkeley)
1225 elif continue_probe and ( values['model'].find("AP79xx") >= 0 or \
1226 values['model'].find("Masterswitch") >= 0 ):
1229 # TODO: make a more robust version of APC
1230 if values['pcu_id'] in [1163,1055,1111,1231,1113,1127,1128,1148]:
1231 apc = APCEurope(values, verbose, ['22', '23'])
1232 rb_ret = apc.reboot(values[nodename], dryrun)
1234 elif values['pcu_id'] in [1110,86]:
1235 apc = APCBrazil(values, verbose, ['22', '23'])
1236 rb_ret = apc.reboot(values[nodename], dryrun)
1238 elif values['pcu_id'] in [1221,1225]:
1239 apc = APCBerlin(values, verbose, ['22', '23'])
1240 rb_ret = apc.reboot(values[nodename], dryrun)
1242 elif values['pcu_id'] in [1173,1221,1220]:
1243 apc = APCFolsom(values, verbose, ['22', '23'])
1244 rb_ret = apc.reboot(values[nodename], dryrun)
1247 apc = APCMaster(values, verbose, ['22', '23'])
1248 rb_ret = apc.reboot(values[nodename], dryrun)
1251 elif continue_probe and values['model'].find("DS4-RPC") >= 0:
1252 if values['pcu_id'] in [1237,1052,1209,1002,1008,1041,1013,1022]:
1253 # These require a 'ctrl-c' to be sent...
1254 baytech = BayTechCtrlC(values, verbose, ['22', '23'])
1255 rb_ret = baytech.reboot(values[nodename], dryrun)
1257 elif values['pcu_id'] in [93]:
1258 baytech = BayTechAU(values, verbose, ['22', '23'])
1259 rb_ret = baytech.reboot(values[nodename], dryrun)
1261 elif values['pcu_id'] in [1057]:
1262 # These require a 'ctrl-c' to be sent...
1263 baytech = BayTechCtrlCUnibe(values, verbose, ['22', '23'])
1264 rb_ret = baytech.reboot(values[nodename], dryrun)
1266 elif values['pcu_id'] in [1012]:
1267 # This pcu sometimes doesn't present the 'Username' prompt,
1268 # unless you immediately try again...
1270 baytech = BayTechGeorgeTown(values, verbose, ['22', '23'])
1271 rb_ret = baytech.reboot(values[nodename], dryrun)
1273 baytech = BayTechGeorgeTown(values, verbose, ['22', '23'])
1274 rb_ret = baytech.reboot(values[nodename], dryrun)
1276 baytech = BayTech(values, verbose, ['22', '23'])
1277 rb_ret = baytech.reboot(values[nodename], dryrun)
1280 elif continue_probe and values['model'].find("ilo") >= 0:
1282 hpilo = HPiLO(values, verbose, ['22'])
1283 rb_ret = hpilo.reboot(0, dryrun)
1285 hpilo = HPiLOHttps(values, verbose, ['443'])
1286 rb_ret = hpilo.reboot(0, dryrun)
1288 hpilo = HPiLOHttps(values, verbose, ['443'])
1289 rb_ret = hpilo.reboot(0, dryrun)
1292 elif continue_probe and values['model'].find("DRAC") >= 0:
1293 # TODO: I don't think DRACRacAdm will throw an exception for the
1294 # default method to catch...
1296 drac = DRACRacAdm(values, verbose, ['443', '5869'])
1297 rb_ret = drac.reboot(0, dryrun)
1299 drac = DRAC(values, verbose, ['22'])
1300 rb_ret = drac.reboot(0, dryrun)
1302 elif continue_probe and values['model'].find("WTI IPS-4") >= 0:
1303 wti = WTIIPS4(values, verbose, ['23'])
1304 rb_ret = wti.reboot(values[nodename], dryrun)
1306 elif continue_probe and values['model'].find("AMT") >= 0:
1307 amt = IntelAMT(values, verbose, ['16992'])
1308 rb_ret = amt.reboot(values[nodename], dryrun)
1310 # BlackBox PSExxx-xx (e.g. PSE505-FR)
1311 elif continue_probe and values['model'].find("ePowerSwitch") >=0:
1312 # TODO: allow a different port than http 80.
1313 if values['pcu_id'] in [1089, 1071, 1046, 1035, 1118]:
1314 eps = ePowerSwitchGood(values, verbose, ['80'])
1315 elif values['pcu_id'] in [1003]:
1318 eps = ePowerSwitch(values, verbose, ['80'])
1320 eps = ePowerSwitchGood(values, verbose, ['80'])
1322 rb_ret = eps.reboot(values[nodename], dryrun)
1323 elif continue_probe and values['pcu_id'] in [1122]:
1324 custom = CustomPCU(values, verbose, ['80', '443'])
1325 custom.reboot(values[nodename], dryrun)
1327 elif continue_probe:
1328 rb_ret = "Unsupported_PCU"
1330 elif continue_probe == False:
1331 if 'portstatus' in values:
1338 except ExceptionPort, err:
1343 #elif continue_probe and values['protocol'] == "racadm" and \
1344 # values['model'] == "RAC":
1345 # rb_ret = racadm_reboot(pcu_name(values),
1346 # values['username'],
1347 # values['password'],
1352 logger.setLevel(logging.DEBUG)
1353 ch = logging.StreamHandler()
1354 ch.setLevel(logging.DEBUG)
1355 formatter = logging.Formatter('LOGGER - %(message)s')
1356 ch.setFormatter(formatter)
1357 logger.addHandler(ch)
1360 if "test" in sys.argv:
1365 for node in sys.argv[1:]:
1366 if node == "test": continue
1368 print "Rebooting %s" % node
1369 if reboot_policy(node, True, dryrun):
1373 except Exception, err:
1374 import traceback; traceback.print_exc()
1377 if __name__ == '__main__':
1379 logger = logging.getLogger("monitor")