Merge branch 'master' of ssh://git.onelab.eu/git/bootmanager
[bootmanager.git] / source / steps / ChainBootNode.py
1 #!/usr/bin/python
2 #
3 # $Id$
4 # $URL$
5 #
6 # Copyright (c) 2003 Intel Corporation
7 # All rights reserved.
8 #
9 # Copyright (c) 2004-2006 The Trustees of Princeton University
10 # All rights reserved.
11
12
13 import string
14 import re
15 import os
16
17 import UpdateNodeConfiguration
18 import MakeInitrd
19 from Exceptions import *
20 import utils
21 import systeminfo
22 import BootAPI
23 import notify_messages
24 import time
25
26 import ModelOptions
27
28 def Run( vars, log ):
29     """
30     Load the kernel off of a node and boot to it.
31     This step assumes the disks are mounted on SYSIMG_PATH.
32     If successful, this function will not return. If it returns, no chain
33     booting has occurred.
34     
35     Expect the following variables:
36     SYSIMG_PATH           the path where the system image will be mounted
37                           (always starts with TEMP_PATH)
38     ROOT_MOUNTED          the node root file system is mounted
39     NODE_SESSION             the unique session val set when we requested
40                              the current boot state
41     PLCONF_DIR               The directory to store PL configuration files in
42     
43     Sets the following variables:
44     ROOT_MOUNTED          the node root file system is mounted
45     """
46
47     log.write( "\n\nStep: Chain booting node.\n" )
48
49     # make sure we have the variables we need
50     try:
51         SYSIMG_PATH= vars["SYSIMG_PATH"]
52         if SYSIMG_PATH == "":
53             raise ValueError, "SYSIMG_PATH"
54
55         PLCONF_DIR= vars["PLCONF_DIR"]
56         if PLCONF_DIR == "":
57             raise ValueError, "PLCONF_DIR"
58
59         # its ok if this is blank
60         NODE_SESSION= vars["NODE_SESSION"]
61
62         NODE_MODEL_OPTIONS= vars["NODE_MODEL_OPTIONS"]
63
64         PARTITIONS= vars["PARTITIONS"]
65         if PARTITIONS == None:
66             raise ValueError, "PARTITIONS"
67
68     except KeyError, var:
69         raise BootManagerException, "Missing variable in vars: %s\n" % var
70     except ValueError, var:
71         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
72
73     ROOT_MOUNTED= 0
74     if vars.has_key('ROOT_MOUNTED'):
75         ROOT_MOUNTED= vars['ROOT_MOUNTED']
76     
77     if ROOT_MOUNTED == 0:
78         log.write( "Mounting node partitions\n" )
79
80         # simply creating an instance of this class and listing the system
81         # block devices will make them show up so vgscan can find the planetlab
82         # volume group
83         systeminfo.get_block_device_list(vars, log)
84         
85         utils.sysexec( "vgscan", log )
86         utils.sysexec( "vgchange -ay planetlab", log )
87
88         utils.makedirs( SYSIMG_PATH )
89
90         cmd = "mount %s %s" % (PARTITIONS["root"],SYSIMG_PATH)
91         utils.sysexec( cmd, log )
92         cmd = "mount -t proc none %s/proc" % SYSIMG_PATH
93         utils.sysexec( cmd, log )
94         cmd = "mount %s %s/vservers" % (PARTITIONS["vservers"],SYSIMG_PATH)
95         utils.sysexec( cmd, log )
96
97         ROOT_MOUNTED= 1
98         vars['ROOT_MOUNTED']= 1
99         
100
101     # write out the session value /etc/planetlab/session
102     try:
103         session_file_path= "%s/%s/session" % (SYSIMG_PATH,PLCONF_DIR)
104         session_file= file( session_file_path, "w" )
105         session_file.write( str(NODE_SESSION) )
106         session_file.close()
107         session_file= None
108         log.write( "Updated /etc/planetlab/session\n" )
109     except IOError, e:
110         log.write( "Unable to write out /etc/planetlab/session, continuing anyway\n" )
111
112     # update configuration files
113     log.write( "Updating configuration files.\n" )
114     try:
115         cmd = "/etc/init.d/conf_files start --noscripts"
116         utils.sysexec_chroot( SYSIMG_PATH, cmd, log )
117     except IOError, e:
118         log.write("conf_files failed with \n %s" % e)
119
120     # update node packages
121     log.write( "Running node update.\n" )
122     if os.path.exists( SYSIMG_PATH + "/usr/bin/NodeUpdate.py" ):
123         cmd = "/usr/bin/NodeUpdate.py start noreboot"
124     else:
125         # for backwards compatibility
126         cmd = "/usr/local/planetlab/bin/NodeUpdate.py start noreboot"
127     utils.sysexec_chroot( SYSIMG_PATH, cmd, log )
128
129     # Re-generate initrd right before kexec call
130     MakeInitrd.Run( vars, log )
131
132     # the following step should be done by NM
133     UpdateNodeConfiguration.Run( vars, log )
134
135     log.write( "Updating ssh public host key with PLC.\n" )
136     ssh_host_key= ""
137     try:
138         ssh_host_key_file= file("%s/etc/ssh/ssh_host_rsa_key.pub"%SYSIMG_PATH,"r")
139         ssh_host_key= ssh_host_key_file.read().strip()
140         ssh_host_key_file.close()
141         ssh_host_key_file= None
142     except IOError, e:
143         pass
144
145     update_vals= {}
146     update_vals['ssh_rsa_key']= ssh_host_key
147     BootAPI.call_api_function( vars, "BootUpdateNode", (update_vals,) )
148
149     # get the kernel version
150     option = ''
151     if NODE_MODEL_OPTIONS & ModelOptions.SMP:
152         option = 'smp'
153
154     log.write( "Copying kernel and initrd for booting.\n" )
155     utils.sysexec( "cp %s/boot/kernel-boot%s /tmp/kernel" % (SYSIMG_PATH,option), log )
156     utils.sysexec( "cp %s/boot/initrd-boot%s /tmp/initrd" % (SYSIMG_PATH,option), log )
157
158     BootAPI.save(vars)
159
160     log.write( "Unmounting disks.\n" )
161     utils.sysexec( "umount %s/vservers" % SYSIMG_PATH, log )
162     utils.sysexec( "umount %s/proc" % SYSIMG_PATH, log )
163     utils.sysexec( "umount %s" % SYSIMG_PATH, log )
164     utils.sysexec( "vgchange -an", log )
165
166     ROOT_MOUNTED= 0
167     vars['ROOT_MOUNTED']= 0
168
169     log.write( "Unloading modules and chain booting to new kernel.\n" )
170
171     # further use of log after Upload will only output to screen
172     log.Upload("/root/.bash_eternal_history")
173
174     # regardless of whether kexec works or not, we need to stop trying to
175     # run anything
176     cancel_boot_flag= "/tmp/CANCEL_BOOT"
177     utils.sysexec( "touch %s" % cancel_boot_flag, log )
178
179     # on 2.x cds (2.4 kernel) for sure, we need to shutdown everything
180     # to get kexec to work correctly. Even on 3.x cds (2.6 kernel),
181     # there are a few buggy drivers that don't disable their hardware
182     # correctly unless they are first unloaded.
183     
184     utils.sysexec_noerr( "ifconfig eth0 down", log )
185
186     utils.sysexec_noerr( "killall dhclient", log )
187         
188     utils.sysexec_noerr( "umount -a -r -t ext2,ext3", log )
189     utils.sysexec_noerr( "modprobe -r lvm-mod", log )
190     
191     # modules that should not get unloaded
192     # unloading cpqphp causes a kernel panic
193     blacklist = [ "floppy", "cpqphp", "i82875p_edac", "mptspi"]
194     try:
195         modules= file("/tmp/loadedmodules","r")
196         
197         for line in modules:
198             module= string.strip(line)
199             if module in blacklist :
200                 log.write("Skipping unload of kernel module '%s'.\n"%module)
201             elif module != "":
202                 log.write( "Unloading %s\n" % module )
203                 utils.sysexec_noerr( "modprobe -r %s" % module, log )
204                 if "e1000" in module:
205                     log.write("Unloading e1000 driver; sleeping 4 seconds...\n")
206                     time.sleep(4)
207
208         modules.close()
209     except IOError:
210         log.write( "Couldn't read /tmp/loadedmodules, continuing.\n" )
211
212     try:
213         modules= file("/proc/modules", "r")
214
215         # Get usage count for USB
216         usb_usage = 0
217         for line in modules:
218             try:
219                 # Module Size UsageCount UsedBy State LoadAddress
220                 parts= string.split(line)
221
222                 if parts[0] == "usb_storage":
223                     usb_usage += int(parts[2])
224             except IndexError, e:
225                 log.write( "Couldn't parse /proc/modules, continuing.\n" )
226
227         modules.seek(0)
228
229         for line in modules:
230             try:
231                 # Module Size UsageCount UsedBy State LoadAddress
232                 parts= string.split(line)
233
234                 # While we would like to remove all "unused" modules,
235                 # you can't trust usage count, especially for things
236                 # like network drivers or RAID array drivers. Just try
237                 # and unload a few specific modules that we know cause
238                 # problems during chain boot, such as USB host
239                 # controller drivers (HCDs) (PL6577).
240                 # if int(parts[2]) == 0:
241                 if False and re.search('_hcd$', parts[0]):
242                     if usb_usage > 0:
243                         log.write( "NOT unloading %s since USB may be in use\n" % parts[0] )
244                     else:
245                         log.write( "Unloading %s\n" % parts[0] )
246                         utils.sysexec_noerr( "modprobe -r %s" % parts[0], log )
247             except IndexError, e:
248                 log.write( "Couldn't parse /proc/modules, continuing.\n" )
249     except IOError:
250         log.write( "Couldn't read /proc/modules, continuing.\n" )
251
252
253     kargs = "root=%s ramdisk_size=8192" % PARTITIONS["mapper-root"]
254     if NODE_MODEL_OPTIONS & ModelOptions.SMP:
255         kargs = kargs + " " + "acpi=off"
256     try:
257         kargsfb = open("/kargs.txt","r")
258         moreargs = kargsfb.readline()
259         kargsfb.close()
260         moreargs = moreargs.strip()
261         log.write( 'Parsed in "%s" kexec args from /kargs.txt\n' % moreargs )
262         kargs = kargs + " " + moreargs
263     except IOError:
264         # /kargs.txt does not exist, which is fine. Just kexec with default
265         # kargs, which is ramdisk_size=8192
266         pass 
267
268     utils.sysexec_noerr( 'hwclock --systohc --utc ' )
269     utils.breakpoint ("Before kexec");
270     try:
271         utils.sysexec( 'kexec --force --initrd=/tmp/initrd ' \
272                        '--append="%s" /tmp/kernel' % kargs)
273     except BootManagerException, e:
274         # if kexec fails, we've shut the machine down to a point where nothing
275         # can run usefully anymore (network down, all modules unloaded, file
276         # systems unmounted. write out the error, and cancel the boot process
277
278         log.write( "\n\n" )
279         log.write( "-------------------------------------------------------\n" )
280         log.write( "kexec failed with the following error. Please report\n" )
281         log.write( "this problem to support@planet-lab.org.\n\n" )
282         log.write( str(e) + "\n\n" )
283         log.write( "The boot process has been canceled.\n" )
284         log.write( "-------------------------------------------------------\n\n" )
285
286     return