update to modules. catches other e1000-like modules in newer hpdc7800
[bootmanager.git] / source / steps / ChainBootNode.py
1 #!/usr/bin/python2
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
14 import UpdateBootStateWithPLC
15 import UpdateNodeConfiguration
16 from Exceptions import *
17 import utils
18 import compatibility
19 import systeminfo
20 import BootAPI
21 import notify_messages
22 import time
23
24 import ModelOptions
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     BOOT_CD_VERSION       A tuple of the current bootcd version
35     SYSIMG_PATH           the path where the system image will be mounted
36                           (always starts with TEMP_PATH)
37     ROOT_MOUNTED          the node root file system is mounted
38     NODE_SESSION             the unique session val set when we requested
39                              the current boot state
40     PLCONF_DIR               The directory to store PL configuration files in
41     
42     Sets the following variables:
43     ROOT_MOUNTED          the node root file system is mounted
44     """
45
46     log.write( "\n\nStep: Chain booting node.\n" )
47
48     # make sure we have the variables we need
49     try:
50         BOOT_CD_VERSION= vars["BOOT_CD_VERSION"]
51         if BOOT_CD_VERSION == "":
52             raise ValueError, "BOOT_CD_VERSION"
53
54         SYSIMG_PATH= vars["SYSIMG_PATH"]
55         if SYSIMG_PATH == "":
56             raise ValueError, "SYSIMG_PATH"
57
58         PLCONF_DIR= vars["PLCONF_DIR"]
59         if PLCONF_DIR == "":
60             raise ValueError, "PLCONF_DIR"
61
62         # its ok if this is blank
63         NODE_SESSION= vars["NODE_SESSION"]
64
65         NODE_MODEL_OPTIONS= vars["NODE_MODEL_OPTIONS"]
66
67         PARTITIONS= vars["PARTITIONS"]
68         if PARTITIONS == None:
69             raise ValueError, "PARTITIONS"
70
71     except KeyError, var:
72         raise BootManagerException, "Missing variable in vars: %s\n" % var
73     except ValueError, var:
74         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
75
76     ROOT_MOUNTED= 0
77     if 'ROOT_MOUNTED' in vars.keys():
78         ROOT_MOUNTED= vars['ROOT_MOUNTED']
79     
80     if ROOT_MOUNTED == 0:
81         log.write( "Mounting node partitions\n" )
82
83         # old cds need extra utilities to run lvm
84         if BOOT_CD_VERSION[0] == 2:
85             compatibility.setup_lvm_2x_cd( vars, log )
86             
87         # simply creating an instance of this class and listing the system
88         # block devices will make them show up so vgscan can find the planetlab
89         # volume group
90         systeminfo.get_block_device_list(vars, log)
91         
92         utils.sysexec( "vgscan", log )
93         utils.sysexec( "vgchange -ay planetlab", log )
94
95         utils.makedirs( SYSIMG_PATH )
96
97         cmd = "mount %s %s" % (PARTITIONS["root"],SYSIMG_PATH)
98         utils.sysexec( cmd, log )
99         cmd = "mount %s %s/vservers" % (PARTITIONS["vservers"],SYSIMG_PATH)
100         utils.sysexec( cmd, log )
101         cmd = "mount -t proc none %s/proc" % SYSIMG_PATH
102         utils.sysexec( cmd, log )
103
104         ROOT_MOUNTED= 1
105         vars['ROOT_MOUNTED']= 1
106         
107
108     # write out the session value /etc/planetlab/session
109     try:
110         session_file_path= "%s/%s/session" % (SYSIMG_PATH,PLCONF_DIR)
111         session_file= file( session_file_path, "w" )
112         session_file.write( str(NODE_SESSION) )
113         session_file.close()
114         session_file= None
115         log.write( "Updated /etc/planetlab/session\n" )
116     except IOError, e:
117         log.write( "Unable to write out /etc/planetlab/session, continuing anyway\n" )
118
119     # update configuration files
120     log.write( "Updating configuration files.\n" )
121     try:
122         cmd = "/etc/init.d/conf_files start --noscripts"
123         utils.sysexec( "chroot %s %s" % (SYSIMG_PATH, cmd), log )
124     except IOError, e:
125         log.write("conf_files failed with \n %s" % e)
126
127     # update node packages
128     log.write( "Running node update.\n" )
129     if os.path.exists( SYSIMG_PATH + "/usr/bin/NodeUpdate.py" ):
130         cmd = "chroot %s /usr/bin/NodeUpdate.py start noreboot" % SYSIMG_PATH
131     else:
132         # for backwards compatibility
133         cmd = "chroot %s /usr/local/planetlab/bin/NodeUpdate.py start noreboot" % SYSIMG_PATH
134     utils.sysexec( cmd, 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("%s/etc/ssh/ssh_host_rsa_key.pub"%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, e:
147         pass
148
149     update_vals= {}
150     update_vals['ssh_host_key']= ssh_host_key
151     BootAPI.call_api_function( vars, "BootUpdateNode", (update_vals,) )
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     utils.sysexec( "cp %s/boot/kernel-boot%s /tmp/kernel" % (SYSIMG_PATH,option), log )
160     utils.sysexec( "cp %s/boot/initrd-boot%s /tmp/initrd" % (SYSIMG_PATH,option), log )
161
162     BootAPI.save(vars)
163
164     log.write( "Unmounting disks.\n" )
165     try:
166         # backwards compat, though, we should never hit this case post PL 3.2
167         os.stat("%s/rcfs/taskclass"%SYSIMG_PATH)
168         utils.sysexec_noerr( "chroot %s umount /rcfs" % SYSIMG_PATH, log )
169     except OSError, e:
170         pass
171
172     utils.sysexec_noerr( "umount %s/proc" % SYSIMG_PATH, log )
173     utils.sysexec_noerr( "umount -r %s/vservers" % SYSIMG_PATH, log )
174     utils.sysexec_noerr( "umount -r %s" % SYSIMG_PATH, log )
175     utils.sysexec_noerr( "vgchange -an", log )
176
177     ROOT_MOUNTED= 0
178     vars['ROOT_MOUNTED']= 0
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()
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     if BOOT_CD_VERSION[0] == 2:
198         utils.sysexec_noerr( "killall dhcpcd", log )
199     elif BOOT_CD_VERSION[0] >= 3:
200         utils.sysexec_noerr( "killall dhclient", log )
201         
202     utils.sysexec_noerr( "umount -a -r -t ext2,ext3", 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" ]
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.breakpoint ("Before kexec");
283     try:
284         utils.sysexec( 'kexec --force --initrd=/tmp/initrd ' \
285                        '--append="%s" /tmp/kernel' % kargs)
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