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