deprecate alpina-BootstrapRPM and the InstallBase step; instead just unpack PlanetLab...
[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     
90     def LogEntry( self, str, inc_newline= 1, display_screen= 1 ):
91         if self.OutputFile:
92             self.OutputFile.write( str )
93         if display_screen:
94             sys.stdout.write( str )
95             
96         if inc_newline:
97             if display_screen:
98                 sys.stdout.write( "\n" )
99             if self.OutputFile:
100                 self.OutputFile.write( "\n" )
101
102         if self.OutputFile:
103             self.OutputFile.flush()
104
105             
106
107     def write( self, str ):
108         """
109         make log behave like a writable file object (for traceback
110         prints)
111         """
112         self.LogEntry( str, 0, 1 )
113
114
115     
116     def Upload( self ):
117         """
118         upload the contents of the log to the server
119         """
120
121         if self.OutputFile is not None:
122             self.LogEntry( "Uploading logs to %s" % UPLOAD_LOG_URL )
123             
124             self.OutputFile.close()
125             self.OutputFile= None
126             
127             curl_cmd= "%s -s --connect-timeout 60 --max-time 600 " \
128                       "--form log=@%s %s" % \
129                       (CURL_PATH, self.OutputFilePath, UPLOAD_LOG_URL)
130             os.system( curl_cmd )
131         
132     
133
134         
135
136
137 class BootManager:
138
139     # file containing initial variables/constants
140     VARS_FILE = "configuration"
141
142     
143     def __init__(self, log):
144         # this contains a set of information used and updated
145         # by each step
146         self.VARS= {}
147
148         # the main logging point
149         self.LOG= log
150
151         # set to 1 if we can run after initialization
152         self.CAN_RUN = 0
153              
154         if not self.ReadBMConf():
155             self.LOG.LogEntry( "Unable to read configuration vars." )
156             return
157
158         # find out which directory we are running it, and set a variable
159         # for that. future steps may need to get files out of the bootmanager
160         # directory
161         current_dir= os.getcwd()
162         self.VARS['BM_SOURCE_DIR']= current_dir
163
164         # not sure what the current PATH is set to, replace it with what
165         # we know will work with all the boot cds
166         os.environ['PATH']= string.join(BIN_PATH,":")
167                    
168         self.CAN_RUN= 1
169         
170
171
172
173     def ReadBMConf(self):
174         """
175         read in and store all variables in VARS_FILE into
176         self.VARS
177         
178         each line is in the format name=val (any whitespace around
179         the = is removed. everything after the = to the end of
180         the line is the value
181         """
182         
183         vars_file= file(self.VARS_FILE,'r')
184         for line in vars_file:
185             # if its a comment or a whitespace line, ignore
186             if line[:1] == "#" or string.strip(line) == "":
187                 continue
188
189             parts= string.split(line,"=")
190             if len(parts) != 2:
191                 self.LOG.LogEntry( "Invalid line in vars file: %s" % line )
192                 return 0
193
194             name= string.strip(parts[0])
195             value= string.strip(parts[1])
196
197             self.VARS[name]= value
198
199         return 1
200     
201
202     def Run(self):
203         """
204         core boot manager logic.
205
206         the way errors are handled is as such: if any particular step
207         cannot continue or unexpectibly fails, an exception is thrown.
208         in this case, the boot manager cannot continue running.
209
210         these step functions can also return a 0/1 depending on whether
211         or not it succeeded. In the case of steps like ConfirmInstallWithUser,
212         a 0 is returned and no exception is thrown if the user chose not
213         to confirm the install. The same goes with the CheckHardwareRequirements.
214         If requriements not met, but tests were succesfull, return 0.
215
216         for steps that run within the installer, they are expected to either
217         complete succesfully and return 1, or throw an execption.
218
219         For exact return values and expected operations, see the comments
220         at the top of each of the invididual step functions.
221         """
222         
223         try:
224             InitializeBootManager.Run( self.VARS, self.LOG )
225             ReadNodeConfiguration.Run( self.VARS, self.LOG )
226             AuthenticateWithPLC.Run( self.VARS, self.LOG )
227             GetAndUpdateNodeDetails.Run( self.VARS, self.LOG )
228             
229             if self.VARS['BOOT_STATE'] == 'new' or \
230                    self.VARS['BOOT_STATE'] == 'inst':
231                 if not ConfirmInstallWithUser.Run( self.VARS, self.LOG ):
232                     return 0
233                 
234                 self.VARS['BOOT_STATE']= 'rins'
235                 UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
236             
237                 if not CheckHardwareRequirements.Run( self.VARS, self.LOG ):
238                     self.VARS['BOOT_STATE']= 'dbg'
239                     UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
240                     raise BootManagerException, "Hardware requirements not met."
241
242                 self.RunInstaller()
243
244                 if ValidateNodeInstall.Run( self.VARS, self.LOG ):
245                     SendHardwareConfigToPLC.Run( self.VARS, self.LOG )
246                     ChainBootNode.Run( self.VARS, self.LOG )
247                 else:
248                     self.VARS['BOOT_STATE']= 'dbg'
249                     self.VARS['STATE_CHANGE_NOTIFY']= 1
250                     self.VARS['STATE_CHANGE_NOTIFY_MESSAGE']= \
251                               notify_messages.MSG_NODE_NOT_INSTALLED
252                     UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
253                     
254
255             elif self.VARS['BOOT_STATE'] == 'rins':
256                 if not CheckHardwareRequirements.Run( self.VARS, self.LOG ):
257                     self.VARS['BOOT_STATE']= 'dbg'
258                     UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
259                     raise BootManagerException, "Hardware requirements not met."
260                 
261                 self.RunInstaller()
262
263                 if ValidateNodeInstall.Run( self.VARS, self.LOG ):
264                     SendHardwareConfigToPLC.Run( self.VARS, self.LOG )
265                     ChainBootNode.Run( self.VARS, self.LOG )
266                 else:
267                     self.VARS['BOOT_STATE']= 'dbg'
268                     self.VARS['STATE_CHANGE_NOTIFY']= 1
269                     self.VARS['STATE_CHANGE_NOTIFY_MESSAGE']= \
270                               notify_messages.MSG_NODE_NOT_INSTALLED
271                     UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
272
273             elif self.VARS['BOOT_STATE'] == 'boot':
274                 if ValidateNodeInstall.Run( self.VARS, self.LOG ):
275                     UpdateNodeConfiguration.Run( self.VARS, self.LOG )
276                     CheckForNewDisks.Run( self.VARS, self.LOG )
277                     SendHardwareConfigToPLC.Run( self.VARS, self.LOG )
278                     ChainBootNode.Run( self.VARS, self.LOG )
279                 else:
280                     self.VARS['BOOT_STATE']= 'dbg'
281                     self.VARS['STATE_CHANGE_NOTIFY']= 1
282                     self.VARS['STATE_CHANGE_NOTIFY_MESSAGE']= \
283                               notify_messages.MSG_NODE_NOT_INSTALLED
284                     UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
285                     
286             elif self.VARS['BOOT_STATE'] == 'dbg':
287                 StartDebug.Run( self.VARS, self.LOG )
288
289         except KeyError, e:
290             self.LOG.write( "\n\nKeyError while running: %s\n" % str(e) )
291         except BootManagerException, e:
292             self.LOG.write( "\n\nException while running: %s\n" % str(e) )
293         
294         return 1
295             
296
297             
298     def RunInstaller(self):
299         """
300         since the installer can be invoked at more than one place
301         in the boot manager logic, seperate the steps necessary
302         to do it here
303         """
304         
305         InstallInit.Run( self.VARS, self.LOG )                    
306         InstallPartitionDisks.Run( self.VARS, self.LOG )            
307         InstallBootstrapRPM.Run( self.VARS, self.LOG )            
308         InstallWriteConfig.Run( self.VARS, self.LOG )
309         InstallBuildVServer.Run( self.VARS, self.LOG )
310         InstallNodeInit.Run( self.VARS, self.LOG )
311         InstallUninitHardware.Run( self.VARS, self.LOG )
312         
313         self.VARS['BOOT_STATE']= 'boot'
314         self.VARS['STATE_CHANGE_NOTIFY']= 1
315         self.VARS['STATE_CHANGE_NOTIFY_MESSAGE']= \
316                                        notify_messages.MSG_INSTALL_FINISHED
317         UpdateBootStateWithPLC.Run( self.VARS, self.LOG )
318
319         SendHardwareConfigToPLC.Run( self.VARS, self.LOG )
320
321     
322     
323 if __name__ == "__main__":
324
325     # set to 0 if no error occurred
326     error= 1
327     
328     # all output goes through this class so we can save it and post
329     # the data back to PlanetLab central
330     LOG= log( LOG_FILE )
331
332     LOG.LogEntry( "BootManager started at: %s" % \
333                   strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) )
334
335     try:
336         bm= BootManager(LOG)
337         if bm.CAN_RUN == 0:
338             LOG.LogEntry( "Unable to initialize BootManager." )
339         else:
340             LOG.LogEntry( "Running version %s of BootManager." %
341                           bm.VARS['VERSION'] )
342             success= bm.Run()
343             if success:
344                 LOG.LogEntry( "\nDone!" );
345             else:
346                 LOG.LogEntry( "\nError occurred!" );
347
348     except:
349         traceback.print_exc(file=LOG.OutputFile)
350         traceback.print_exc()
351
352     LOG.LogEntry( "BootManager finished at: %s" % \
353                   strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) )
354
355     LOG.Upload()
356     
357     sys.exit(error)