6 # Copyright (c) 2003 Intel Corporation
9 # Copyright (c) 2004-2006 The Trustees of Princeton University
10 # All rights reserved.
13 import sys, os, traceback
18 from Exceptions import *
19 import notify_messages
20 import BootServerRequest
22 # all output is written to this file
23 BM_NODE_LOG= "/tmp/bm.log"
24 VARS_FILE = "configuration"
26 # the new contents of PATH when the boot manager is running
27 BIN_PATH= ('/usr/local/bin',
34 def read_configuration_file(filename):
35 # read in and store all variables in VARS_FILE into each line
36 # is in the format name=val (any whitespace around the = is
37 # removed. everything after the = to the end of the line is
40 vars_file= file(filename,'r')
42 for line in vars_file:
43 # if its a comment or a whitespace line, ignore
44 if line[:1] == "#" or string.strip(line) == "":
47 parts= string.split(line,"=")
50 raise Exception( "Invalid line in vars file: %s" % line )
52 name= string.strip(parts[0])
53 value= string.strip(parts[1])
54 value= value.replace("'", "") # remove quotes
55 value= value.replace('"', "") # remove quotes
60 raise Exception( "Unable to read configuration vars." )
62 # find out which directory we are running it, and set a variable
63 # for that. future steps may need to get files out of the bootmanager
65 current_dir= os.getcwd()
66 vars['BM_SOURCE_DIR']= current_dir
70 ##############################
73 format="%H:%M:%S(%Z) "
75 def __init__( self, OutputFilePath= None ):
77 self.OutputFile= open( OutputFilePath, "w")
78 self.OutputFilePath= OutputFilePath
80 print( "bootmanager log : Unable to open output file %r, continuing"%OutputFilePath )
85 vars = read_configuration_file(VARS_FILE)
88 self.LogEntry( str(e) )
91 def LogEntry( self, str, inc_newline= 1, display_screen= 1 ):
92 now=time.strftime(log.format, time.localtime())
94 self.OutputFile.write( now+str )
96 sys.stdout.write( now+str )
100 sys.stdout.write( "\n" )
102 self.OutputFile.write( "\n" )
105 self.OutputFile.flush()
107 def write( self, str ):
109 make log behave like a writable file object (for traceback
112 self.LogEntry( str, 0, 1 )
114 # bm log uploading is available back again, as of nodeconfig-5.0-2
117 upload the contents of the log to the server
119 if self.OutputFile is not None:
120 self.OutputFile.flush()
122 self.LogEntry( "Uploading logs to %s" % self.VARS['UPLOAD_LOG_SCRIPT'] )
124 self.OutputFile.close()
125 self.OutputFile= None
127 hostname= self.VARS['INTERFACE_SETTINGS']['hostname'] + "." + \
128 self.VARS['INTERFACE_SETTINGS']['domainname']
129 bs_request = BootServerRequest.BootServerRequest(self.VARS)
131 # this was working until f10
132 bs_request.MakeRequest(PartialPath = self.VARS['UPLOAD_LOG_SCRIPT'],
133 GetVars = None, PostVars = None,
134 DoSSL = True, DoCertCheck = True,
135 FormData = ["log=@" + self.OutputFilePath,
136 "hostname=" + hostname,
141 bs_request.MakeRequest(PartialPath = self.VARS['UPLOAD_LOG_SCRIPT'],
142 GetVars = None, PostVars = None,
143 DoSSL = True, DoCertCheck = True,
144 FormData = [('log',(pycurl.FORM_FILE, self.OutputFilePath)),
145 ("hostname",hostname),
149 ##############################
152 # file containing initial variables/constants
154 # the set of valid node run states
155 NodeRunStates = {'reinstall':None,
161 def __init__(self, log, forceState):
162 # override machine's current state from the command line
163 self.forceState = forceState
165 # the main logging point
168 # set to 1 if we can run after initialization
172 # this contains a set of information used and updated by each step
177 # not sure what the current PATH is set to, replace it with what
178 # we know will work with all the boot cds
179 os.environ['PATH']= string.join(BIN_PATH,":")
185 core boot manager logic.
187 the way errors are handled is as such: if any particular step
188 cannot continue or unexpectibly fails, an exception is thrown.
189 in this case, the boot manager cannot continue running.
191 these step functions can also return a 0/1 depending on whether
192 or not it succeeded. In the case of steps like ConfirmInstallWithUser,
193 a 0 is returned and no exception is thrown if the user chose not
194 to confirm the install. The same goes with the CheckHardwareRequirements.
195 If requriements not met, but tests were succesfull, return 0.
197 for steps that run within the installer, they are expected to either
198 complete succesfully and return 1, or throw an execption.
200 For exact return values and expected operations, see the comments
201 at the top of each of the invididual step functions.
204 def _nodeNotInstalled(message='MSG_NODE_NOT_INSTALLED'):
205 # called by the _xxxState() functions below upon failure
206 self.VARS['RUN_LEVEL']= 'failboot'
207 notify = getattr(notify_messages, message)
208 self.VARS['STATE_CHANGE_NOTIFY']= 1
209 self.VARS['STATE_CHANGE_NOTIFY_MESSAGE']= notify
210 raise BootManagerException, notify
213 # implements the boot logic, which consists of first
214 # double checking that the node was properly installed,
215 # checking whether someone added or changed disks, and
216 # then finally chain boots.
218 # starting the fallback/debug ssh daemon for safety:
219 # if the node install somehow hangs, or if it simply takes ages,
220 # we can still enter and investigate
222 StartDebug.Run(self.VARS, self.LOG, last_resort = False)
226 InstallInit.Run( self.VARS, self.LOG )
227 ret = ValidateNodeInstall.Run( self.VARS, self.LOG )
229 WriteModprobeConfig.Run( self.VARS, self.LOG )
230 WriteNetworkConfig.Run( self.VARS, self.LOG )
231 CheckForNewDisks.Run( self.VARS, self.LOG )
232 SendHardwareConfigToPLC.Run( self.VARS, self.LOG )
233 ChainBootNode.Run( self.VARS, self.LOG )
235 _nodeNotInstalled('MSG_NODE_FILESYSTEM_CORRUPT')
237 _nodeNotInstalled('MSG_NODE_MOUNT_FAILED')
239 _nodeNotInstalled('MSG_NODE_MISSING_KERNEL')
245 # starting the fallback/debug ssh daemon for safety:
246 # if the node install somehow hangs, or if it simply takes ages,
247 # we can still enter and investigate
249 StartDebug.Run(self.VARS, self.LOG, last_resort = False)
253 # implements the reinstall logic, which will check whether
254 # the min. hardware requirements are met, install the
255 # software, and upon correct installation will switch too
256 # 'boot' state and chainboot into the production system
257 if not CheckHardwareRequirements.Run( self.VARS, self.LOG ):
258 self.VARS['RUN_LEVEL']= 'failboot'
259 raise BootManagerException, "Hardware requirements not met."
262 InstallInit.Run( self.VARS, self.LOG )
263 InstallPartitionDisks.Run( self.VARS, self.LOG )
264 InstallBootstrapFS.Run( self.VARS, self.LOG )
265 InstallWriteConfig.Run( self.VARS, self.LOG )
266 InstallUninitHardware.Run( self.VARS, self.LOG )
267 self.VARS['BOOT_STATE']= 'boot'
268 self.VARS['STATE_CHANGE_NOTIFY']= 1
269 self.VARS['STATE_CHANGE_NOTIFY_MESSAGE']= \
270 notify_messages.MSG_INSTALL_FINISHED
271 UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
275 # implements the new install logic, which will first check
276 # with the user whether it is ok to install on this
277 # machine, switch to 'reinstall' state and then invoke the reinstall
278 # logic. See reinstallState logic comments for further
280 if not ConfirmInstallWithUser.Run( self.VARS, self.LOG ):
282 self.VARS['BOOT_STATE']= 'reinstall'
283 UpdateRunLevelWithPLC.Run( self.VARS, self.LOG )
286 def _debugRun(state='failboot'):
287 # implements debug logic, which starts the sshd and just waits around
288 self.VARS['RUN_LEVEL']=state
289 UpdateRunLevelWithPLC.Run( self.VARS, self.LOG )
290 StartDebug.Run( self.VARS, self.LOG )
291 # fsck/mount fs if present, and ignore return value if it's not.
292 ValidateNodeInstall.Run( self.VARS, self.LOG )
295 # should never happen; log event
296 self.LOG.write( "\nInvalid BOOT_STATE = %s\n" % self.VARS['BOOT_STATE'])
299 # setup state -> function hash table
300 BootManager.NodeRunStates['reinstall'] = _reinstallRun
301 BootManager.NodeRunStates['boot'] = _bootRun
302 BootManager.NodeRunStates['safeboot'] = lambda : _debugRun('safeboot')
303 BootManager.NodeRunStates['disabled'] = lambda : _debugRun('disabled')
307 InitializeBootManager.Run( self.VARS, self.LOG )
308 ReadNodeConfiguration.Run( self.VARS, self.LOG )
309 AuthenticateWithPLC.Run( self.VARS, self.LOG )
310 StartRunlevelAgent.Run( self.VARS, self.LOG )
311 GetAndUpdateNodeDetails.Run( self.VARS, self.LOG )
313 # override machine's current state from the command line
314 if self.forceState is not None:
315 self.VARS['BOOT_STATE']= self.forceState
316 UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
317 UpdateRunLevelWithPLC.Run( self.VARS, self.LOG )
319 stateRun = BootManager.NodeRunStates.get(self.VARS['BOOT_STATE'],_badstateRun)
324 self.LOG.write( "\n\nKeyError while running: %s\n" % str(e) )
325 except BootManagerException, e:
326 self.LOG.write( "\n\nException while running: %s\n" % str(e) )
327 except BootManagerAuthenticationException, e:
328 self.LOG.write( "\n\nFailed to Authenticate Node: %s\n" % str(e) )
329 # sets /tmp/CANCEL_BOOT flag
330 StartDebug.Run(self.VARS, self.LOG )
331 # Return immediately b/c any other calls to API will fail
334 self.LOG.write( "\n\nImplementation Error\n")
335 traceback.print_exc(file=self.LOG.OutputFile)
336 traceback.print_exc()
341 except BootManagerException, e:
342 self.LOG.write( "\n\nException while running: %s\n" % str(e) )
344 self.LOG.write( "\n\nImplementation Error\n")
345 traceback.print_exc(file=self.LOG.OutputFile)
346 traceback.print_exc()
354 utils.prompt_for_breakpoint_mode()
356 utils.breakpoint ("Entering BootManager::main")
358 # set to 1 if error occurred
361 # all output goes through this class so we can save it and post
362 # the data back to PlanetLab central
363 LOG= log( BM_NODE_LOG )
365 LOG.LogEntry( "BootManager started at: %s" % \
366 time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) )
372 if BootManager.NodeRunStates.has_key(fState):
375 LOG.LogEntry("FATAL: cannot force node run state to=%s" % fState)
378 traceback.print_exc(file=LOG.OutputFile)
379 traceback.print_exc()
382 LOG.LogEntry( "BootManager finished at: %s" % \
383 time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) )
388 bm= BootManager(LOG,forceState)
390 LOG.LogEntry( "Unable to initialize BootManager." )
392 LOG.LogEntry( "Running version %s of BootManager." % bm.VARS['VERSION'] )
395 LOG.LogEntry( "\nDone!" );
397 LOG.LogEntry( "\nError occurred!" );
400 traceback.print_exc(file=LOG.OutputFile)
401 traceback.print_exc()
403 LOG.LogEntry( "BootManager finished at: %s" % \
404 time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) )
410 if __name__ == "__main__":
411 error = main(sys.argv)