better handle the kexec failure cases by notifying the user of the exact
[bootmanager.git] / source / BootManager.py
1 #!/usr/bin/python2 -u
2
3 # ------------------------------------------------------------------------
4 # THIS file used to be named alpina.py, from the node installer. Since then
5 # the installer has been expanded to include all the functions of the boot
6 # manager as well, hence the new name for this file.
7 # ------------------------------------------------------------------------
8
9 # Copyright (c) 2003 Intel Corporation
10 # All rights reserved.
11
12 # Redistribution and use in source and binary forms, with or without
13 # modification, are permitted provided that the following conditions are
14 # met:
15
16 #     * Redistributions of source code must retain the above copyright
17 #       notice, this list of conditions and the following disclaimer.
18
19 #     * Redistributions in binary form must reproduce the above
20 #       copyright notice, this list of conditions and the following
21 #       disclaimer in the documentation and/or other materials provided
22 #       with the distribution.
23
24 #     * Neither the name of the Intel Corporation nor the names of its
25 #       contributors may be used to endorse or promote products derived
26 #       from this software without specific prior written permission.
27
28 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
32 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
33 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
34 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
35 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
37 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
38 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39
40 # EXPORT LAWS: THIS LICENSE ADDS NO RESTRICTIONS TO THE EXPORT LAWS OF
41 # YOUR JURISDICTION. It is licensee's responsibility to comply with any
42 # export regulations applicable in licensee's jurisdiction. Under
43 # CURRENT (May 2000) U.S. export regulations this software is eligible
44 # for export from the U.S. and can be downloaded by or otherwise
45 # exported or reexported worldwide EXCEPT to U.S. embargoed destinations
46 # which include Cuba, Iraq, Libya, North Korea, Iran, Syria, Sudan,
47 # Afghanistan and any other country to which the U.S. has embargoed
48 # goods and services.
49
50
51 import string
52 import sys, os, traceback
53 from time import gmtime, strftime
54 from gzip import GzipFile
55
56 from steps import *
57 from Exceptions import *
58 import notify_messages
59
60
61
62 # all output is written to this file
63 LOG_FILE= "/tmp/bm.log"
64 CURL_PATH= "curl"
65 UPLOAD_LOG_URL = "http://boot.planet-lab.org/alpina-logs/upload.php"
66
67 # the new contents of PATH when the boot manager is running
68 BIN_PATH= ('/usr/local/bin',
69            '/usr/local/sbin',
70            '/bin',
71            '/sbin',
72            '/usr/bin',
73            '/usr/sbin',
74            '/usr/local/planetlab/bin')
75            
76
77
78 class log:
79
80     def __init__( self, OutputFilePath= None ):
81         if OutputFilePath:
82             try:
83                 self.OutputFilePath= OutputFilePath
84                 self.OutputFile= GzipFile( OutputFilePath, "w", 9 )
85             except:
86                 print( "Unable to open output file for log, continuing" )
87                 self.OutputFile= None
88
89         # for upload
90         os.system( "ifconfig eth0 > /tmp/ifconfig" )
91
92     
93     def LogEntry( self, str, inc_newline= 1, display_screen= 1 ):
94         if self.OutputFile:
95             self.OutputFile.write( str )
96         if display_screen:
97             sys.stdout.write( str )
98             
99         if inc_newline:
100             if display_screen:
101                 sys.stdout.write( "\n" )
102             if self.OutputFile:
103                 self.OutputFile.write( "\n" )
104
105         if self.OutputFile:
106             self.OutputFile.flush()
107
108             
109
110     def write( self, str ):
111         """
112         make log behave like a writable file object (for traceback
113         prints)
114         """
115         self.LogEntry( str, 0, 1 )
116
117
118     
119     def Upload( self ):
120         """
121         upload the contents of the log to the server
122         """
123
124         if self.OutputFile is not None:
125             self.LogEntry( "Uploading logs to %s" % UPLOAD_LOG_URL )
126             
127             self.OutputFile.close()
128             self.OutputFile= None
129             
130             curl_cmd= "%s -s --connect-timeout 60 --max-time 600 " \
131                       "--form log=@%s --form ifconfig=\</tmp/ifconfig %s" % \
132                       (CURL_PATH, self.OutputFilePath, UPLOAD_LOG_URL)
133             os.system( curl_cmd )
134         
135     
136
137         
138
139
140 class BootManager:
141
142     # file containing initial variables/constants
143     VARS_FILE = "configuration"
144
145     
146     def __init__(self, log):
147         # this contains a set of information used and updated
148         # by each step
149         self.VARS= {}
150
151         # the main logging point
152         self.LOG= log
153
154         # set to 1 if we can run after initialization
155         self.CAN_RUN = 0
156              
157         if not self.ReadBMConf():
158             self.LOG.LogEntry( "Unable to read configuration vars." )
159             return
160
161         # find out which directory we are running it, and set a variable
162         # for that. future steps may need to get files out of the bootmanager
163         # directory
164         current_dir= os.getcwd()
165         self.VARS['BM_SOURCE_DIR']= current_dir
166
167         # not sure what the current PATH is set to, replace it with what
168         # we know will work with all the boot cds
169         os.environ['PATH']= string.join(BIN_PATH,":")
170                    
171         self.CAN_RUN= 1
172         
173
174
175
176     def ReadBMConf(self):
177         """
178         read in and store all variables in VARS_FILE into
179         self.VARS
180         
181         each line is in the format name=val (any whitespace around
182         the = is removed. everything after the = to the end of
183         the line is the value
184         """
185         
186         vars_file= file(self.VARS_FILE,'r')
187         for line in vars_file:
188             # if its a comment or a whitespace line, ignore
189             if line[:1] == "#" or string.strip(line) == "":
190                 continue
191
192             parts= string.split(line,"=")
193             if len(parts) != 2:
194                 self.LOG.LogEntry( "Invalid line in vars file: %s" % line )
195                 return 0
196
197             name= string.strip(parts[0])
198             value= string.strip(parts[1])
199
200             self.VARS[name]= value
201
202         return 1
203     
204
205     def Run(self):
206         """
207         core boot manager logic.
208
209         the way errors are handled is as such: if any particular step
210         cannot continue or unexpectibly fails, an exception is thrown.
211         in this case, the boot manager cannot continue running.
212
213         these step functions can also return a 0/1 depending on whether
214         or not it succeeded. In the case of steps like ConfirmInstallWithUser,
215         a 0 is returned and no exception is thrown if the user chose not
216         to confirm the install. The same goes with the CheckHardwareRequirements.
217         If requriements not met, but tests were succesfull, return 0.
218
219         for steps that run within the installer, they are expected to either
220         complete succesfully and return 1, or throw an execption.
221
222         For exact return values and expected operations, see the comments
223         at the top of each of the invididual step functions.
224         """
225         
226         try:
227             InitializeBootManager.Run( self.VARS, self.LOG )
228             ReadNodeConfiguration.Run( self.VARS, self.LOG )
229             AuthenticateWithPLC.Run( self.VARS, self.LOG )
230             GetAndUpdateNodeDetails.Run( self.VARS, self.LOG )
231             
232             if self.VARS['BOOT_STATE'] == 'new' or \
233                    self.VARS['BOOT_STATE'] == 'inst':
234                 if not ConfirmInstallWithUser.Run( self.VARS, self.LOG ):
235                     return 0
236                 
237                 self.VARS['BOOT_STATE']= 'rins'
238                 UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
239             
240                 if not CheckHardwareRequirements.Run( self.VARS, self.LOG ):
241                     self.VARS['BOOT_STATE']= 'dbg'
242                     UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
243                     raise BootManagerException, "Hardware requirements not met."
244
245                 self.RunInstaller()
246
247                 if ValidateNodeInstall.Run( self.VARS, self.LOG ):
248                     SendHardwareConfigToPLC.Run( self.VARS, self.LOG )
249                     ChainBootNode.Run( self.VARS, self.LOG )
250                 else:
251                     self.VARS['BOOT_STATE']= 'dbg'
252                     self.VARS['STATE_CHANGE_NOTIFY']= 1
253                     self.VARS['STATE_CHANGE_NOTIFY_MESSAGE']= \
254                               notify_messages.MSG_NODE_NOT_INSTALLED
255                     UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
256                     
257
258             elif self.VARS['BOOT_STATE'] == 'rins':
259                 if not CheckHardwareRequirements.Run( self.VARS, self.LOG ):
260                     self.VARS['BOOT_STATE']= 'dbg'
261                     UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
262                     raise BootManagerException, "Hardware requirements not met."
263                 
264                 self.RunInstaller()
265
266                 if ValidateNodeInstall.Run( self.VARS, self.LOG ):
267                     SendHardwareConfigToPLC.Run( self.VARS, self.LOG )
268                     ChainBootNode.Run( self.VARS, self.LOG )
269                 else:
270                     self.VARS['BOOT_STATE']= 'dbg'
271                     self.VARS['STATE_CHANGE_NOTIFY']= 1
272                     self.VARS['STATE_CHANGE_NOTIFY_MESSAGE']= \
273                               notify_messages.MSG_NODE_NOT_INSTALLED
274                     UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
275
276             elif self.VARS['BOOT_STATE'] == 'boot':
277                 if ValidateNodeInstall.Run( self.VARS, self.LOG ):
278                     UpdateNodeConfiguration.Run( self.VARS, self.LOG )
279                     CheckForNewDisks.Run( self.VARS, self.LOG )
280                     SendHardwareConfigToPLC.Run( self.VARS, self.LOG )
281                     ChainBootNode.Run( self.VARS, self.LOG )
282                 else:
283                     self.VARS['BOOT_STATE']= 'dbg'
284                     self.VARS['STATE_CHANGE_NOTIFY']= 1
285                     self.VARS['STATE_CHANGE_NOTIFY_MESSAGE']= \
286                               notify_messages.MSG_NODE_NOT_INSTALLED
287                     UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
288                     
289             elif self.VARS['BOOT_STATE'] == 'dbg':
290                 StartDebug.Run( self.VARS, self.LOG )
291
292         except KeyError, e:
293             self.LOG.write( "\n\nKeyError while running: %s\n" % str(e) )
294         except BootManagerException, e:
295             self.LOG.write( "\n\nException while running: %s\n" % str(e) )
296         
297         return 1
298             
299
300             
301     def RunInstaller(self):
302         """
303         since the installer can be invoked at more than one place
304         in the boot manager logic, seperate the steps necessary
305         to do it here
306         """
307         
308         InstallInit.Run( self.VARS, self.LOG )                    
309         InstallPartitionDisks.Run( self.VARS, self.LOG )            
310         InstallBootstrapRPM.Run( self.VARS, self.LOG )            
311         InstallBase.Run( self.VARS, self.LOG )            
312         InstallWriteConfig.Run( self.VARS, self.LOG )
313         InstallBuildVServer.Run( self.VARS, self.LOG )
314         InstallNodeInit.Run( self.VARS, self.LOG )
315         InstallUninitHardware.Run( self.VARS, self.LOG )
316         
317         self.VARS['BOOT_STATE']= 'boot'
318         self.VARS['STATE_CHANGE_NOTIFY']= 1
319         self.VARS['STATE_CHANGE_NOTIFY_MESSAGE']= \
320                                        notify_messages.MSG_INSTALL_FINISHED
321         UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
322
323         SendHardwareConfigToPLC.Run( self.VARS, self.LOG )
324
325     
326     
327 if __name__ == "__main__":
328
329     # set to 0 if no error occurred
330     error= 1
331     
332     # all output goes through this class so we can save it and post
333     # the data back to PlanetLab central
334     LOG= log( LOG_FILE )
335
336     LOG.LogEntry( "BootManager started at: %s" % \
337                   strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) )
338
339     try:
340         bm= BootManager(LOG)
341         if bm.CAN_RUN == 0:
342             LOG.LogEntry( "Unable to initialize BootManager." )
343         else:
344             LOG.LogEntry( "Running version %s of BootManager." %
345                           bm.VARS['VERSION'] )
346             success= bm.Run()
347             if success:
348                 LOG.LogEntry( "\nDone!" );
349             else:
350                 LOG.LogEntry( "\nError occurred!" );
351
352     except:
353         traceback.print_exc(file=LOG.OutputFile)
354         traceback.print_exc()
355
356     LOG.LogEntry( "BootManager finished at: %s" % \
357                   strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) )
358
359     LOG.Upload()
360     
361     sys.exit(error)