check in all bootmanager sources
[bootmanager.git] / source / steps / InstallPartitionDisks.py
1 # Copyright (c) 2003 Intel Corporation
2 # All rights reserved.
3
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
6 # met:
7
8 #     * Redistributions of source code must retain the above copyright
9 #       notice, this list of conditions and the following disclaimer.
10
11 #     * Redistributions in binary form must reproduce the above
12 #       copyright notice, this list of conditions and the following
13 #       disclaimer in the documentation and/or other materials provided
14 #       with the distribution.
15
16 #     * Neither the name of the Intel Corporation nor the names of its
17 #       contributors may be used to endorse or promote products derived
18 #       from this software without specific prior written permission.
19
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
24 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32 # EXPORT LAWS: THIS LICENSE ADDS NO RESTRICTIONS TO THE EXPORT LAWS OF
33 # YOUR JURISDICTION. It is licensee's responsibility to comply with any
34 # export regulations applicable in licensee's jurisdiction. Under
35 # CURRENT (May 2000) U.S. export regulations this software is eligible
36 # for export from the U.S. and can be downloaded by or otherwise
37 # exported or reexported worldwide EXCEPT to U.S. embargoed destinations
38 # which include Cuba, Iraq, Libya, North Korea, Iran, Syria, Sudan,
39 # Afghanistan and any other country to which the U.S. has embargoed
40 # goods and services.
41
42
43 import os, sys
44 import string
45 import popen2
46
47
48 from Exceptions import *
49 import utils
50 import BootServerRequest
51 import compatibility
52
53
54
55 def Run( vars, log ):
56     """
57     Setup the block devices for install, partition them w/ LVM
58     
59     Expect the following variables from the store:
60     INSTALL_BLOCK_DEVICES    list of block devices to install onto
61     TEMP_PATH                somewhere to store what we need to run
62     ROOT_SIZE                the size of the root logical volume
63     SWAP_SIZE                the size of the swap partition
64     ALPINA_SERVER_DIR        directory on the boot servers containing alpina
65                              scripts and support files
66     BOOT_CD_VERSION          A tuple of the current bootcd version
67     
68     Sets the following variables:
69     PARTITIONS               diction of generic part. types (root/swap)
70                              and their associated devices.
71                              Current keys/values:
72                                  root    /dev/planetlab/root
73                                  swap    /dev/planetlab/swap
74     
75     """
76
77     log.write( "\n\nStep: Install: partitioning disks.\n" )
78         
79     # make sure we have the variables we need
80     try:
81         TEMP_PATH= vars["TEMP_PATH"]
82         if TEMP_PATH == "":
83             raise ValueError, "TEMP_PATH"
84
85         INSTALL_BLOCK_DEVICES= vars["INSTALL_BLOCK_DEVICES"]
86         if( len(INSTALL_BLOCK_DEVICES) == 0 ):
87             raise ValueError, "INSTALL_BLOCK_DEVICES is empty"
88
89         ROOT_SIZE= vars["ROOT_SIZE"]
90         if ROOT_SIZE == "" or ROOT_SIZE == 0:
91             raise ValueError, "ROOT_SIZE invalid"
92
93         SWAP_SIZE= vars["SWAP_SIZE"]
94         if SWAP_SIZE == "" or SWAP_SIZE == 0:
95             raise ValueError, "SWAP_SIZE invalid"
96
97         ALPINA_SERVER_DIR= vars["ALPINA_SERVER_DIR"]
98         if ALPINA_SERVER_DIR == None:
99             raise ValueError, "ALPINA_SERVER_DIR"
100
101         BOOT_CD_VERSION= vars["BOOT_CD_VERSION"]
102         if BOOT_CD_VERSION == "":
103             raise ValueError, "BOOT_CD_VERSION"
104
105     except KeyError, var:
106         raise BootManagerException, "Missing variable in vars: %s\n" % var
107     except ValueError, var:
108         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
109
110     bs_request= BootServerRequest.BootServerRequest()
111
112     
113     # old cds need extra utilities to partition disks and setup lvm
114     if BOOT_CD_VERSION[0] == 2:
115         compatibility.setup_partdisks_2x_cd( vars, log )
116
117     import parted
118         
119     # define the basic partition paths
120     PARTITIONS= {}
121     PARTITIONS["root"]= "/dev/planetlab/root"
122     PARTITIONS["swap"]= "/dev/planetlab/swap"
123     PARTITIONS["vservers"]= "/dev/planetlab/vservers"
124     # Linux 2.6 mounts LVM with device mapper
125     PARTITIONS["mapper-root"]= "/dev/mapper/planetlab-root"
126     PARTITIONS["mapper-swap"]= "/dev/mapper/planetlab-swap"
127     PARTITIONS["mapper-vservers"]= "/dev/mapper/planetlab-vservers"
128     vars["PARTITIONS"]= PARTITIONS
129
130     
131     # disable swap if its on
132     utils.sysexec_noerr( "swapoff %s" % PARTITIONS["swap"], log )
133
134     # shutdown and remove any lvm groups/volumes
135     utils.sysexec_noerr( "vgscan", log )
136     utils.sysexec_noerr( "vgchange -ay", log )        
137     utils.sysexec_noerr( "lvremove -f /dev/planetlab/root", log )
138     utils.sysexec_noerr( "lvremove -f /dev/planetlab/swap", log )
139     utils.sysexec_noerr( "lvremove -f /dev/planetlab/vservers", log )
140     utils.sysexec_noerr( "vgchange -an", log )
141     utils.sysexec_noerr( "vgremove planetlab", log )
142
143     log.write( "Running vgscan for devices\n" )
144     utils.sysexec_noerr( "vgscan", log )
145     
146     used_devices= []
147
148     for device in INSTALL_BLOCK_DEVICES:
149
150         if single_partition_device( device, vars, log ):
151             used_devices.append( device )
152             log.write( "Successfully initialized %s\n" % device )
153         else:
154             log.write( "Unable to partition %s, not using it.\n" % device )
155             continue
156
157     # list of devices to be used with vgcreate
158     vg_device_list= ""
159
160     # initialize the physical volumes
161     for device in used_devices:
162
163         part_path= get_partition_path_from_device( device, vars, log )
164         
165         if not create_lvm_physical_volume( part_path, vars, log ):
166             raise BootManagerException, "Could not create lvm physical volume " \
167                   "on partition %s" % part_path
168         
169         vg_device_list = vg_device_list + " " + part_path
170
171     # create an lvm volume group
172     utils.sysexec( "vgcreate -s32M planetlab %s" % vg_device_list, log)
173
174     # create swap logical volume
175     utils.sysexec( "lvcreate -L%s -nswap planetlab" % SWAP_SIZE, log )
176
177     # create root logical volume
178     utils.sysexec( "lvcreate -L%s -nroot planetlab" % ROOT_SIZE, log )
179
180     # create vservers logical volume with all remaining space
181     # first, we need to get the number of remaining extents we can use
182     remaining_extents= get_remaining_extents_on_vg( vars, log )
183     
184     utils.sysexec( "lvcreate -l%s -nvservers planetlab" % remaining_extents, log )
185
186     # activate volume group (should already be active)
187     #utils.sysexec( TEMP_PATH + "vgchange -ay planetlab", log )
188
189     # make swap
190     utils.sysexec( "mkswap %s" % PARTITIONS["swap"], log )
191
192     # make root file system
193     utils.sysexec( "mkfs.ext2 -j %s" % PARTITIONS["root"], log )
194
195     # make vservers file system
196     utils.sysexec( "mkfs.ext2 -m 0 -j %s" % PARTITIONS["vservers"], log )
197
198     # save the list of block devices in the log
199     log.write( "Block devices used (in lvm):\n" )
200     log.write( repr(used_devices) + "\n" )
201     log.write( "End of block devices used (in lvm).\n" )
202
203     # list of block devices used may be updated
204     vars["INSTALL_BLOCK_DEVICES"]= used_devices
205
206     return 1
207
208
209
210 def single_partition_device( device, vars, log ):
211     """
212     initialize a disk by removing the old partition tables,
213     and creating a new single partition that fills the disk.
214
215     return 1 if sucessful, 0 otherwise
216     """
217
218     BOOT_CD_VERSION= vars["BOOT_CD_VERSION"]
219     if BOOT_CD_VERSION[0] == 2:
220         compatibility.setup_partdisks_2x_cd( vars, log )
221
222     import parted
223     
224     lvm_flag= parted.partition_flag_get_by_name('lvm')
225     
226     try:
227         # wipe the old partition table
228         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % device, log )
229
230         # get the device
231         dev= parted.PedDevice.get(device)
232
233         # 2.x cds have different libparted that 3.x cds, and they have
234         # different interfaces
235         if BOOT_CD_VERSION[0] == 3:
236
237             # create a new partition table
238             disk= dev.disk_new_fresh(parted.disk_type_get("msdos"))
239
240             # create one big partition on each block device
241             constraint= dev.constraint_any()
242
243             new_part= disk.partition_new(
244                 parted.PARTITION_PRIMARY,
245                 parted.file_system_type_get("ext2"),
246                 0, 1 )
247
248             # make it an lvm partition
249             new_part.set_flag(lvm_flag,1)
250
251             # actually add the partition to the disk
252             disk.add_partition(new_part, constraint)
253
254             disk.maximize_partition(new_part,constraint)
255
256             disk.commit()
257             del disk
258         else:
259             # create a new partition table
260             dev.disk_create(parted.disk_type_get("msdos"))
261
262             # get the disk
263             disk= parted.PedDisk.open(dev)
264
265                 # create one big partition on each block device
266             part= disk.next_partition()
267             while part:
268                 if part.type == parted.PARTITION_FREESPACE:
269                     new_part= disk.partition_new(
270                         parted.PARTITION_PRIMARY,
271                         parted.file_system_type_get("ext2"),
272                         part.geom.start,
273                         part.geom.end )
274
275                     constraint = disk.constraint_any()
276
277                     # make it an lvm partition
278                     new_part.set_flag(lvm_flag,1)
279
280                     # actually add the partition to the disk
281                     disk.add_partition(new_part, constraint)
282
283                     break
284
285                 part= disk.next_partition(part)
286
287             disk.write()
288             disk.close()
289             del disk
290             
291     except BootManagerException, e:
292         log.write( "BootManagerException while running: %s\n" % str(e) )
293         return 0
294
295     except parted.error, e:
296         log.write( "parted exception while running: %s\n" % str(e) )
297         return 0
298                    
299     return 1
300
301
302
303 def create_lvm_physical_volume( part_path, vars, log ):
304     """
305     make the specificed partition a lvm physical volume.
306
307     return 1 if successful, 0 otherwise.
308     """
309
310     try:
311         # again, wipe any old data, this time on the partition
312         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % part_path, log )
313         utils.sysexec( "pvcreate -fy %s" % part_path, log )
314     except BootManagerException, e:
315         log.write( "create_lvm_physical_volume failed.\n" )
316         return 0
317
318     return 1
319
320
321
322 def get_partition_path_from_device( device, vars, log ):
323     """
324     given a device, return the path of the first partition on the device
325     """
326
327     BOOT_CD_VERSION= vars["BOOT_CD_VERSION"]
328         
329     # those who wrote the cciss driver just had to make it difficult
330     if BOOT_CD_VERSION[0] == 3:
331         cciss_test= "/dev/cciss"
332         if device[:len(cciss_test)] == cciss_test:
333             part_path= device + "p1"
334         else:
335             part_path= device + "1"
336     else:
337         # since device ends in /disc, we need to make it end in
338         # /part1 to indicate the first partition (for devfs based 2.x cds)
339         dev_parts= string.split(device,"/")
340         dev_parts[len(dev_parts)-1]= "part1"
341         part_path= string.join(dev_parts,"/")
342
343     return part_path
344
345
346
347 def get_remaining_extents_on_vg( vars, log ):
348     """
349     return the free amount of extents on the planetlab volume group
350     """
351     
352     c_stdout, c_stdin = popen2.popen2("vgdisplay -c planetlab")
353     result= string.strip(c_stdout.readline())
354     c_stdout.close()
355     c_stdin.close()
356     remaining_extents= string.split(result,":")[15]
357     
358     return remaining_extents