3 # Attempt to reboot a node in debug state.
12 from getsshkeys import SSHKnownHosts
20 import ssh.pxssh as pxssh
21 import ssh.fdpexpect as fdpexpect
22 import ssh.pexpect as pexpect
23 from unified_model import *
24 from emailTxt import mailtxt
25 from nodeconfig import network_config_to_str
30 class Sopen(subprocess.Popen):
31 def kill(self, signal = signal.SIGTERM):
32 os.kill(self.pid, signal)
34 #from Rpyc import SocketConnection, Async
35 from Rpyc import SocketConnection, Async
36 from Rpyc.Utils import *
42 fb = database.dbLoad("findbad")
43 fbnode = fb['nodes'][node]['values']
47 def __init__(self, connection, node, config):
52 def get_boot_state(self):
53 if self.c.modules.os.path.exists('/tmp/source'):
55 elif self.c.modules.os.path.exists('/vservers'):
61 self.c.modules.os.system("dmesg > /var/log/dmesg.bm.log")
62 download(self.c, "/var/log/dmesg.bm.log", "log/dmesg.%s.log" % self.node)
63 log = open("log/dmesg.%s.log" % self.node, 'r')
66 def get_bootmanager_log(self):
67 download(self.c, "/tmp/bm.log", "log/bm.%s.log.gz" % self.node)
68 os.system("zcat log/bm.%s.log.gz > log/bm.%s.log" % (self.node, self.node))
69 log = open("log/bm.%s.log" % self.node, 'r')
72 def dump_plconf_file(self):
74 self.c.modules.sys.path.append("/tmp/source/")
75 self.c.modules.os.chdir('/tmp/source')
77 log = c.modules.BootManager.log('/tmp/new.log')
78 bm = c.modules.BootManager.BootManager(log,'boot')
80 BootManagerException = c.modules.Exceptions.BootManagerException
81 InitializeBootManager = c.modules.BootManager.InitializeBootManager
82 ReadNodeConfiguration = c.modules.BootManager.ReadNodeConfiguration
85 InitializeBootManager.Run(bm.VARS, bm.LOG)
86 try: ReadNodeConfiguration.Run(bm.VARS, bm.LOG)
90 print " Possibly, unable to find valid configuration file"
92 if bm_continue and self.config and not self.config.quiet:
93 for key in bm.VARS.keys():
94 print key, " == ", bm.VARS[key]
96 if self.config and not self.config.quiet: print " Unable to read Node Configuration"
99 def compare_and_repair_nodekeys(self):
101 self.c.modules.sys.path.append("/tmp/source/")
102 self.c.modules.os.chdir('/tmp/source')
104 log = c.modules.BootManager.log('/tmp/new.log')
105 bm = c.modules.BootManager.BootManager(log,'boot')
107 BootManagerException = c.modules.Exceptions.BootManagerException
108 InitializeBootManager = c.modules.BootManager.InitializeBootManager
109 ReadNodeConfiguration = c.modules.BootManager.ReadNodeConfiguration
112 plcnode = api.GetNodes({'hostname': self.node}, None)[0]
114 InitializeBootManager.Run(bm.VARS, bm.LOG)
115 try: ReadNodeConfiguration.Run(bm.VARS, bm.LOG)
120 print " Possibly, unable to find valid configuration file"
123 print " NODE: %s" % bm.VARS['NODE_KEY']
124 print " PLC : %s" % plcnode['key']
126 if bm.VARS['NODE_KEY'] == plcnode['key']:
129 if api.UpdateNode(self.node, {'key': bm.VARS['NODE_KEY']}):
130 print " Successfully updated NODE_KEY with PLC"
135 #for key in bm.VARS.keys():
136 # print key, " == ", bm.VARS[key]
138 print " Unable to retrieve NODE_KEY"
140 def bootmanager_running(self):
141 if self.c.modules.os.path.exists('/tmp/BM_RUNNING'):
146 def set_nodestate(self, state='boot'):
147 return api.UpdateNode(self.node, {'boot_state' : state})
149 def restart_node(self, state='boot'):
150 api.UpdateNode(self.node, {'boot_state' : state})
152 pflags = PersistFlags(self.node, 1*60*60*24, db='restart_persistflags')
153 if not pflags.getRecentFlag('gentlekill'):
154 print " Killing all slice processes... : %s" % self.node
155 cmd_slicekill = "ls -d /proc/virtual/[0-9]* | awk -F '/' '{print $4}' | xargs -I{} /usr/sbin/vkill -s 9 --xid {} -- 0"
156 self.c.modules.os.system(cmd_slicekill)
157 cmd = """ shutdown -r +1 & """
158 print " Restarting %s : %s" % ( self.node, cmd)
159 self.c.modules.os.system(cmd)
161 pflags.setRecentFlag('gentlekill')
164 print " Restarting with sysrq 'sub' %s" % self.node
165 cmd = """ (sleep 5; echo 's' > /proc/sysrq-trigger; echo 'u' > /proc/sysrq-trigger; echo 'b' > /proc/sysrq-trigger ) & """
166 self.c.modules.os.system(cmd)
170 def restart_bootmanager(self, forceState):
172 self.c.modules.os.chdir('/tmp/source')
173 if self.c.modules.os.path.exists('/tmp/BM_RUNNING'):
174 print " BootManager is already running: try again soon..."
176 print " Starting 'BootManager.py %s' on %s " % (forceState, self.node)
177 cmd = "( touch /tmp/BM_RUNNING ; " + \
178 " python ./BootManager.py %s &> server.log < /dev/null ; " + \
179 " rm -f /tmp/BM_RUNNING " + \
181 cmd = cmd % forceState
182 self.c.modules.os.system(cmd)
188 class PlanetLabSession:
189 globalport = 22000 + int(random.random()*1000)
191 def __init__(self, node, nosetup, verbose):
192 self.verbose = verbose
195 self.nosetup = nosetup
199 def get_connection(self, config):
200 return NodeConnection(SocketConnection("localhost", self.port), self.node, config)
202 def setup_host(self):
203 self.port = PlanetLabSession.globalport
204 PlanetLabSession.globalport = PlanetLabSession.globalport + 1
207 args['port'] = self.port
208 args['user'] = 'root'
209 args['hostname'] = self.node
210 args['monitordir'] = config.MONITOR_SCRIPT_ROOT
214 print "Skipping setup"
217 # COPY Rpyc files to host
218 cmd = "rsync -qv -az -e ssh %(monitordir)s/Rpyc/ %(user)s@%(hostname)s:Rpyc 2> /dev/null" % args
219 if self.verbose: print cmd
222 localos = moncommands.CMD()
224 ret = localos.system(cmd, timeout)
227 print "\tUNKNOWN SSH KEY FOR %s; making an exception" % self.node
228 #print "MAKE EXPLICIT EXCEPTION FOR %s" % self.node
229 k = SSHKnownHosts(); k.updateDirect(self.node); k.write(); del k
230 ret = localos.system(cmd, timeout)
233 print "\tFAILED TWICE"
235 raise Exception("Failed twice trying to login with updated ssh host key")
238 # KILL any already running servers.
239 ssh = moncommands.SSH(args['user'], args['hostname'], ssh_port)
240 (ov,ev) = ssh.run_noexcept2("""<<\EOF
242 echo "kill server" >> out.log
243 ps ax | grep Rpyc | grep -v grep | awk '{print $1}' | xargs kill 2> /dev/null ;
244 echo "export" >> out.log
245 export PYTHONPATH=$HOME ;
246 echo "start server" >> out.log
247 python Rpyc/Servers/forking_server.py &> server.log &
248 echo "done" >> out.log
250 #cmd = """ssh %(user)s@%(hostname)s """ + \
251 # """'ps ax | grep Rpyc | grep -v grep | awk "{print \$1}" | xargs kill 2> /dev/null' """
253 #if self.verbose: print cmd
255 #print localos.system(cmd,timeout)
257 ## START a new rpyc server.
258 #cmd = """ssh -n %(user)s@%(hostname)s "export PYTHONPATH=\$HOME; """ + \
259 # """python Rpyc/Servers/forking_server.py &> server.log < /dev/null &" """
261 #if self.verbose: print cmd
262 #print localos.system(cmd,timeout)
266 # This was tricky to make synchronous. The combination of ssh-clients-4.7p1,
267 # and the following options seems to work well.
268 cmd = """ssh -o ExitOnForwardFailure=yes -o BatchMode=yes """ + \
269 """-o PermitLocalCommand=yes -o LocalCommand='echo "READY"' """ + \
270 """-o ConnectTimeout=120 """ + \
271 """-n -N -L %(port)s:localhost:18812 """ + \
272 """%(user)s@%(hostname)s"""
274 if self.verbose: print cmd
275 self.command = Sopen(cmd, shell=True, stdout=subprocess.PIPE)
276 # TODO: the read() here may block indefinitely. Need a better
277 # approach therefore, that includes a timeout.
278 #ret = self.command.stdout.read(5)
279 ret = moncommands.read_t(self.command.stdout, 5)
283 # NOTE: There is still a slight race for machines that are slow...
284 self.timeout = 2*(t2-t1)
285 print "Sleeping for %s sec" % self.timeout
286 time.sleep(self.timeout)
289 if self.command.returncode is not None:
290 print "Failed to establish tunnel!"
291 raise Exception("SSH Tunnel exception : %s %s" % (self.node, self.command.returncode))
293 raise Exception("Unknown SSH Tunnel Exception: still running, but did not report 'READY'")
297 if self.verbose: print "Killing SSH session %s" % self.port
301 def steps_to_list(steps):
303 for (id,label) in steps:
304 ret_list.append(label)
307 def index_to_id(steps,index):
308 if index < len(steps):
309 return steps[index][0]
313 def reboot(hostname, config=None, forced_action=None):
315 # NOTE: Nothing works if the bootcd is REALLY old.
316 # So, this is the first step.
317 fbnode = get_fbnode(hostname)
318 if fbnode['category'] == "OLDBOOTCD":
319 print "...NOTIFY OWNER TO UPDATE BOOTCD!!!"
321 args['hostname_list'] = " %s" % hostname
323 m = PersistMessage(hostname, "Please Update Boot Image for %s" % hostname,
324 mailtxt.newbootcd_one[1] % args, True, db='bootcd_persistmessages')
326 loginbase = plc.siteId(hostname)
327 m.send([const.PIEMAIL % loginbase, const.TECHEMAIL % loginbase])
329 print "\tDisabling %s due to out-of-date BOOTCD" % hostname
330 api.UpdateNode(hostname, {'boot_state' : 'disable'})
334 print "Creating session for %s" % node
335 # update known_hosts file (in case the node has rebooted since last run)
336 if config and not config.quiet: print "...updating known_hosts ssh-rsa key for %s" % node
338 k = SSHKnownHosts(); k.update(node); k.write(); del k
340 print traceback.print_exc()
345 session = PlanetLabSession(node, False, True)
347 session = PlanetLabSession(node, config.nosetup, config.verbose)
349 print "ERROR setting up session for %s" % hostname
350 print traceback.print_exc()
355 conn = session.get_connection(config)
357 # NOTE: sometimes the wait in setup_host() is not long enough.
358 # So, here we try to wait a little longer before giving up entirely.
360 time.sleep(session.timeout*4)
361 conn = session.get_connection(config)
363 print traceback.print_exc()
366 if forced_action == "reboot":
367 conn.restart_node('rins')
370 boot_state = conn.get_boot_state()
371 if boot_state == "boot":
372 print "...Boot state of %s already completed : skipping..." % node
374 elif boot_state == "unknown":
375 print "...Unknown bootstate for %s : skipping..."% node
380 if conn.bootmanager_running():
381 print "...BootManager is currently running. Skipping host %s" % node
386 # conn.restart_bootmanager(config.force)
389 # Read persistent flags, tagged on one week intervals.
390 pflags = PersistFlags(hostname, 3*60*60*24, db='debug_persistflags')
393 if config and not config.quiet: print "...downloading dmesg from %s" % node
394 dmesg = conn.get_dmesg()
395 child = fdpexpect.fdspawn(dmesg)
400 ('scsierror' , 'SCSI error : <\d+ \d+ \d+ \d+> return code = 0x\d+'),
401 ('ioerror' , 'end_request: I/O error, dev sd\w+, sector \d+'),
402 ('ccisserror' , 'cciss: cmd \w+ has CHECK CONDITION byte \w+ = \w+'),
404 ('buffererror', 'Buffer I/O error on device dm-\d, logical block \d+'),
406 ('hdaseekerror', 'hda: dma_intr: status=0x\d+ { DriveReady SeekComplete Error }'),
407 ('hdacorrecterror', 'hda: dma_intr: error=0x\d+ { UncorrectableError }, LBAsect=\d+, sector=\d+'),
409 ('atareadyerror' , 'ata\d+: status=0x\d+ { DriveReady SeekComplete Error }'),
410 ('atacorrecterror' , 'ata\d+: error=0x\d+ { UncorrectableError }'),
412 ('sdXerror' , 'sd\w: Current: sense key: Medium Error'),
413 ('ext3error' , 'EXT3-fs error (device dm-\d+): ext3_find_entry: reading directory #\d+ offset \d+'),
415 ('floppytimeout','floppy0: floppy timeout called'),
416 ('floppyerror', 'end_request: I/O error, dev fd\w+, sector \d+'),
418 # hda: dma_intr: status=0x51 { DriveReady SeekComplete Error }
419 # hda: dma_intr: error=0x40 { UncorrectableError }, LBAsect=23331263, sector=23331263
421 # floppy0: floppy timeout called
422 # end_request: I/O error, dev fd0, sector 0
424 # Buffer I/O error on device dm-2, logical block 8888896
425 # ata1: status=0x51 { DriveReady SeekComplete Error }
426 # ata1: error=0x40 { UncorrectableError }
427 # SCSI error : <0 0 0 0> return code = 0x8000002
428 # sda: Current: sense key: Medium Error
429 # Additional sense: Unrecovered read error - auto reallocate failed
431 # SCSI error : <0 2 0 0> return code = 0x40001
432 # end_request: I/O error, dev sda, sector 572489600
434 id = index_to_id(steps, child.expect( steps_to_list(steps) + [ pexpect.EOF ]))
441 if config and not config.quiet: print "\tSET: ", s
444 print "...Potential drive errors on %s" % node
445 if len(s) == 2 and 'floppyerror' in s:
446 print "...Should investigate. Continuing with node."
448 print "...Should investigate. Skipping node."
449 # TODO: send message related to these errors.
451 args['hostname'] = hostname
452 args['log'] = conn.get_dmesg().read()
454 m = PersistMessage(hostname, mailtxt.baddisk[0] % args,
455 mailtxt.baddisk[1] % args, True, db='hardware_persistmessages')
457 loginbase = plc.siteId(hostname)
458 m.send([const.PIEMAIL % loginbase, const.TECHEMAIL % loginbase])
459 conn.set_nodestate('disable')
462 print "...Downloading bm.log from %s" % node
463 log = conn.get_bootmanager_log()
464 child = fdpexpect.fdspawn(log)
467 if config.collect: return True
473 if config and not config.quiet: print "...Scanning bm.log for errors"
479 ('bminit' , 'Initializing the BootManager.'),
480 ('cfg' , 'Reading node configuration file.'),
481 ('auth' , 'Authenticating node with PLC.'),
482 ('getplc' , 'Retrieving details of node from PLC.'),
483 ('update' , 'Updating node boot state at PLC.'),
484 ('hardware' , 'Checking if hardware requirements met.'),
485 ('installinit' , 'Install: Initializing.'),
486 ('installdisk' , 'Install: partitioning disks.'),
487 ('installbootfs', 'Install: bootstrapfs tarball.'),
488 ('installcfg' , 'Install: Writing configuration files.'),
489 ('installstop' , 'Install: Shutting down installer.'),
490 ('update2' , 'Updating node boot state at PLC.'),
491 ('installinit2' , 'Install: Initializing.'),
492 ('validate' , 'Validating node installation.'),
493 ('rebuildinitrd', 'Rebuilding initrd'),
494 ('netcfg' , 'Install: Writing Network Configuration files.'),
495 ('update3' , 'Updating node configuration.'),
496 ('disk' , 'Checking for unused disks to add to LVM.'),
497 ('update4' , 'Sending hardware configuration to PLC.'),
498 ('debug' , 'Starting debug mode'),
499 ('bmexceptmount', 'BootManagerException during mount'),
500 ('bmexceptvgscan', 'BootManagerException during vgscan/vgchange'),
501 ('bmexceptrmfail', 'Unable to remove directory tree: /tmp/mnt'),
502 ('exception' , 'Exception'),
503 ('nocfg' , 'Found configuration file planet.cnf on floppy, but was unable to parse it.'),
504 ('protoerror' , 'XML RPC protocol error'),
505 ('nodehostname' , 'Configured node hostname does not resolve'),
506 ('implementerror', 'Implementation Error'),
507 ('readonlyfs' , '[Errno 30] Read-only file system'),
508 ('noinstall' , 'notinstalled'),
509 ('bziperror' , 'bzip2: Data integrity error when decompressing.'),
510 ('noblockdev' , "No block devices detected."),
511 ('dnserror' , 'Name or service not known'),
512 ('downloadfail' , 'Unable to download main tarball /boot/bootstrapfs-planetlab-i386.tar.bz2 from server.'),
513 ('disktoosmall' , 'The total usable disk size of all disks is insufficient to be usable as a PlanetLab node.'),
514 ('hardwarerequirefail' , 'Hardware requirements not met'),
515 ('mkfsfail' , 'while running: Running mkfs.ext2 -q -m 0 -j /dev/planetlab/vservers failed'),
516 ('nofilereference', "No such file or directory: '/tmp/mnt/sysimg//vservers/.vref/planetlab-f8-i386/etc/hosts'"),
517 ('kernelcopyfail', "cp: cannot stat `/tmp/mnt/sysimg/boot/kernel-boot': No such file or directory"),
518 ('chrootfail' , 'Running chroot /tmp/mnt/sysimg'),
519 ('modulefail' , 'Unable to get list of system modules'),
520 ('writeerror' , 'write error: No space left on device'),
521 ('nospace' , "No space left on device"),
522 ('nonode' , 'Failed to authenticate call: No such node'),
523 ('authfail' , 'Failed to authenticate call: Call could not be authenticated'),
524 ('bootcheckfail' , 'BootCheckAuthentication'),
525 ('bootupdatefail' , 'BootUpdateNode'),
527 list = steps_to_list(steps)
528 index = child.expect( list + [ pexpect.EOF ])
529 id = index_to_id(steps,index)
532 if id == "exception":
533 if config and not config.quiet: print "...Found An Exception!!!"
534 elif index == len(list):
538 s = "-".join(sequence)
539 print " FOUND SEQUENCE: ", s
541 # NOTE: We get or set the flag based on the current sequence identifier.
542 # By using the sequence identifier, we guarantee that there will be no
543 # frequent loops. I'm guessing there is a better way to track loops,
545 #if not config.force and pflags.getRecentFlag(s):
546 # pflags.setRecentFlag(s)
548 # print "... flag is set or it has already run recently. Skipping %s" % node
554 # restart_bootmanager_boot
555 for n in ["bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-update3-disk-update4-done",
556 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-disk-update4-update3-exception-protoerror-update-protoerror-debug-done",
557 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-disk-update4-update3-update3-implementerror-bootupdatefail-update-debug-done",
559 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-disk-update4-update3-update3-exception-protoerror-update-protoerror-debug-done",
561 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-disk-update4-update3-exception-protoerror-update-debug-done",
562 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-disk-update4-update3-exception-chrootfail-update-debug-done",
563 "bminit-cfg-auth-getplc-update-debug-done",
564 "bminit-cfg-auth-getplc-exception-protoerror-update-protoerror-debug-done",
565 "bminit-cfg-auth-protoerror-exception-update-protoerror-debug-done",
566 "bminit-cfg-auth-protoerror-exception-update-bootupdatefail-authfail-debug-done",
567 "bminit-cfg-auth-protoerror-exception-update-debug-done",
568 "bminit-cfg-auth-getplc-exception-protoerror-update-debug-done",
569 "bminit-cfg-auth-getplc-implementerror-update-debug-done",
571 sequences.update({n : "restart_bootmanager_boot"})
573 # conn.restart_bootmanager('rins')
574 for n in [ "bminit-cfg-auth-getplc-installinit-validate-exception-modulefail-update-debug-done",
575 "bminit-cfg-auth-getplc-update-installinit-validate-exception-modulefail-update-debug-done",
576 "bminit-cfg-auth-getplc-installinit-validate-bmexceptmount-exception-noinstall-update-debug-done",
577 "bminit-cfg-auth-getplc-update-installinit-validate-bmexceptmount-exception-noinstall-update-debug-done",
578 "bminit-cfg-auth-getplc-installinit-validate-bmexceptvgscan-exception-noinstall-update-debug-done",
579 "bminit-cfg-auth-getplc-update-installinit-validate-exception-noinstall-update-debug-done",
580 "bminit-cfg-auth-getplc-hardware-installinit-installdisk-bziperror-exception-update-debug-done",
581 "bminit-cfg-auth-getplc-update-hardware-installinit-installdisk-installbootfs-exception-update-debug-done",
582 "bminit-cfg-auth-getplc-update-installinit-validate-bmexceptvgscan-exception-noinstall-update-debug-done",
583 "bminit-cfg-auth-getplc-hardware-installinit-installdisk-installbootfs-exception-update-debug-done",
584 "bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-nofilereference-update-debug-done",
585 "bminit-cfg-auth-getplc-update-hardware-installinit-installdisk-exception-mkfsfail-update-debug-done",
586 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-exception-chrootfail-update-debug-done",
587 "bminit-cfg-auth-getplc-update-hardware-installinit-installdisk-installbootfs-installcfg-installstop-update-installinit-validate-rebuildinitrd-netcfg-disk-update4-update3-update3-kernelcopyfail-exception-update-debug-done",
588 "bminit-cfg-auth-getplc-hardware-installinit-installdisk-installbootfs-installcfg-installstop-update-installinit-validate-rebuildinitrd-netcfg-disk-update4-update3-update3-kernelcopyfail-exception-update-debug-done",
589 "bminit-cfg-auth-getplc-installinit-validate-exception-noinstall-update-debug-done",
591 sequences.update({n : "restart_bootmanager_rins"})
594 sequences.update({"bminit-cfg-auth-bootcheckfail-authfail-exception-update-bootupdatefail-authfail-debug-done": "repair_node_keys"})
596 # conn.restart_node('rins')
597 for n in ["bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-exception-chrootfail-update-debug-done",
598 "bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-update3-disk-update4-exception-chrootfail-update-debug-done",
599 "bminit-cfg-auth-getplc-hardware-installinit-installdisk-installbootfs-installcfg-exception-chrootfail-update-debug-done",
600 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-writeerror-exception-chrootfail-update-debug-done",
601 "bminit-cfg-auth-getplc-update-hardware-installinit-exception-bmexceptrmfail-update-debug-done",
602 "bminit-cfg-auth-getplc-hardware-installinit-exception-bmexceptrmfail-update-debug-done",
603 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-disk-update4-update3-implementerror-bootupdatefail-update-debug-done",
604 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-readonlyfs-update-debug-done",
605 "bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-update3-nospace-exception-update-debug-done",
606 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-nospace-update-debug-done",
607 "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-update-debug-done",
608 "bminit-cfg-auth-getplc-update-hardware-installinit-installdisk-installbootfs-exception-downloadfail-update-debug-done",
610 sequences.update({n : "restart_node_rins"})
613 for n in ["bminit-cfg-auth-getplc-implementerror-bootupdatefail-update-debug-done",
614 "bminit-cfg-auth-implementerror-bootcheckfail-update-debug-done",
615 "bminit-cfg-auth-implementerror-bootcheckfail-update-implementerror-bootupdatefail-done",
616 "bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-nospace-update-debug-done",
617 "bminit-cfg-auth-getplc-hardware-installinit-installdisk-installbootfs-exception-downloadfail-update-debug-done",
619 sequences.update({n: "restart_node_boot"})
621 # update_node_config_email
622 for n in ["bminit-cfg-exception-nocfg-update-bootupdatefail-nonode-debug-done",
623 "bminit-cfg-exception-update-bootupdatefail-nonode-debug-done",
624 "bminit-cfg-auth-bootcheckfail-nonode-exception-update-bootupdatefail-nonode-debug-done",
626 sequences.update({n : "update_node_config_email"})
628 for n in [ "bminit-cfg-exception-nodehostname-update-debug-done",
629 "bminit-cfg-update-exception-nodehostname-update-debug-done",
631 sequences.update({n : "nodenetwork_email"})
633 # update_bootcd_email
634 for n in ["bminit-cfg-auth-getplc-update-hardware-exception-noblockdev-hardwarerequirefail-update-debug-done",
635 "bminit-cfg-auth-getplc-hardware-exception-noblockdev-hardwarerequirefail-update-debug-done",
636 "bminit-cfg-auth-getplc-update-hardware-noblockdev-exception-hardwarerequirefail-update-debug-done",
637 "bminit-cfg-auth-getplc-hardware-noblockdev-exception-hardwarerequirefail-update-debug-done",
638 "bminit-cfg-auth-getplc-hardware-exception-hardwarerequirefail-update-debug-done",
640 sequences.update({n : "update_bootcd_email"})
642 for n in [ "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-nofilereference-update-debug-done",
644 sequences.update({n: "suspect_error_email"})
646 # update_hardware_email
647 sequences.update({"bminit-cfg-auth-getplc-hardware-exception-disktoosmall-hardwarerequirefail-update-debug-done" : "update_hardware_email"})
648 sequences.update({"bminit-cfg-auth-getplc-hardware-disktoosmall-exception-hardwarerequirefail-update-debug-done" : "update_hardware_email"})
650 # broken_hardware_email
651 sequences.update({"bminit-cfg-auth-getplc-update-hardware-exception-hardwarerequirefail-update-debug-done" : "broken_hardware_email"})
655 "bminit-cfg-update-implementerror-bootupdatefail-dnserror-update-implementerror-bootupdatefail-dnserror-done",
656 "bminit-cfg-auth-implementerror-bootcheckfail-dnserror-update-implementerror-bootupdatefail-dnserror-done",
658 sequences.update( { n : "bad_dns_email"})
663 if s not in sequences:
664 print " HOST %s" % hostname
665 print " UNKNOWN SEQUENCE: %s" % s
668 args['hostname'] = hostname
670 args['bmlog'] = conn.get_bootmanager_log().read()
671 m = PersistMessage(hostname, mailtxt.unknownsequence[0] % args,
672 mailtxt.unknownsequence[1] % args, False, db='unknown_persistmessages')
674 m.send(['monitor-list@lists.planet-lab.org'])
676 conn.restart_bootmanager('boot')
678 # NOTE: Do not set the pflags value for this sequence if it's unknown.
679 # This way, we can check it again after we've fixed it.
684 if sequences[s] == "restart_bootmanager_boot":
685 if config and not config.quiet: print "...Restarting BootManager.py on %s "% node
686 conn.restart_bootmanager('boot')
687 elif sequences[s] == "restart_bootmanager_rins":
688 if config and not config.quiet: print "...Restarting BootManager.py on %s "% node
689 conn.restart_bootmanager('rins')
690 elif sequences[s] == "restart_node_rins":
691 conn.restart_node('rins')
692 elif sequences[s] == "restart_node_boot":
693 conn.restart_node('boot')
694 elif sequences[s] == "repair_node_keys":
695 if conn.compare_and_repair_nodekeys():
696 # the keys either are in sync or were forced in sync.
697 # so try to reboot the node again.
698 conn.restart_bootmanager('rins')
701 # there was some failure to synchronize the keys.
702 print "...Unable to repair node keys on %s" % node
704 elif sequences[s] == "suspect_error_email":
706 args['hostname'] = hostname
708 args['bmlog'] = conn.get_bootmanager_log().read()
709 m = PersistMessage(hostname, "Suspicous error from BootManager on %s" % args,
710 mailtxt.unknownsequence[1] % args, False, db='suspect_persistmessages')
712 m.send(['monitor-list@lists.planet-lab.org'])
714 conn.restart_bootmanager('boot')
716 elif sequences[s] == "update_node_config_email":
717 print "...Sending message to UPDATE NODE CONFIG"
719 args['hostname'] = hostname
720 m = PersistMessage(hostname, mailtxt.plnode_cfg[0] % args, mailtxt.plnode_cfg[1] % args,
721 True, db='nodeid_persistmessages')
722 loginbase = plc.siteId(hostname)
723 m.send([const.PIEMAIL % loginbase, const.TECHEMAIL % loginbase])
724 conn.dump_plconf_file()
725 conn.set_nodestate('disable')
727 elif sequences[s] == "nodenetwork_email":
728 print "...Sending message to LOOK AT NODE NETWORK"
730 args['hostname'] = hostname
731 args['bmlog'] = conn.get_bootmanager_log().read()
732 m = PersistMessage(hostname, mailtxt.plnode_network[0] % args, mailtxt.plnode_cfg[1] % args,
733 True, db='nodenet_persistmessages')
734 loginbase = plc.siteId(hostname)
735 m.send([const.PIEMAIL % loginbase, const.TECHEMAIL % loginbase])
736 conn.dump_plconf_file()
737 conn.set_nodestate('disable')
739 elif sequences[s] == "update_bootcd_email":
740 print "...NOTIFY OWNER TO UPDATE BOOTCD!!!"
743 args.update(getconf.getconf(hostname)) # NOTE: Generates boot images for the user:
744 args['hostname_list'] = "%s" % hostname
746 m = PersistMessage(hostname, "Please Update Boot Image for %s" % hostname,
747 mailtxt.newalphacd_one[1] % args, True, db='bootcd_persistmessages')
749 loginbase = plc.siteId(hostname)
750 m.send([const.PIEMAIL % loginbase, const.TECHEMAIL % loginbase])
752 print "\tDisabling %s due to out-of-date BOOTCD" % hostname
753 conn.set_nodestate('disable')
755 elif sequences[s] == "broken_hardware_email":
756 # MAKE An ACTION record that this host has failed hardware. May
757 # require either an exception "/minhw" or other manual intervention.
758 # Definitely need to send out some more EMAIL.
759 print "...NOTIFYING OWNERS OF BROKEN HARDWARE on %s!!!" % hostname
760 # TODO: email notice of broken hardware
762 args['hostname'] = hostname
763 args['log'] = conn.get_dmesg().read()
764 m = PersistMessage(hostname, mailtxt.baddisk[0] % args,
765 mailtxt.baddisk[1] % args, True, db='hardware_persistmessages')
767 loginbase = plc.siteId(hostname)
768 m.send([const.PIEMAIL % loginbase, const.TECHEMAIL % loginbase])
769 conn.set_nodestate('disable')
771 elif sequences[s] == "update_hardware_email":
772 print "...NOTIFYING OWNERS OF MINIMAL HARDWARE FAILURE on %s!!!" % hostname
774 args['hostname'] = hostname
775 args['bmlog'] = conn.get_bootmanager_log().read()
776 m = PersistMessage(hostname, mailtxt.minimalhardware[0] % args,
777 mailtxt.minimalhardware[1] % args, True, db='minhardware_persistmessages')
779 loginbase = plc.siteId(hostname)
780 m.send([const.PIEMAIL % loginbase, const.TECHEMAIL % loginbase])
781 conn.set_nodestate('disable')
783 elif sequences[s] == "bad_dns_email":
784 print "...NOTIFYING OWNERS OF DNS FAILURE on %s!!!" % hostname
787 node = api.GetNodes(hostname)[0]
788 net = api.GetNodeNetworks(node['nodenetwork_ids'])[0]
790 print traceback.print_exc()
791 # TODO: api error. skip email, b/c all info is not available,
792 # flag_set will not be recorded.
794 nodenet_str = network_config_to_str(net)
796 args['hostname'] = hostname
797 args['network_config'] = nodenet_str
798 args['nodenetwork_id'] = net['nodenetwork_id']
799 m = PersistMessage(hostname, mailtxt.baddns[0] % args,
800 mailtxt.baddns[1] % args, True, db='baddns_persistmessages')
802 loginbase = plc.siteId(hostname)
803 m.send([const.PIEMAIL % loginbase, const.TECHEMAIL % loginbase])
804 conn.set_nodestate('disable')
807 pflags.setRecentFlag(s)
813 # MAIN -------------------------------------------------------------------
816 import parser as parsermodule
817 parser = parsermodule.getParser()
819 parser.set_defaults(child=False, collect=False, nosetup=False, verbose=False,
820 force=None, quiet=False)
821 parser.add_option("", "--child", dest="child", action="store_true",
822 help="This is the child mode of this process.")
823 parser.add_option("", "--force", dest="force", metavar="boot_state",
824 help="Force a boot state passed to BootManager.py.")
825 parser.add_option("", "--quiet", dest="quiet", action="store_true",
826 help="Extra quiet output messages.")
827 parser.add_option("", "--verbose", dest="verbose", action="store_true",
828 help="Extra debug output messages.")
829 parser.add_option("", "--nonet", dest="nonet", action="store_true",
830 help="Do not setup the network, use existing log files to re-run a test pass.")
831 parser.add_option("", "--collect", dest="collect", action="store_true",
832 help="No action, just collect dmesg, and bm.log")
833 parser.add_option("", "--nosetup", dest="nosetup", action="store_true",
834 help="Do not perform the orginary setup phase.")
836 parser = parsermodule.getParser(['nodesets', 'defaults'], parser)
837 config = parsermodule.parse_args(parser)
840 nodes = config.getListFromFile(config.nodelist)
842 nodes = [ config.node ]
850 if __name__ == "__main__":