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