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