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