6ea62139321a5d18348f006118769660aaa75ee5
[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     # avoid using conf_files initscript as we're moving to systemd on some platforms
113
114     if (vars['ONE_PARTITION']!='1'):
115         try:
116             cmd = "/usr/bin/env python /usr/share/NodeManager/conf_files.py --noscripts"
117             utils.sysexec_chroot( SYSIMG_PATH, cmd, log )
118         except IOError, e:
119             log.write("conf_files failed with \n %s" % e)
120
121         # update node packages
122         log.write( "Running node update.\n" )
123         if os.path.exists( SYSIMG_PATH + "/usr/bin/NodeUpdate.py" ):
124             cmd = "/usr/bin/NodeUpdate.py start noreboot"
125         else:
126             # for backwards compatibility
127             cmd = "/usr/local/planetlab/bin/NodeUpdate.py start noreboot"
128         utils.sysexec_chroot( SYSIMG_PATH, cmd, log )
129
130     # Re-generate initrd right before kexec call
131     # this is not required anymore on recent depls.
132     if vars['virt'] == 'vs':
133         MakeInitrd.Run( vars, log )
134
135     # the following step should be done by NM
136     UpdateNodeConfiguration.Run( vars, log )
137
138     log.write( "Updating ssh public host key with PLC.\n" )
139     ssh_host_key= ""
140     try:
141         ssh_host_key_file= file("%s/etc/ssh/ssh_host_rsa_key.pub"%SYSIMG_PATH,"r")
142         ssh_host_key= ssh_host_key_file.read().strip()
143         ssh_host_key_file.close()
144         ssh_host_key_file= None
145     except IOError, e:
146         pass
147
148     update_vals= {}
149     update_vals['ssh_rsa_key']= ssh_host_key
150     BootAPI.call_api_function( vars, "BootUpdateNode", (update_vals,) )
151
152
153     # get the kernel version
154     option = ''
155     if NODE_MODEL_OPTIONS & ModelOptions.SMP:
156         option = 'smp'
157
158     log.write( "Copying kernel and initrd for booting.\n" )
159     if vars['virt'] == 'vs':
160         utils.sysexec( "cp %s/boot/kernel-boot%s /tmp/kernel" % (SYSIMG_PATH,option), log )
161         utils.sysexec( "cp %s/boot/initrd-boot%s /tmp/initrd" % (SYSIMG_PATH,option), log )
162     else:
163         # Use chroot to call rpm, b/c the bootimage&nodeimage rpm-versions may not work together
164         try:
165             kversion = os.popen("chroot %s rpm -qa kernel | tail -1 | cut -c 8-" % SYSIMG_PATH).read().rstrip()
166             major_version = int(kversion[0]) # Check if the string looks like a kernel version
167         except:
168             # Try a different method for non-rpm-based distributions
169             kversion = os.popen("ls -lrt %s/lib/modules | tail -1 | awk '{print $9;}'"%SYSIMG_PATH).read().rstrip()
170
171         utils.sysexec( "cp %s/boot/vmlinuz-%s /tmp/kernel" % (SYSIMG_PATH,kversion), log )
172         candidates=[]
173         # f16/18: expect initramfs image here
174         candidates.append ("/boot/initramfs-%s.img"%(kversion))
175         # f20: uses a uid of some kind, e.g. /boot/543f88c129de443baaa65800cf3927ce/<kversion>/initrd
176         candidates.append ("/boot/*/%s/initrd"%(kversion))
177         # Ubuntu:
178         candidates.append ("/boot/initrd.img-%s"%(kversion))
179         def find_file_in_sysimg (candidates):
180             import glob
181             for pattern in candidates:
182                 matches=glob.glob(SYSIMG_PATH+pattern)
183                 log.write("locating initrd: found %d matches in %s\n"%(len(matches),pattern))
184                 if matches: return matches[0]
185         initrd=find_file_in_sysimg(candidates)
186         if initrd:
187             utils.sysexec( "cp %s /tmp/initrd" % initrd, log )
188         else:
189             raise Exception,"Unable to locate initrd - bailing out"
190
191     BootAPI.save(vars)
192
193     log.write( "Unmounting disks.\n" )
194     
195     if (vars['ONE_PARTITION']!='1'):
196         utils.sysexec( "umount %s/vservers" % SYSIMG_PATH, log )
197     utils.sysexec( "umount %s/proc" % SYSIMG_PATH, log )
198     utils.sysexec_noerr( "umount %s/dev" % SYSIMG_PATH, log )
199     utils.sysexec_noerr( "umount %s/sys" % SYSIMG_PATH, log )
200     utils.sysexec( "umount %s" % SYSIMG_PATH, log )
201     utils.sysexec( "vgchange -an", log )
202
203     ROOT_MOUNTED= 0
204     vars['ROOT_MOUNTED']= 0
205
206     # Change runlevel to 'boot' prior to kexec.
207     StopRunlevelAgent.Run( vars, log )
208
209     log.write( "Unloading modules and chain booting to new kernel.\n" )
210
211     # further use of log after Upload will only output to screen
212     log.Upload("/root/.bash_eternal_history")
213
214     # regardless of whether kexec works or not, we need to stop trying to
215     # run anything
216     cancel_boot_flag= "/tmp/CANCEL_BOOT"
217     utils.sysexec( "touch %s" % cancel_boot_flag, log )
218
219     # on 2.x cds (2.4 kernel) for sure, we need to shutdown everything
220     # to get kexec to work correctly. Even on 3.x cds (2.6 kernel),
221     # there are a few buggy drivers that don't disable their hardware
222     # correctly unless they are first unloaded.
223     
224     utils.sysexec_noerr( "ifconfig eth0 down", log )
225
226     utils.sysexec_noerr( "killall dhclient", log )
227         
228     if vars['virt'] == 'vs':
229         utils.sysexec_noerr( "umount -a -r -t ext2,ext3", log )
230     else:
231         utils.sysexec_noerr( "umount -a -r -t ext2,ext3,btrfs", log )
232     utils.sysexec_noerr( "modprobe -r lvm-mod", log )
233     
234     # modules that should not get unloaded
235     # unloading cpqphp causes a kernel panic
236     blacklist = [ "floppy", "cpqphp", "i82875p_edac", "mptspi"]
237     try:
238         modules= file("/tmp/loadedmodules","r")
239         
240         for line in modules:
241             module= string.strip(line)
242             if module in blacklist :
243                 log.write("Skipping unload of kernel module '%s'.\n"%module)
244             elif module != "":
245                 log.write( "Unloading %s\n" % module )
246                 utils.sysexec_noerr( "modprobe -r %s" % module, log )
247                 if "e1000" in module:
248                     log.write("Unloading e1000 driver; sleeping 4 seconds...\n")
249                     time.sleep(4)
250
251         modules.close()
252     except IOError:
253         log.write( "Couldn't read /tmp/loadedmodules, continuing.\n" )
254
255     try:
256         modules= file("/proc/modules", "r")
257
258         # Get usage count for USB
259         usb_usage = 0
260         for line in modules:
261             try:
262                 # Module Size UsageCount UsedBy State LoadAddress
263                 parts= string.split(line)
264
265                 if parts[0] == "usb_storage":
266                     usb_usage += int(parts[2])
267             except IndexError, e:
268                 log.write( "Couldn't parse /proc/modules, continuing.\n" )
269
270         modules.seek(0)
271
272         for line in modules:
273             try:
274                 # Module Size UsageCount UsedBy State LoadAddress
275                 parts= string.split(line)
276
277                 # While we would like to remove all "unused" modules,
278                 # you can't trust usage count, especially for things
279                 # like network drivers or RAID array drivers. Just try
280                 # and unload a few specific modules that we know cause
281                 # problems during chain boot, such as USB host
282                 # controller drivers (HCDs) (PL6577).
283                 # if int(parts[2]) == 0:
284                 if False and re.search('_hcd$', parts[0]):
285                     if usb_usage > 0:
286                         log.write( "NOT unloading %s since USB may be in use\n" % parts[0] )
287                     else:
288                         log.write( "Unloading %s\n" % parts[0] )
289                         utils.sysexec_noerr( "modprobe -r %s" % parts[0], log )
290             except IndexError, e:
291                 log.write( "Couldn't parse /proc/modules, continuing.\n" )
292     except IOError:
293         log.write( "Couldn't read /proc/modules, continuing.\n" )
294
295
296     kargs = "root=%s ramdisk_size=8192" % PARTITIONS["mapper-root"]
297     if NODE_MODEL_OPTIONS & ModelOptions.SMP:
298         kargs = kargs + " " + "acpi=off"
299     try:
300         kargsfb = open("/kargs.txt","r")
301         moreargs = kargsfb.readline()
302         kargsfb.close()
303         moreargs = moreargs.strip()
304         log.write( 'Parsed in "%s" kexec args from /kargs.txt\n' % moreargs )
305         kargs = kargs + " " + moreargs
306     except IOError:
307         # /kargs.txt does not exist, which is fine. Just kexec with default
308         # kargs, which is ramdisk_size=8192
309         pass 
310
311     utils.sysexec_noerr( 'hwclock --systohc --utc ', log )
312     utils.breakpoint ("Before kexec");
313     try:
314         utils.sysexec( 'kexec --force --initrd=/tmp/initrd --append="%s" /tmp/kernel' % kargs, log)
315     except BootManagerException, e:
316         # if kexec fails, we've shut the machine down to a point where nothing
317         # can run usefully anymore (network down, all modules unloaded, file
318         # systems unmounted. write out the error, and cancel the boot process
319
320         log.write( "\n\n" )
321         log.write( "-------------------------------------------------------\n" )
322         log.write( "kexec failed with the following error. Please report\n" )
323         log.write( "this problem to support@planet-lab.org.\n\n" )
324         log.write( str(e) + "\n\n" )
325         log.write( "The boot process has been canceled.\n" )
326         log.write( "-------------------------------------------------------\n\n" )
327
328     return