error caused by older versions of python on newer code.
[monitor.git] / bootman.py
1 #!/usr/bin/python
2
3 # Attempt to reboot a node in debug state.
4
5 import plc
6 api = plc.getAuthAPI()
7
8 import sys
9 import os
10 import const
11
12 from getsshkeys import SSHKnownHosts
13
14 import subprocess
15 import time
16 import database
17 import moncommands
18 from sets import Set
19
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
26 import traceback
27 import config
28
29 import signal
30 class Sopen(subprocess.Popen):
31         def kill(self, signal = signal.SIGTERM):
32                 os.kill(self.pid, signal)
33
34 #from Rpyc import SocketConnection, Async
35 from Rpyc import SocketConnection, Async
36 from Rpyc.Utils import *
37 fb = None
38
39 def get_fbnode(node):
40         global fb
41         if fb is None:
42                 fb = database.dbLoad("findbad")
43         fbnode = fb['nodes'][node]['values']
44         return fbnode
45
46 class NodeConnection:
47         def __init__(self, connection, node, config):
48                 self.node = node
49                 self.c = connection
50                 self.config = config
51
52         def get_boot_state(self):
53                 if self.c.modules.os.path.exists('/tmp/source'):
54                         return "dbg"
55                 elif self.c.modules.os.path.exists('/vservers'): 
56                         return "boot"
57                 else:
58                         return "unknown"
59
60         def get_dmesg(self):
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')
64                 return log
65
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')
70                 return log
71
72         def dump_plconf_file(self):
73                 c = self.c
74                 self.c.modules.sys.path.append("/tmp/source/")
75                 self.c.modules.os.chdir('/tmp/source')
76
77                 log = c.modules.BootManager.log('/tmp/new.log')
78                 bm = c.modules.BootManager.BootManager(log,'boot')
79
80                 BootManagerException = c.modules.Exceptions.BootManagerException
81                 InitializeBootManager = c.modules.BootManager.InitializeBootManager
82                 ReadNodeConfiguration = c.modules.BootManager.ReadNodeConfiguration
83                 bm_continue = True
84
85                 InitializeBootManager.Run(bm.VARS, bm.LOG)
86                 try: ReadNodeConfiguration.Run(bm.VARS, bm.LOG)
87                 except Exception, x:
88                         bm_continue = False
89                         print "   ERROR:", x
90                         print "   Possibly, unable to find valid configuration file"
91
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]
95                 else:
96                         if self.config and not self.config.quiet: print "   Unable to read Node Configuration"
97                 
98
99         def compare_and_repair_nodekeys(self):
100                 c = self.c
101                 self.c.modules.sys.path.append("/tmp/source/")
102                 self.c.modules.os.chdir('/tmp/source')
103
104                 log = c.modules.BootManager.log('/tmp/new.log')
105                 bm = c.modules.BootManager.BootManager(log,'boot')
106
107                 BootManagerException = c.modules.Exceptions.BootManagerException
108                 InitializeBootManager = c.modules.BootManager.InitializeBootManager
109                 ReadNodeConfiguration = c.modules.BootManager.ReadNodeConfiguration
110                 bm_continue = True
111
112                 plcnode = api.GetNodes({'hostname': self.node}, None)[0]
113
114                 InitializeBootManager.Run(bm.VARS, bm.LOG)
115                 try: ReadNodeConfiguration.Run(bm.VARS, bm.LOG)
116                 except Exception, x:
117                         bm_continue = False
118                         print "exception"
119                         print x
120                         print "   Possibly, unable to find valid configuration file"
121
122                 if bm_continue:
123                         print "   NODE: %s" % bm.VARS['NODE_KEY']
124                         print "   PLC : %s" % plcnode['key']
125
126                         if bm.VARS['NODE_KEY'] == plcnode['key']:
127                                 return True
128                         else:
129                                 if api.UpdateNode(self.node, {'key': bm.VARS['NODE_KEY']}):
130                                         print "   Successfully updated NODE_KEY with PLC"
131                                         return True
132                                 else:
133                                         return False
134                                 
135                         #for key in bm.VARS.keys():
136                         #       print key, " == ", bm.VARS[key]
137                 else:
138                         print "   Unable to retrieve NODE_KEY"
139
140         def bootmanager_running(self):
141                 if self.c.modules.os.path.exists('/tmp/BM_RUNNING'):
142                         return True
143                 else:
144                         return False
145
146         def set_nodestate(self, state='boot'):
147                 return api.UpdateNode(self.node, {'boot_state' : state})
148
149         def restart_node(self, state='boot'):
150                 api.UpdateNode(self.node, {'boot_state' : state})
151
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)
160
161                         pflags.setRecentFlag('gentlekill')
162                         pflags.save()
163                 else:
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)
167
168                 return
169
170         def restart_bootmanager(self, forceState):
171
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..."
175                 else:
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 " + \
180                                   ") &" 
181                         cmd = cmd % forceState
182                         self.c.modules.os.system(cmd)
183
184                 return 
185
186
187 import random
188 class PlanetLabSession:
189         globalport = 22000 + int(random.random()*1000)
190
191         def __init__(self, node, nosetup, verbose):
192                 self.verbose = verbose
193                 self.node = node
194                 self.port = None
195                 self.nosetup = nosetup
196                 self.command = None
197                 self.setup_host()
198
199         def get_connection(self, config):
200                 return NodeConnection(SocketConnection("localhost", self.port), self.node, config)
201         
202         def setup_host(self):
203                 self.port = PlanetLabSession.globalport
204                 PlanetLabSession.globalport = PlanetLabSession.globalport + 1
205
206                 args = {}
207                 args['port'] = self.port
208                 args['user'] = 'root'
209                 args['hostname'] = self.node
210                 args['monitordir'] = config.MONITOR_SCRIPT_ROOT
211                 ssh_port = 22
212
213                 if self.nosetup:
214                         print "Skipping setup"
215                         return 
216
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
220                 # TODO: Add timeout
221                 timeout = 120
222                 localos = moncommands.CMD()
223
224                 ret = localos.system(cmd, timeout)
225                 print ret
226                 if ret != 0:
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)
231                         print ret
232                         if ret != 0:
233                                 print "\tFAILED TWICE"
234                                 #sys.exit(1)
235                                 raise Exception("Failed twice trying to login with updated ssh host key")
236
237                 t1 = time.time()
238                 # KILL any already running servers.
239                 ssh = moncommands.SSH(args['user'], args['hostname'], ssh_port)
240                 (ov,ev) = ssh.run_noexcept2("""<<\EOF
241             rm -f out.log
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
249 EOF""")
250                 #cmd = """ssh %(user)s@%(hostname)s """ + \
251                 #        """'ps ax | grep Rpyc | grep -v grep | awk "{print \$1}" | xargs kill 2> /dev/null' """
252                 #cmd = cmd % args
253                 #if self.verbose: print cmd
254                 ## TODO: Add timeout
255                 #print localos.system(cmd,timeout)
256
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 &" """ 
260                 #cmd = cmd % args
261                 #if self.verbose: print cmd
262                 #print localos.system(cmd,timeout)
263                 print ssh.ret
264
265                 # TODO: Add 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"""
273                 cmd = cmd % args
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)
280
281                 t2 = time.time()
282                 if 'READY' in ret:
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)
287                         return
288
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))
292
293                 raise Exception("Unknown SSH Tunnel Exception: still running, but did not report 'READY'")
294
295         def __del__(self):
296                 if self.command:
297                         if self.verbose: print "Killing SSH session %s" % self.port
298                         self.command.kill()
299
300
301 def steps_to_list(steps):
302         ret_list = []
303         for (id,label) in steps:
304                 ret_list.append(label)
305         return ret_list
306
307 def index_to_id(steps,index):
308         if index < len(steps):
309                 return steps[index][0]
310         else:
311                 return "done"
312
313 def reboot(hostname, config=None, forced_action=None):
314
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!!!"
320                 args = {}
321                 args['hostname_list'] = "    %s" % hostname
322
323                 m = PersistMessage(hostname, "Please Update Boot Image for %s" % hostname,
324                                                         mailtxt.newbootcd_one[1] % args, True, db='bootcd_persistmessages')
325
326                 loginbase = plc.siteId(hostname)
327                 emails = plc.getTechEmails(loginbase)
328                 m.send(emails) 
329
330                 print "\tDisabling %s due to out-of-date BOOTCD" % hostname
331                 api.UpdateNode(hostname, {'boot_state' : 'disable'})
332                 return True
333
334         node = hostname
335         print "Creating session for %s" % node
336         # update known_hosts file (in case the node has rebooted since last run)
337         if config and not config.quiet: print "...updating known_hosts ssh-rsa key for %s" % node
338         try:
339                 k = SSHKnownHosts(); k.update(node); k.write(); del k
340         except:
341                 print traceback.print_exc()
342                 return False
343
344         try:
345                 if config == None:
346                         session = PlanetLabSession(node, False, True)
347                 else:
348                         session = PlanetLabSession(node, config.nosetup, config.verbose)
349         except Exception, e:
350                 print "ERROR setting up session for %s" % hostname
351                 print traceback.print_exc()
352                 print e
353                 return False
354
355         try:
356                 conn = session.get_connection(config)
357         except EOFError:
358                 # NOTE: sometimes the wait in setup_host() is not long enough.  
359                 # So, here we try to wait a little longer before giving up entirely.
360                 try:
361                         time.sleep(session.timeout*4)
362                         conn = session.get_connection(config)
363                 except:
364                         print traceback.print_exc()
365                         return False
366
367         if forced_action == "reboot":
368                 conn.restart_node('rins')
369                 return True
370
371         boot_state = conn.get_boot_state()
372         if boot_state == "boot":
373                 print "...Boot state of %s already completed : skipping..." % node
374                 return True
375         elif boot_state == "unknown":
376                 print "...Unknown bootstate for %s : skipping..."% node
377                 return False
378         else:
379                 pass
380
381         if conn.bootmanager_running():
382                 print "...BootManager is currently running.  Skipping host %s" % node
383                 return True
384
385         #if config != None:
386         #       if config.force:
387         #               conn.restart_bootmanager(config.force)
388         #               return True
389
390         # Read persistent flags, tagged on one week intervals.
391         pflags = PersistFlags(hostname, 3*60*60*24, db='debug_persistflags')
392                 
393
394         if config and not config.quiet: print "...downloading dmesg from %s" % node
395         dmesg = conn.get_dmesg()
396         child = fdpexpect.fdspawn(dmesg)
397
398         sequence = []
399         while True:
400                 steps = [
401                         ('scsierror'  , 'SCSI error : <\d+ \d+ \d+ \d+> return code = 0x\d+'),
402                         ('ioerror'    , 'end_request: I/O error, dev sd\w+, sector \d+'),
403                         ('ccisserror' , 'cciss: cmd \w+ has CHECK CONDITION  byte \w+ = \w+'),
404
405                         ('buffererror', 'Buffer I/O error on device dm-\d, logical block \d+'),
406
407                         ('hdaseekerror', 'hda: dma_intr: status=0x\d+ { DriveReady SeekComplete Error }'),
408                         ('hdacorrecterror', 'hda: dma_intr: error=0x\d+ { UncorrectableError }, LBAsect=\d+, sector=\d+'),
409
410                         ('atareadyerror'   , 'ata\d+: status=0x\d+ { DriveReady SeekComplete Error }'),
411                         ('atacorrecterror' , 'ata\d+: error=0x\d+ { UncorrectableError }'),
412
413                         ('sdXerror'   , 'sd\w: Current: sense key: Medium Error'),
414                         ('ext3error'   , 'EXT3-fs error (device dm-\d+): ext3_find_entry: reading directory #\d+ offset \d+'),
415
416                         ('floppytimeout','floppy0: floppy timeout called'),
417                         ('floppyerror',  'end_request: I/O error, dev fd\w+, sector \d+'),
418
419                         # hda: dma_intr: status=0x51 { DriveReady SeekComplete Error }
420                         # hda: dma_intr: error=0x40 { UncorrectableError }, LBAsect=23331263, sector=23331263
421
422                         # floppy0: floppy timeout called
423                         # end_request: I/O error, dev fd0, sector 0
424
425                         # Buffer I/O error on device dm-2, logical block 8888896
426                         # ata1: status=0x51 { DriveReady SeekComplete Error }
427                         # ata1: error=0x40 { UncorrectableError }
428                         # SCSI error : <0 0 0 0> return code = 0x8000002
429                         # sda: Current: sense key: Medium Error
430                         #       Additional sense: Unrecovered read error - auto reallocate failed
431
432                         # SCSI error : <0 2 0 0> return code = 0x40001
433                         # end_request: I/O error, dev sda, sector 572489600
434                 ]
435                 id = index_to_id(steps, child.expect( steps_to_list(steps) + [ pexpect.EOF ]))
436                 sequence.append(id)
437
438                 if id == "done":
439                         break
440
441         s = Set(sequence)
442         if config and not config.quiet: print "\tSET: ", s
443
444         if len(s) > 1:
445                 print "...Potential drive errors on %s" % node
446                 if len(s) == 2 and 'floppyerror' in s:
447                         print "...Should investigate.  Continuing with node."
448                 else:
449                         print "...Should investigate.  Skipping node."
450                         # TODO: send message related to these errors.
451                         args = {}
452                         args['hostname'] = hostname
453                         args['log'] = conn.get_dmesg().read()
454
455                         m = PersistMessage(hostname, mailtxt.baddisk[0] % args,
456                                                                                  mailtxt.baddisk[1] % args, True, db='hardware_persistmessages')
457
458                         loginbase = plc.siteId(hostname)
459                         emails = plc.getTechEmails(loginbase)
460                         m.send(emails) 
461                         conn.set_nodestate('disable')
462                         return False
463
464         print "...Downloading bm.log from %s" % node
465         log = conn.get_bootmanager_log()
466         child = fdpexpect.fdspawn(log)
467
468         try:
469                 if config.collect: return True
470         except:
471                 pass
472
473         time.sleep(1)
474
475         if config and not config.quiet: print "...Scanning bm.log for errors"
476         action_id = "dbg"
477         sequence = []
478         while True:
479
480                 steps = [
481                         ('bminit'               , 'Initializing the BootManager.'),
482                         ('cfg'                  , 'Reading node configuration file.'),
483                         ('auth'                 , 'Authenticating node with PLC.'),
484                         ('getplc'               , 'Retrieving details of node from PLC.'),
485                         ('update'               , 'Updating node boot state at PLC.'),
486                         ('hardware'             , 'Checking if hardware requirements met.'),
487                         ('installinit'  , 'Install: Initializing.'),
488                         ('installdisk'  , 'Install: partitioning disks.'),
489                         ('installbootfs', 'Install: bootstrapfs tarball.'),
490                         ('installcfg'   , 'Install: Writing configuration files.'),
491                         ('installstop'  , 'Install: Shutting down installer.'),
492                         ('update2'              , 'Updating node boot state at PLC.'),
493                         ('installinit2' , 'Install: Initializing.'),
494                         ('validate'             , 'Validating node installation.'),
495                         ('rebuildinitrd', 'Rebuilding initrd'),
496                         ('netcfg'               , 'Install: Writing Network Configuration files.'),
497                         ('update3'              , 'Updating node configuration.'),
498                         ('disk'                 , 'Checking for unused disks to add to LVM.'),
499                         ('update4'              , 'Sending hardware configuration to PLC.'),
500                         ('debug'                , 'Starting debug mode'),
501                         ('bmexceptmount', 'BootManagerException during mount'),
502                         ('bmexceptvgscan', 'BootManagerException during vgscan/vgchange'),
503                         ('bmexceptrmfail', 'Unable to remove directory tree: /tmp/mnt'),
504                         ('exception'    , 'Exception'),
505                         ('nocfg'        , 'Found configuration file planet.cnf on floppy, but was unable to parse it.'),
506                         ('protoerror'   , 'XML RPC protocol error'),
507                         ('nodehostname' , 'Configured node hostname does not resolve'),
508                         ('implementerror', 'Implementation Error'),
509                         ('readonlyfs'   , '[Errno 30] Read-only file system'),
510                         ('noinstall'    , 'notinstalled'),
511                         ('bziperror'    , 'bzip2: Data integrity error when decompressing.'),
512                         ('noblockdev'   , "No block devices detected."),
513                         ('dnserror'     , 'Name or service not known'),
514                         ('downloadfail' , 'Unable to download main tarball /boot/bootstrapfs-planetlab-i386.tar.bz2 from server.'),
515                         ('disktoosmall' , 'The total usable disk size of all disks is insufficient to be usable as a PlanetLab node.'),
516                         ('hardwarerequirefail' , 'Hardware requirements not met'),
517                         ('mkfsfail'         , 'while running: Running mkfs.ext2 -q  -m 0 -j /dev/planetlab/vservers failed'),
518                         ('nofilereference', "No such file or directory: '/tmp/mnt/sysimg//vservers/.vref/planetlab-f8-i386/etc/hosts'"),
519                         ('kernelcopyfail', "cp: cannot stat `/tmp/mnt/sysimg/boot/kernel-boot': No such file or directory"),
520                         ('chrootfail'   , 'Running chroot /tmp/mnt/sysimg'),
521                         ('modulefail'   , 'Unable to get list of system modules'),
522                         ('writeerror'   , 'write error: No space left on device'),
523                         ('nospace'      , "No space left on device"),
524                         ('nonode'       , 'Failed to authenticate call: No such node'),
525                         ('authfail'     , 'Failed to authenticate call: Call could not be authenticated'),
526                         ('bootcheckfail'     , 'BootCheckAuthentication'),
527                         ('bootupdatefail'   , 'BootUpdateNode'),
528                 ]
529                 list = steps_to_list(steps)
530                 index = child.expect( list + [ pexpect.EOF ])
531                 id = index_to_id(steps,index)
532                 sequence.append(id)
533
534                 if id == "exception":
535                         if config and not config.quiet: print "...Found An Exception!!!"
536                 elif index == len(list):
537                         #print "Reached EOF"
538                         break
539                 
540         s = "-".join(sequence)
541         print "   FOUND SEQUENCE: ", s
542
543         # NOTE: We get or set the flag based on the current sequence identifier.
544         #  By using the sequence identifier, we guarantee that there will be no
545         #  frequent loops.  I'm guessing there is a better way to track loops,
546         #  though.
547         #if not config.force and pflags.getRecentFlag(s):
548         #       pflags.setRecentFlag(s)
549         #       pflags.save() 
550         #       print "... flag is set or it has already run recently. Skipping %s" % node
551         #       return True
552
553         sequences = {}
554
555
556         # restart_bootmanager_boot
557         for n in ["bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-update3-disk-update4-done",
558                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-disk-update4-update3-exception-protoerror-update-protoerror-debug-done",
559                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-disk-update4-update3-update3-implementerror-bootupdatefail-update-debug-done",
560
561                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-disk-update4-update3-update3-exception-protoerror-update-protoerror-debug-done",
562
563                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-disk-update4-update3-exception-protoerror-update-debug-done",
564                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-disk-update4-update3-exception-chrootfail-update-debug-done",
565                         "bminit-cfg-auth-getplc-update-debug-done",
566                         "bminit-cfg-auth-getplc-exception-protoerror-update-protoerror-debug-done",
567                         "bminit-cfg-auth-protoerror-exception-update-protoerror-debug-done",
568                         "bminit-cfg-auth-protoerror-exception-update-bootupdatefail-authfail-debug-done",
569                         "bminit-cfg-auth-protoerror-exception-update-debug-done",
570                         "bminit-cfg-auth-getplc-exception-protoerror-update-debug-done",
571                         "bminit-cfg-auth-getplc-implementerror-update-debug-done",
572                         ]:
573                 sequences.update({n : "restart_bootmanager_boot"})
574
575         #       conn.restart_bootmanager('rins')
576         for n in [ "bminit-cfg-auth-getplc-installinit-validate-exception-modulefail-update-debug-done",
577                         "bminit-cfg-auth-getplc-update-installinit-validate-exception-modulefail-update-debug-done",
578                         "bminit-cfg-auth-getplc-installinit-validate-bmexceptmount-exception-noinstall-update-debug-done",
579                         "bminit-cfg-auth-getplc-update-installinit-validate-bmexceptmount-exception-noinstall-update-debug-done",
580                         "bminit-cfg-auth-getplc-installinit-validate-bmexceptvgscan-exception-noinstall-update-debug-done",
581                         "bminit-cfg-auth-getplc-update-installinit-validate-exception-noinstall-update-debug-done",
582                         "bminit-cfg-auth-getplc-hardware-installinit-installdisk-bziperror-exception-update-debug-done",
583                         "bminit-cfg-auth-getplc-update-hardware-installinit-installdisk-installbootfs-exception-update-debug-done",
584                         "bminit-cfg-auth-getplc-update-installinit-validate-bmexceptvgscan-exception-noinstall-update-debug-done",
585                         "bminit-cfg-auth-getplc-hardware-installinit-installdisk-installbootfs-exception-update-debug-done",
586                         "bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-nofilereference-update-debug-done",
587                         "bminit-cfg-auth-getplc-update-hardware-installinit-installdisk-exception-mkfsfail-update-debug-done",
588                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-exception-chrootfail-update-debug-done",
589                         "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",
590                         "bminit-cfg-auth-getplc-hardware-installinit-installdisk-installbootfs-installcfg-installstop-update-installinit-validate-rebuildinitrd-netcfg-disk-update4-update3-update3-kernelcopyfail-exception-update-debug-done",
591                         "bminit-cfg-auth-getplc-installinit-validate-exception-noinstall-update-debug-done",
592                         # actual solution appears to involve removing the bad files, and
593                         # continually trying to boot the node.
594                         "bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-disk-update4-update3-update3-implementerror-update-debug-done",
595                         ]:
596                 sequences.update({n : "restart_bootmanager_rins"})
597
598         # repair_node_keys
599         sequences.update({"bminit-cfg-auth-bootcheckfail-authfail-exception-update-bootupdatefail-authfail-debug-done": "repair_node_keys"})
600
601         #   conn.restart_node('rins')
602         for n in ["bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-exception-chrootfail-update-debug-done",
603                         "bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-update3-disk-update4-exception-chrootfail-update-debug-done",
604                         "bminit-cfg-auth-getplc-hardware-installinit-installdisk-installbootfs-installcfg-exception-chrootfail-update-debug-done",
605                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-writeerror-exception-chrootfail-update-debug-done",
606                         "bminit-cfg-auth-getplc-update-hardware-installinit-exception-bmexceptrmfail-update-debug-done",
607                         "bminit-cfg-auth-getplc-hardware-installinit-exception-bmexceptrmfail-update-debug-done",
608                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-disk-update4-update3-implementerror-bootupdatefail-update-debug-done",
609                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-readonlyfs-update-debug-done",
610                         "bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-update3-nospace-exception-update-debug-done",
611                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-nospace-update-debug-done",
612                         "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-update-debug-done",
613                         "bminit-cfg-auth-getplc-update-hardware-installinit-installdisk-installbootfs-exception-downloadfail-update-debug-done",
614                         ]:
615                 sequences.update({n : "restart_node_rins"})
616
617         #       restart_node_boot
618         for n in ["bminit-cfg-auth-getplc-implementerror-bootupdatefail-update-debug-done",
619                          "bminit-cfg-auth-implementerror-bootcheckfail-update-debug-done",
620                          "bminit-cfg-auth-implementerror-bootcheckfail-update-implementerror-bootupdatefail-done",
621                          "bminit-cfg-auth-getplc-update-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-nospace-update-debug-done",
622                          "bminit-cfg-auth-getplc-hardware-installinit-installdisk-installbootfs-exception-downloadfail-update-debug-done",
623                          "bminit-cfg-auth-getplc-update-installinit-validate-implementerror-update-debug-done",
624                          ]:
625                 sequences.update({n: "restart_node_boot"})
626
627         # update_node_config_email
628         for n in ["bminit-cfg-exception-nocfg-update-bootupdatefail-nonode-debug-done",
629                           "bminit-cfg-exception-update-bootupdatefail-nonode-debug-done",
630                           "bminit-cfg-auth-bootcheckfail-nonode-exception-update-bootupdatefail-nonode-debug-done",
631                         ]:
632                 sequences.update({n : "update_node_config_email"})
633
634         for n in [ "bminit-cfg-exception-nodehostname-update-debug-done", 
635                            "bminit-cfg-update-exception-nodehostname-update-debug-done", 
636                         ]:
637                 sequences.update({n : "nodenetwork_email"})
638
639         # update_bootcd_email
640         for n in ["bminit-cfg-auth-getplc-update-hardware-exception-noblockdev-hardwarerequirefail-update-debug-done",
641                         "bminit-cfg-auth-getplc-hardware-exception-noblockdev-hardwarerequirefail-update-debug-done",
642                         "bminit-cfg-auth-getplc-update-hardware-noblockdev-exception-hardwarerequirefail-update-debug-done",
643                         "bminit-cfg-auth-getplc-hardware-noblockdev-exception-hardwarerequirefail-update-debug-done",
644                         "bminit-cfg-auth-getplc-hardware-exception-hardwarerequirefail-update-debug-done",
645                         ]:
646                 sequences.update({n : "update_bootcd_email"})
647
648         for n in [ "bminit-cfg-auth-getplc-installinit-validate-rebuildinitrd-netcfg-update3-implementerror-nofilereference-update-debug-done",
649                         ]:
650                 sequences.update({n: "suspect_error_email"})
651
652         # update_hardware_email
653         sequences.update({"bminit-cfg-auth-getplc-hardware-exception-disktoosmall-hardwarerequirefail-update-debug-done" : "update_hardware_email"})
654         sequences.update({"bminit-cfg-auth-getplc-hardware-disktoosmall-exception-hardwarerequirefail-update-debug-done" : "update_hardware_email"})
655
656         # broken_hardware_email
657         sequences.update({"bminit-cfg-auth-getplc-update-hardware-exception-hardwarerequirefail-update-debug-done" : "broken_hardware_email"})
658
659         # bad_dns_email
660         for n in [ 
661          "bminit-cfg-update-implementerror-bootupdatefail-dnserror-update-implementerror-bootupdatefail-dnserror-done",
662                 "bminit-cfg-auth-implementerror-bootcheckfail-dnserror-update-implementerror-bootupdatefail-dnserror-done",
663                 ]:
664                 sequences.update( { n : "bad_dns_email"})
665
666         flag_set = True
667
668         
669         if s not in sequences:
670                 print "   HOST %s" % hostname
671                 print "   UNKNOWN SEQUENCE: %s" % s
672
673                 args = {}
674                 args['hostname'] = hostname
675                 args['sequence'] = s
676                 args['bmlog'] = conn.get_bootmanager_log().read()
677                 m = PersistMessage(hostname, mailtxt.unknownsequence[0] % args,
678                                                                          mailtxt.unknownsequence[1] % args, False, db='unknown_persistmessages')
679                 m.reset()
680                 m.send([config.cc_email]) 
681
682                 conn.restart_bootmanager('boot')
683
684                 # NOTE: Do not set the pflags value for this sequence if it's unknown.
685                 # This way, we can check it again after we've fixed it.
686                 flag_set = False
687
688         else:
689
690                 if   sequences[s] == "restart_bootmanager_boot":
691                         if config and not config.quiet: print "...Restarting BootManager.py on %s "% node
692                         conn.restart_bootmanager('boot')
693                 elif sequences[s] == "restart_bootmanager_rins":
694                         if config and not config.quiet: print "...Restarting BootManager.py on %s "% node
695                         conn.restart_bootmanager('rins')
696                 elif sequences[s] == "restart_node_rins":
697                         conn.restart_node('rins')
698                 elif sequences[s] == "restart_node_boot":
699                         conn.restart_node('boot')
700                 elif sequences[s] == "repair_node_keys":
701                         if conn.compare_and_repair_nodekeys():
702                                 # the keys either are in sync or were forced in sync.
703                                 # so try to reboot the node again.
704                                 conn.restart_bootmanager('rins')
705                                 pass
706                         else:
707                                 # there was some failure to synchronize the keys.
708                                 print "...Unable to repair node keys on %s" % node
709
710                 elif sequences[s] == "suspect_error_email":
711                         args = {}
712                         args['hostname'] = hostname
713                         args['sequence'] = s
714                         args['bmlog'] = conn.get_bootmanager_log().read()
715                         m = PersistMessage(hostname, "Suspicous error from BootManager on %s" % args,
716                                                                                  mailtxt.unknownsequence[1] % args, False, db='suspect_persistmessages')
717                         m.reset()
718                         m.send([config.cc_email]) 
719
720                         conn.restart_bootmanager('boot')
721
722                 elif sequences[s] == "update_node_config_email":
723                         print "...Sending message to UPDATE NODE CONFIG"
724                         args = {}
725                         args['hostname'] = hostname
726                         m = PersistMessage(hostname,  mailtxt.plnode_cfg[0] % args,  mailtxt.plnode_cfg[1] % args, 
727                                                                 True, db='nodeid_persistmessages')
728                         loginbase = plc.siteId(hostname)
729                         emails = plc.getTechEmails(loginbase)
730                         m.send(emails) 
731                         conn.dump_plconf_file()
732                         conn.set_nodestate('disable')
733
734                 elif sequences[s] == "nodenetwork_email":
735                         print "...Sending message to LOOK AT NODE NETWORK"
736                         args = {}
737                         args['hostname'] = hostname
738                         args['bmlog'] = conn.get_bootmanager_log().read()
739                         m = PersistMessage(hostname,  mailtxt.plnode_network[0] % args,  mailtxt.plnode_cfg[1] % args, 
740                                                                 True, db='nodenet_persistmessages')
741                         loginbase = plc.siteId(hostname)
742                         emails = plc.getTechEmails(loginbase)
743                         m.send(emails) 
744                         conn.dump_plconf_file()
745                         conn.set_nodestate('disable')
746
747                 elif sequences[s] == "update_bootcd_email":
748                         print "...NOTIFY OWNER TO UPDATE BOOTCD!!!"
749                         import getconf
750                         args = {}
751                         args.update(getconf.getconf(hostname)) # NOTE: Generates boot images for the user:
752                         args['hostname_list'] = "%s" % hostname
753
754                         m = PersistMessage(hostname, "Please Update Boot Image for %s" % hostname,
755                                                                 mailtxt.newalphacd_one[1] % args, True, db='bootcd_persistmessages')
756
757                         loginbase = plc.siteId(hostname)
758                         emails = plc.getTechEmails(loginbase)
759                         m.send(emails) 
760
761                         print "\tDisabling %s due to out-of-date BOOTCD" % hostname
762                         conn.set_nodestate('disable')
763
764                 elif sequences[s] == "broken_hardware_email":
765                         # MAKE An ACTION record that this host has failed hardware.  May
766                         # require either an exception "/minhw" or other manual intervention.
767                         # Definitely need to send out some more EMAIL.
768                         print "...NOTIFYING OWNERS OF BROKEN HARDWARE on %s!!!" % hostname
769                         # TODO: email notice of broken hardware
770                         args = {}
771                         args['hostname'] = hostname
772                         args['log'] = conn.get_dmesg().read()
773                         m = PersistMessage(hostname, mailtxt.baddisk[0] % args,
774                                                                                  mailtxt.baddisk[1] % args, True, db='hardware_persistmessages')
775
776                         loginbase = plc.siteId(hostname)
777                         emails = plc.getTechEmails(loginbase)
778                         m.send(emails) 
779                         conn.set_nodestate('disable')
780
781                 elif sequences[s] == "update_hardware_email":
782                         print "...NOTIFYING OWNERS OF MINIMAL HARDWARE FAILURE on %s!!!" % hostname
783                         args = {}
784                         args['hostname'] = hostname
785                         args['bmlog'] = conn.get_bootmanager_log().read()
786                         m = PersistMessage(hostname, mailtxt.minimalhardware[0] % args,
787                                                                                  mailtxt.minimalhardware[1] % args, True, db='minhardware_persistmessages')
788
789                         loginbase = plc.siteId(hostname)
790                         emails = plc.getTechEmails(loginbase)
791                         m.send(emails) 
792                         conn.set_nodestate('disable')
793
794                 elif sequences[s] == "bad_dns_email":
795                         print "...NOTIFYING OWNERS OF DNS FAILURE on %s!!!" % hostname
796                         args = {}
797                         try:
798                                 node = api.GetNodes(hostname)[0]
799                                 net = api.GetNodeNetworks(node['nodenetwork_ids'])[0]
800                         except:
801                                 print traceback.print_exc()
802                                 # TODO: api error. skip email, b/c all info is not available,
803                                 # flag_set will not be recorded.
804                                 return False
805                         nodenet_str = network_config_to_str(net)
806
807                         args['hostname'] = hostname
808                         args['network_config'] = nodenet_str
809                         args['nodenetwork_id'] = net['nodenetwork_id']
810                         m = PersistMessage(hostname, mailtxt.baddns[0] % args,
811                                                                                  mailtxt.baddns[1] % args, True, db='baddns_persistmessages')
812
813                         loginbase = plc.siteId(hostname)
814                         emails = plc.getTechEmails(loginbase)
815                         m.send(emails) 
816                         conn.set_nodestate('disable')
817
818         if flag_set:
819                 pflags.setRecentFlag(s)
820                 pflags.save() 
821
822         return True
823         
824
825 # MAIN -------------------------------------------------------------------
826
827 def main():
828         import parser as parsermodule
829         parser = parsermodule.getParser()
830
831         parser.set_defaults(child=False, collect=False, nosetup=False, verbose=False, 
832                                                 force=None, quiet=False)
833         parser.add_option("", "--child", dest="child", action="store_true", 
834                                                 help="This is the child mode of this process.")
835         parser.add_option("", "--force", dest="force", metavar="boot_state",
836                                                 help="Force a boot state passed to BootManager.py.")
837         parser.add_option("", "--quiet", dest="quiet", action="store_true", 
838                                                 help="Extra quiet output messages.")
839         parser.add_option("", "--verbose", dest="verbose", action="store_true", 
840                                                 help="Extra debug output messages.")
841         parser.add_option("", "--nonet", dest="nonet", action="store_true", 
842                                                 help="Do not setup the network, use existing log files to re-run a test pass.")
843         parser.add_option("", "--collect", dest="collect", action="store_true", 
844                                                 help="No action, just collect dmesg, and bm.log")
845         parser.add_option("", "--nosetup", dest="nosetup", action="store_true", 
846                                                 help="Do not perform the orginary setup phase.")
847
848         parser = parsermodule.getParser(['nodesets', 'defaults'], parser)
849         config = parsermodule.parse_args(parser)
850
851         if config.nodelist:
852                 nodes = config.getListFromFile(config.nodelist)
853         elif config.node:
854                 nodes = [ config.node ]
855         else:
856                 parser.print_help()
857                 sys.exit(1)
858
859         for node in nodes:
860                 reboot(node, config)
861
862 if __name__ == "__main__":
863         main()