check deployment node tag and if present install the deployment bootstrapfs.
[bootmanager.git] / source / steps / InstallBootstrapFS.py
1 #!/usr/bin/python
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 import traceback 
14
15 from Exceptions import *
16 import utils
17 import BootServerRequest
18 import BootAPI
19
20
21 def Run( vars, log ):
22     """
23     Download enough files to run rpm and yum from a chroot in
24     the system image directory
25     
26     Expect the following variables from the store:
27     SYSIMG_PATH          the path where the system image will be mounted
28     PARTITIONS           dictionary of generic part. types (root/swap)
29                          and their associated devices.
30     SUPPORT_FILE_DIR     directory on the boot servers containing
31                          scripts and support files
32     NODE_ID              the id of this machine
33     
34     Sets the following variables:
35     TEMP_BOOTCD_PATH     where the boot cd is remounted in the temp
36                          path
37     ROOT_MOUNTED         set to 1 when the the base logical volumes
38                          are mounted.
39     """
40
41     log.write( "\n\nStep: Install: bootstrapfs tarball.\n" )
42
43     # make sure we have the variables we need
44     try:
45         SYSIMG_PATH= vars["SYSIMG_PATH"]
46         if SYSIMG_PATH == "":
47             raise ValueError, "SYSIMG_PATH"
48
49         PARTITIONS= vars["PARTITIONS"]
50         if PARTITIONS == None:
51             raise ValueError, "PARTITIONS"
52
53         SUPPORT_FILE_DIR= vars["SUPPORT_FILE_DIR"]
54         if SUPPORT_FILE_DIR == None:
55             raise ValueError, "SUPPORT_FILE_DIR"
56
57         NODE_ID= vars["NODE_ID"]
58         if NODE_ID == "":
59             raise ValueError, "NODE_ID"
60
61     except KeyError, var:
62         raise BootManagerException, "Missing variable in vars: %s\n" % var
63     except ValueError, var:
64         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
65
66
67     try:
68         # make sure the required partitions exist
69         val= PARTITIONS["root"]
70         val= PARTITIONS["swap"]
71         val= PARTITIONS["vservers"]
72     except KeyError, part:
73         log.write( "Missing partition in PARTITIONS: %s\n" % part )
74         return 0   
75
76     bs_request= BootServerRequest.BootServerRequest(vars)
77     
78     log.write( "turning on swap space\n" )
79     utils.sysexec( "swapon %s" % PARTITIONS["swap"], log )
80
81     # make sure the sysimg dir is present
82     utils.makedirs( SYSIMG_PATH )
83
84     log.write( "mounting root file system\n" )
85     utils.sysexec( "mount -t ext3 %s %s" % (PARTITIONS["root"],SYSIMG_PATH), log )
86
87     log.write( "mounting vserver partition in root file system\n" )
88     utils.makedirs( SYSIMG_PATH + "/vservers" )
89     utils.sysexec( "mount -t ext3 %s %s/vservers" % (PARTITIONS["vservers"],
90                                                      SYSIMG_PATH), log )
91
92     vars['ROOT_MOUNTED']= 1
93
94     # check deployment (if it's alpha?)
95     deployment = ""
96     try:
97         node_tag_ids = BootAPI.call_api_function(vars, "GetNodes", (NODE_ID,))[0]['node_tag_ids']
98         node_tags = BootAPI.call_api_function(vars, "GetNodeTags", (node_tag_ids,))
99         deployment_tag = [x for x in node_tags if x['tagname'] == 'deployment']
100         if deployment_tag:
101             deployment = deployment_tag[0]['value']
102     except:
103         log.write("WARNING : Failed to query tag 'deployment'\n")
104         log.write(traceback.format_exc())
105
106     # which extensions are we part of ?
107     utils.breakpoint("Checking for the extension(s) tags")
108     extensions = []
109     try:
110         extension_tag = BootAPI.call_api_function(vars, "GetNodeExtensions", (NODE_ID,) )
111         if extension_tag:
112             extensions = extension_tag.split()
113
114     except:
115         log.write("WARNING : Failed to query tag 'extensions'\n")
116         log.write(traceback.format_exc())
117
118     if not extensions:
119         log.write("installing only core software\n")
120     
121     # check if the plain-bootstrapfs tag is set
122     download_suffix=".tar.bz2"
123     untar_option="-j"
124     try:
125         if BootAPI.call_api_function (vars, "GetNodePlainBootstrapfs", (NODE_ID,) ):
126             download_suffix=".tar"
127             untar_option=""
128     except:
129         log.write("WARNING : Failed to query tag 'plain-bootstrapfs'\n")
130         log.write(traceback.format_exc())
131
132     if not untar_option:
133         log.write("Using uncompressed bootstrapfs images\n")
134
135     # see also GetBootMedium in PLCAPI that does similar things
136     # figuring the default node family:
137     # (1) get node's tags 'arch' and 'pldistro'
138     # (2) if unsuccessful search /etc/planetlab/nodefamily on the bootcd
139     # (3) if that fails, set to planetlab-i386
140
141     try:
142         api_pldistro = BootAPI.call_api_function(vars, "GetNodePldistro", (NODE_ID,) )
143     except:
144         log.write("WARNING : Failed to query tag 'pldistro'\n")
145         api_pldistro = None
146     try:
147         api_arch = BootAPI.call_api_function(vars, "GetNodeArch", (NODE_ID,) )
148     except:
149         log.write("WARNING : Failed to query tag 'arch'\n")
150         api_arch = None
151     try:
152         (etc_pldistro,etc_arch) = file("/etc/planetlab/nodefamily").read().strip().split("-")
153     except:
154         log.write("WARNING : Failed to parse /etc/planetlab/nodefamily\n")
155         (etc_pldistro,etc_arch)=(None,None)
156     default_pldistro="planetlab"
157     default_arch="i386"
158
159     if api_pldistro:
160         pldistro = api_pldistro
161         log.write ("Using pldistro from pldistro API tag\n")
162     elif etc_pldistro:
163         pldistro = etc_pldistro
164         log.write ("Using pldistro from /etc/planetlab/nodefamily\n")
165     else:
166         pldistro = default_pldistro
167         log.write ("Using default pldistro\n")
168
169     if api_arch:
170         arch = api_arch
171         log.write ("Using arch from arch API tag\n")
172     elif etc_arch:
173         arch = etc_arch
174         log.write ("Using arch from /etc/planetlab/nodefamily\n")
175     else:
176         arch = default_arch
177         log.write ("Using default arch\n")
178
179     log.write ("Using nodefamily=%s-%s\n"%(pldistro,arch))
180
181     bootstrapfs_names = [ pldistro ] + extensions
182
183     # download and extract support tarball for this step, which has
184     # everything we need to successfully run
185
186     # we first try to find a tarball, if it is not found we use yum instead
187     yum_extensions = []
188     # download and extract support tarball for this step, 
189     for bootstrapfs_name in bootstrapfs_names:
190         tarball = "bootstrapfs-%s-%s%s"%(bootstrapfs_name,arch,download_suffix)
191         if len(deployment):
192             # we keep bootstrapfs tarballs for deployments in a
193             # sub-folder, but with same filenames
194             tarball = "%s/%s" %(deployment, tarball)
195         source_file= "%s/%s" % (SUPPORT_FILE_DIR,tarball)
196         dest_file= "%s/%s" % (SYSIMG_PATH, os.path.basename(tarball))
197
198         # 30 is the connect timeout, 14400 is the max transfer time in
199         # seconds (4 hours)
200         log.write( "downloading %s\n" % source_file )
201         result= bs_request.DownloadFile( source_file, None, None,
202                                          1, 1, dest_file,
203                                          30, 14400)
204         if result:
205             log.write( "extracting %s in %s\n" % (dest_file,SYSIMG_PATH) )
206             result= utils.sysexec( "tar -C %s -xpf %s %s" % (SYSIMG_PATH,dest_file,untar_option), log )
207             log.write( "Done\n")
208             utils.removefile( dest_file )
209         else:
210             # the main tarball is required
211             if bootstrapfs_name == pldistro:
212                 raise BootManagerException, "Unable to download main tarball %s from server." % \
213                     source_file
214             else:
215                 log.write("tarball for %s-%s not found, scheduling a yum attempt\n"%(bootstrapfs_name,arch))
216                 yum_extensions.append(bootstrapfs_name)
217
218     # copy resolv.conf from the base system into our temp dir
219     # so DNS lookups work correctly while we are chrooted
220     log.write( "Copying resolv.conf to temp dir\n" )
221     utils.sysexec( "cp /etc/resolv.conf %s/etc/" % SYSIMG_PATH, log )
222
223     # Copy the boot server certificate(s) and GPG public key to
224     # /usr/boot in the temp dir.
225     log.write( "Copying boot server certificates and public key\n" )
226
227     if os.path.exists("/usr/boot"):
228         utils.makedirs(SYSIMG_PATH + "/usr")
229         shutil.copytree("/usr/boot", SYSIMG_PATH + "/usr/boot")
230     elif os.path.exists("/usr/bootme"):
231         utils.makedirs(SYSIMG_PATH + "/usr/boot")
232         boot_server = file("/usr/bootme/BOOTSERVER").readline().strip()
233         shutil.copy("/usr/bootme/cacert/" + boot_server + "/cacert.pem",
234                     SYSIMG_PATH + "/usr/boot/cacert.pem")
235         file(SYSIMG_PATH + "/usr/boot/boot_server", "w").write(boot_server)
236         shutil.copy("/usr/bootme/pubring.gpg", SYSIMG_PATH + "/usr/boot/pubring.gpg")
237         
238     # For backward compatibility
239     if os.path.exists("/usr/bootme"):
240         utils.makedirs(SYSIMG_PATH + "/mnt/cdrom")
241         shutil.copytree("/usr/bootme", SYSIMG_PATH + "/mnt/cdrom/bootme")
242
243     # Import the GPG key into the RPM database so that RPMS can be verified
244     utils.makedirs(SYSIMG_PATH + "/etc/pki/rpm-gpg")
245     utils.sysexec("gpg --homedir=/root --export --armor" \
246                   " --no-default-keyring --keyring %s/usr/boot/pubring.gpg" \
247                   " >%s/etc/pki/rpm-gpg/RPM-GPG-KEY-planetlab" % (SYSIMG_PATH, SYSIMG_PATH))
248     utils.sysexec_chroot(SYSIMG_PATH, "rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-planetlab")
249
250     # the yum config has changed entirely; 
251     # in addition yum installs have more or less never worked - let's forget about this
252     # maybe NodeManager could profitably do the job instead
253     if yum_extensions:
254         log.write("WARNING : yum installs for node extensions are not supported anymore\n")
255
256     return 1