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