fix the parted-version selection code, f14 has parted.version broken
[bootmanager.git] / source / steps / InstallPartitionDisks.py
1 #!/usr/bin/python
2
3 # Copyright (c) 2003 Intel Corporation
4 # All rights reserved.
5 #
6 # Copyright (c) 2004-2006 The Trustees of Princeton University
7 # All rights reserved.
8 # expected /proc/partitions format
9
10 import os, sys
11 import string
12 import popen2
13
14
15 from Exceptions import *
16 import utils
17 import BootServerRequest
18
19 import ModelOptions
20
21 def Run( vars, log ):
22     """
23     Setup the block devices for install, partition them w/ LVM
24     
25     Expect the following variables from the store:
26     INSTALL_BLOCK_DEVICES    list of block devices to install onto
27     TEMP_PATH                somewhere to store what we need to run
28     ROOT_SIZE                the size of the root logical volume
29     SWAP_SIZE                the size of the swap partition
30     """
31
32     log.write( "\n\nStep: Install: partitioning disks.\n" )
33         
34     # make sure we have the variables we need
35     try:
36         TEMP_PATH= vars["TEMP_PATH"]
37         if TEMP_PATH == "":
38             raise ValueError, "TEMP_PATH"
39
40         INSTALL_BLOCK_DEVICES= vars["INSTALL_BLOCK_DEVICES"]
41         if( len(INSTALL_BLOCK_DEVICES) == 0 ):
42             raise ValueError, "INSTALL_BLOCK_DEVICES is empty"
43
44         ROOT_SIZE= vars["ROOT_SIZE"]
45         if ROOT_SIZE == "" or ROOT_SIZE == 0:
46             raise ValueError, "ROOT_SIZE invalid"
47
48         SWAP_SIZE= vars["SWAP_SIZE"]
49         if SWAP_SIZE == "" or SWAP_SIZE == 0:
50             raise ValueError, "SWAP_SIZE invalid"
51
52         NODE_MODEL_OPTIONS= vars["NODE_MODEL_OPTIONS"]
53
54         PARTITIONS= vars["PARTITIONS"]
55         if PARTITIONS == None:
56             raise ValueError, "PARTITIONS"
57
58         if NODE_MODEL_OPTIONS & ModelOptions.RAWDISK:
59             VSERVERS_SIZE= "-1"
60             if "VSERVERS_SIZE" in vars:
61                 VSERVERS_SIZE= vars["VSERVERS_SIZE"]
62                 if VSERVERS_SIZE == "" or VSERVERS_SIZE == 0:
63                     raise ValueError, "VSERVERS_SIZE"
64
65     except KeyError, var:
66         raise BootManagerException, "Missing variable in vars: %s\n" % var
67     except ValueError, var:
68         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
69
70     bs_request= BootServerRequest.BootServerRequest(vars)
71
72     
73     # disable swap if its on
74     utils.sysexec_noerr( "swapoff %s" % PARTITIONS["swap"], log )
75
76     # shutdown and remove any lvm groups/volumes
77     utils.sysexec_noerr( "vgscan", log )
78     utils.sysexec_noerr( "vgchange -ay", log )        
79     utils.sysexec_noerr( "lvremove -f %s" % PARTITIONS["root"], log )
80     utils.sysexec_noerr( "lvremove -f %s" % PARTITIONS["swap"], log )
81     utils.sysexec_noerr( "lvremove -f %s" % PARTITIONS["vservers"], log )
82     utils.sysexec_noerr( "vgchange -an", log )
83     utils.sysexec_noerr( "vgremove -f planetlab", log )
84
85     log.write( "Running vgscan for devices\n" )
86     utils.sysexec_noerr( "vgscan", log )
87     
88     used_devices= []
89
90     INSTALL_BLOCK_DEVICES.sort()
91     for device in INSTALL_BLOCK_DEVICES:
92
93         if single_partition_device( device, vars, log ):
94             if (len(used_devices) > 0 and
95                 (vars['NODE_MODEL_OPTIONS'] & ModelOptions.RAWDISK)):
96                 log.write( "Running in raw disk mode, not using %s.\n" % device )
97             else:
98                 used_devices.append( device )
99                 log.write( "Successfully initialized %s\n" % device )
100         else:
101             log.write( "Unable to partition %s, not using it.\n" % device )
102             continue
103
104     # list of devices to be used with vgcreate
105     vg_device_list= ""
106
107     # initialize the physical volumes
108     for device in used_devices:
109
110         part_path= get_partition_path_from_device( device, vars, log )
111         
112         if not create_lvm_physical_volume( part_path, vars, log ):
113             raise BootManagerException, "Could not create lvm physical volume " \
114                   "on partition %s" % part_path
115         
116         vg_device_list = vg_device_list + " " + part_path
117
118     # create an lvm volume group
119     utils.sysexec( "vgcreate -s32M planetlab %s" % vg_device_list, log)
120
121     # create swap logical volume
122     utils.sysexec( "lvcreate -L%s -nswap planetlab" % SWAP_SIZE, log )
123
124     # create root logical volume
125     utils.sysexec( "lvcreate -L%s -nroot planetlab" % ROOT_SIZE, log )
126
127     if vars['NODE_MODEL_OPTIONS'] & ModelOptions.RAWDISK and VSERVERS_SIZE != "-1":
128         utils.sysexec( "lvcreate -L%s -nvservers planetlab" % VSERVERS_SIZE, log )
129         remaining_extents= get_remaining_extents_on_vg( vars, log )
130         utils.sysexec( "lvcreate -l%s -nrawdisk planetlab" % remaining_extents, log )
131     else:
132         # create vservers logical volume with all remaining space
133         # first, we need to get the number of remaining extents we can use
134         remaining_extents= get_remaining_extents_on_vg( vars, log )
135         
136         utils.sysexec( "lvcreate -l%s -nvservers planetlab" % remaining_extents, log )
137
138     # activate volume group (should already be active)
139     #utils.sysexec( TEMP_PATH + "vgchange -ay planetlab", log )
140
141     # make swap
142     utils.sysexec( "mkswap %s" % PARTITIONS["swap"], log )
143
144     # check if badhd option has been set
145     option = ''
146     txt = ''
147     if NODE_MODEL_OPTIONS & ModelOptions.BADHD:
148         option = '-c'
149         txt = " with bad block search enabled, which may take a while"
150     
151     # filesystems partitions names and their corresponding
152     # reserved-blocks-percentages
153     filesystems = {"root":5,"vservers":0}
154
155     # make the file systems
156     for fs in filesystems.keys():
157         # get the reserved blocks percentage
158         rbp = filesystems[fs]
159         devname = PARTITIONS[fs]
160         log.write("formatting %s partition (%s)%s.\n" % (fs,devname,txt))
161         utils.sysexec( "mkfs.ext2 -q %s -m %d -j %s" % (option,rbp,devname), log )
162
163     # disable time/count based filesystems checks
164     for filesystem in ("root","vservers"):
165         utils.sysexec_noerr( "tune2fs -c -1 -i 0 %s" % PARTITIONS[filesystem], log)
166
167     # save the list of block devices in the log
168     log.write( "Block devices used (in lvm): %s\n" % repr(used_devices))
169
170     # list of block devices used may be updated
171     vars["INSTALL_BLOCK_DEVICES"]= used_devices
172
173     return 1
174
175
176 import parted
177 def single_partition_device( device, vars, log ):
178     """
179     initialize a disk by removing the old partition tables,
180     and creating a new single partition that fills the disk.
181
182     return 1 if sucessful, 0 otherwise
183     """
184
185     # two forms, depending on which version of pyparted we have
186     # v1 does not have a 'version' method
187     # v2 and above does, but to make it worse, 
188     # parted-3.4 on f14 has parted.version broken and raises SystemError
189     try:
190         parted.version()
191         return single_partition_device_2_x (device, vars, log)
192     except AttributeError:
193         # old parted does not have version at all
194         return single_partition_device_1_x (device, vars, log)
195     except SystemError:
196         # let's assume this is >=2
197         return single_partition_device_2_x (device, vars, log)
198     except:
199         raise
200
201 def single_partition_device_1_x ( device, vars, log):
202     
203     lvm_flag= parted.partition_flag_get_by_name('lvm')
204     
205     try:
206         print >>log, "Using pyparted 1.x"
207         # wipe the old partition table
208         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % device, log )
209
210         # get the device
211         dev= parted.PedDevice.get(device)
212
213         # create a new partition table
214         disk= dev.disk_new_fresh(parted.disk_type_get("msdos"))
215
216         # create one big partition on each block device
217         constraint= dev.constraint_any()
218
219         new_part= disk.partition_new(
220             parted.PARTITION_PRIMARY,
221             parted.file_system_type_get("ext2"),
222             0, 1 )
223
224         # make it an lvm partition
225         new_part.set_flag(lvm_flag,1)
226
227         # actually add the partition to the disk
228         disk.add_partition(new_part, constraint)
229
230         disk.maximize_partition(new_part,constraint)
231
232         disk.commit()
233         del disk
234             
235     except BootManagerException, e:
236         log.write( "BootManagerException while running: %s\n" % str(e) )
237         return 0
238
239     except parted.error, e:
240         log.write( "parted exception while running: %s\n" % str(e) )
241         return 0
242                    
243     return 1
244
245
246
247 def single_partition_device_2_x ( device, vars, log):
248     try:
249         print >>log, "Using pyparted 2.x"
250         # wipe the old partition table
251         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % device, log )
252         # get the device
253         dev= parted.Device(device)
254         # create a new partition table
255         disk= parted.freshDisk(dev,'msdos')
256         # create one big partition on each block device
257         constraint= parted.constraint.Constraint (device=dev)
258         geometry = parted.geometry.Geometry (device=dev, start=0, end=1)
259         fs = parted.filesystem.FileSystem (type="ext2",geometry=geometry)
260         new_part= parted.partition.Partition (disk, type=parted.PARTITION_NORMAL, 
261                                               fs=fs, geometry=geometry)
262         # make it an lvm partition
263         new_part.setFlag(parted.PARTITION_LVM)
264         # actually add the partition to the disk
265         disk.addPartition(new_part, constraint)
266         disk.maximizePartition(new_part,constraint)
267         disk.commit()
268         print >>log, 'Current disk for %s'%device,disk
269         print >>log, 'Current dev for %s'%device,dev
270         del disk
271     except Exception, e:
272         log.write( "Exception inside single_partition_device_2_x : %s\n" % str(e) )
273         import traceback
274         traceback.print_exc(file=log)
275         return 0
276                    
277     return 1
278
279
280
281 def create_lvm_physical_volume( part_path, vars, log ):
282     """
283     make the specificed partition a lvm physical volume.
284
285     return 1 if successful, 0 otherwise.
286     """
287
288     try:
289         # again, wipe any old data, this time on the partition
290         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % part_path, log )
291         ### patch Thierry Parmentelat, required on some hardware
292         import time
293         time.sleep(1)
294         utils.sysexec( "pvcreate -ffy %s" % part_path, log )
295     except BootManagerException, e:
296         log.write( "create_lvm_physical_volume failed.\n" )
297         return 0
298
299     return 1
300
301
302
303 def get_partition_path_from_device( device, vars, log ):
304     """
305     given a device, return the path of the first partition on the device
306     """
307
308     # those who wrote the cciss driver just had to make it difficult
309     cciss_test= "/dev/cciss"
310     if device[:len(cciss_test)] == cciss_test:
311         part_path= device + "p1"
312     else:
313         part_path= device + "1"
314
315     return part_path
316
317
318
319 def get_remaining_extents_on_vg( vars, log ):
320     """
321     return the free amount of extents on the planetlab volume group
322     """
323     
324     c_stdout, c_stdin = popen2.popen2("vgdisplay -c planetlab")
325     result= string.strip(c_stdout.readline())
326     c_stdout.close()
327     c_stdin.close()
328     remaining_extents= string.split(result,":")[15]
329     
330     return remaining_extents