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