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