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