review how to figure nodefamily:
[bootmanager.git] / source / steps / InstallBootstrapFS.py
1 #!/usr/bin/python2
2
3 # Copyright (c) 2003 Intel Corporation
4 # All rights reserved.
5 #
6 # Copyright (c) 2004-2007 The Trustees of Princeton University
7 # All rights reserved.
8 # expected /proc/partitions format
9
10 import os, sys, string
11 import popen2
12 import shutil
13
14 from Exceptions import *
15 import utils
16 import BootServerRequest
17 import BootAPI
18
19
20 def Run( vars, log ):
21     """
22     Download enough files to run rpm and yum from a chroot in
23     the system image directory
24     
25     Expect the following variables from the store:
26     SYSIMG_PATH          the path where the system image will be mounted
27     PARTITIONS           dictionary of generic part. types (root/swap)
28                          and their associated devices.
29     SUPPORT_FILE_DIR     directory on the boot servers containing
30                          scripts and support files
31     NODE_ID              the id of this machine
32     
33     Sets the following variables:
34     TEMP_BOOTCD_PATH     where the boot cd is remounted in the temp
35                          path
36     ROOT_MOUNTED         set to 1 when the the base logical volumes
37                          are mounted.
38     """
39
40     log.write( "\n\nStep: Install: bootstrapfs tarball.\n" )
41
42     # make sure we have the variables we need
43     try:
44         SYSIMG_PATH= vars["SYSIMG_PATH"]
45         if SYSIMG_PATH == "":
46             raise ValueError, "SYSIMG_PATH"
47
48         PARTITIONS= vars["PARTITIONS"]
49         if PARTITIONS == None:
50             raise ValueError, "PARTITIONS"
51
52         SUPPORT_FILE_DIR= vars["SUPPORT_FILE_DIR"]
53         if SUPPORT_FILE_DIR == None:
54             raise ValueError, "SUPPORT_FILE_DIR"
55
56         NODE_ID= vars["NODE_ID"]
57         if NODE_ID == "":
58             raise ValueError, "NODE_ID"
59
60     except KeyError, var:
61         raise BootManagerException, "Missing variable in vars: %s\n" % var
62     except ValueError, var:
63         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
64
65
66     try:
67         # make sure the required partitions exist
68         val= PARTITIONS["root"]
69         val= PARTITIONS["swap"]
70         val= PARTITIONS["vservers"]
71     except KeyError, part:
72         log.write( "Missing partition in PARTITIONS: %s\n" % part )
73         return 0   
74
75     bs_request= BootServerRequest.BootServerRequest()
76     
77     log.write( "turning on swap space\n" )
78     utils.sysexec( "swapon %s" % PARTITIONS["swap"], log )
79
80     # make sure the sysimg dir is present
81     utils.makedirs( SYSIMG_PATH )
82
83     log.write( "mounting root file system\n" )
84     utils.sysexec( "mount -t ext3 %s %s" % (PARTITIONS["root"],SYSIMG_PATH), log )
85
86     log.write( "mounting vserver partition in root file system\n" )
87     utils.makedirs( SYSIMG_PATH + "/vservers" )
88     utils.sysexec( "mount -t ext3 %s %s/vservers" % (PARTITIONS["vservers"],
89                                                      SYSIMG_PATH), log )
90
91     vars['ROOT_MOUNTED']= 1
92
93     # check which nodegroups we are part of (>=4.0)
94     utils.breakpoint("querying nodegroups for loading extensions")
95     try:
96         nodes = BootAPI.call_api_function(vars, "GetNodes", ([NODE_ID], ['nodegroup_ids']))
97         node = nodes[0]
98         nodegroups = BootAPI.call_api_function(vars, "GetNodeGroups", (node['nodegroup_ids'], ['name']))
99         nodegroupnames = [ nodegroup['name'].lower() for nodegroup in nodegroups ]
100
101     except:
102         log.write("WARNING : Failed to query nodegroups - installing only core software\n")
103         nodegroupnames = []
104         pass
105
106     # see also GetBootMedium in PLCAPI that does similar things
107     # figuring the default node family:
108     # (1) look at /etc/planetlab/nodefamily on the bootcd
109     # (2) otherwise use GetPlcRelease()
110     # (3) if everything else fails, set to planetlab-i386
111     try:
112         (pldistro,arch) = file("/etc/planetlab/nodefamily").read().split("-")
113     except:
114         # fetch the pldistro our myplc was built upon
115         try:
116             plc_release = BootAPI.call_api_function (vars, "GetPlcRelease",())
117             pldistro = plc_release ['build']['planetlab-distro']
118             arch = plc_release ['build']['target-arch']
119         except:
120             (pldistro,arch) = ("planetlab","i386")
121
122     # scan nodegroupnames - temporary, as most of this nodegroup-based info 
123     # should be more adequately defined in the nodes data model
124     known_archs = [ 'i386', 'x86_64' ]
125     extensions = []
126     # (1) if groupname == arch, nodefamily becomes pldistro-groupname
127     # (2) else if groupname looks like pldistro-arch, it is taken as a nodefamily
128     # (3) otherwise groupname is taken as an extension
129     for nodegroupname in nodegroupnames:
130         if nodegroupname in known_archs:
131             arch = nodegroupname
132         else:
133             is_nodefamily = False
134             for known_arch in known_archs:
135                 try:
136                     (api_pldistro,api_arch)=nodegroupname.split("-")
137                     # sanity check
138                     if api_arch != known_arch: raise Exception,"mismatch"
139                     (pldistro,arch) = (api_pldistro, api_arch)
140                     is_nodefamily = True
141                     break
142                 except:
143                     pass
144             if not is_nodefamily:
145                 extensions.append(nodegroupname)
146             
147     bootstrapfs_names = [ pldistro ] + extensions
148
149     # download and extract support tarball for this step, which has
150     # everything we need to successfully run
151
152     # we first try to find a tarball, if it is not found we use yum instead
153     yum_extensions = []
154     # download and extract support tarball for this step, 
155     for bootstrapfs_name in bootstrapfs_names:
156         tarball = "bootstrapfs-%s-%s.tar.bz2"%(bootstrapfs_name,arch)
157         source_file= "%s/%s" % (SUPPORT_FILE_DIR,tarball)
158         dest_file= "%s/%s" % (SYSIMG_PATH, tarball)
159
160         # 30 is the connect timeout, 14400 is the max transfer time in
161         # seconds (4 hours)
162         log.write( "downloading %s\n" % source_file )
163         result= bs_request.DownloadFile( source_file, None, None,
164                                          1, 1, dest_file,
165                                          30, 14400)
166         if result:
167             log.write( "extracting %s in %s\n" % (dest_file,SYSIMG_PATH) )
168             result= utils.sysexec( "tar -C %s -xpjf %s" % (SYSIMG_PATH,dest_file), log )
169             log.write( "Done\n")
170             utils.removefile( dest_file )
171         else:
172             # the main tarball is required
173             if bootstrapfs_name == pldistro:
174                 raise BootManagerException, "Unable to download main tarball %s from server." % \
175                     source_file
176             else:
177                 log.write("tarball for %s-%s not found, scheduling a yum attempt\n"%(bootstrapfs_name,arch))
178                 yum_extensions.append(bootstrapfs_name)
179
180     # copy resolv.conf from the base system into our temp dir
181     # so DNS lookups work correctly while we are chrooted
182     log.write( "Copying resolv.conf to temp dir\n" )
183     utils.sysexec( "cp /etc/resolv.conf %s/etc/" % SYSIMG_PATH, log )
184
185     # Copy the boot server certificate(s) and GPG public key to
186     # /usr/boot in the temp dir.
187     log.write( "Copying boot server certificates and public key\n" )
188
189     if os.path.exists("/usr/boot"):
190         utils.makedirs(SYSIMG_PATH + "/usr")
191         shutil.copytree("/usr/boot", SYSIMG_PATH + "/usr/boot")
192     elif os.path.exists("/usr/bootme"):
193         utils.makedirs(SYSIMG_PATH + "/usr/boot")
194         boot_server = file("/usr/bootme/BOOTSERVER").readline().strip()
195         shutil.copy("/usr/bootme/cacert/" + boot_server + "/cacert.pem",
196                     SYSIMG_PATH + "/usr/boot/cacert.pem")
197         file(SYSIMG_PATH + "/usr/boot/boot_server", "w").write(boot_server)
198         shutil.copy("/usr/bootme/pubring.gpg", SYSIMG_PATH + "/usr/boot/pubring.gpg")
199         
200     # For backward compatibility
201     if os.path.exists("/usr/bootme"):
202         utils.makedirs(SYSIMG_PATH + "/mnt/cdrom")
203         shutil.copytree("/usr/bootme", SYSIMG_PATH + "/mnt/cdrom/bootme")
204
205     # Import the GPG key into the RPM database so that RPMS can be verified
206     utils.makedirs(SYSIMG_PATH + "/etc/pki/rpm-gpg")
207     utils.sysexec("gpg --homedir=/root --export --armor" \
208                   " --no-default-keyring --keyring %s/usr/boot/pubring.gpg" \
209                   " >%s/etc/pki/rpm-gpg/RPM-GPG-KEY-planetlab" % (SYSIMG_PATH, SYSIMG_PATH))
210     utils.sysexec("chroot %s rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-planetlab" % \
211                   SYSIMG_PATH)
212
213     # yum-based extensions:
214     # before we can use yum, yum.conf needs to get installed
215     # xxx this should probably depend on the node's nodegroup, at least among alpha, beta ..
216     # however there does not seem to be a clear interface for that in yum.conf.php
217     # so let's keep it simple for the bootstrap phase, as yum.conf will get overwritten anyway
218     if yum_extensions:
219         getDict = {'gpgcheck':1,'arch':arch}
220         url="PlanetLabConf/yum.conf.php"
221         dest="%s/etc/yum.conf"%SYSIMG_PATH
222         log.write("downloading bootstrap yum.conf\n")
223         yumconf=bs_request.DownloadFile (url,getDict,None,
224                                          1, 1, dest)
225         if not yumconf:
226             log.write("Cannot fetch %s from %s - aborting yum extensions"%(dest,url))
227             # failures here should not stop the install process
228             return 1
229
230         # yum also needs /proc to be mounted 
231         # do it here so as to not break the tarballs-only case
232         cmd = "mount -t proc none %s/proc" % SYSIMG_PATH
233         utils.sysexec( cmd, log )
234         # we now just need to yum groupinstall everything
235         for extension in yum_extensions:
236             yum_command="yum groupinstall extension%s"%extension
237             utils.breakpoint ("before chroot %s %s"%(SYSIMG_PATH,yum_command))
238             log.write("Attempting to install extension %s through yum\n"%extension)
239             utils.sysexec_noerr("chroot %s %s" % (SYSIMG_PATH,yum_command))
240             # xxx how to check that this completed correctly ?
241         # let's cleanup
242         utils.sysexec_noerr( "umount %s/proc" % SYSIMG_PATH, log )
243         utils.breakpoint ("Done with yum extensions")
244
245     return 1