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