add a comment about why this partitioning code is still 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 import time
14
15 from Exceptions import *
16 import utils
17 import BootServerRequest
18 import BootAPI
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     # get partitions
108     partitions = []
109     for device in used_devices:
110         part_path= get_partition_path_from_device( device, vars, log )
111         partitions.append(part_path)
112    
113     # create raid partition
114     raid_partition = create_raid_partition(partitions, vars, log)
115     if raid_partition != None:
116         partitions = [raid_partition]      
117     log.write("PARTITIONS %s\n" %  str(partitions)) 
118     # initialize the physical volumes
119     for part_path in partitions:
120         if not create_lvm_physical_volume( part_path, vars, log ):
121             raise BootManagerException, "Could not create lvm physical volume " \
122                   "on partition %s" % part_path
123         vg_device_list = vg_device_list + " " + part_path
124
125     # create an lvm volume group
126     utils.sysexec( "vgcreate -s32M planetlab %s" % vg_device_list, log)
127
128     # create swap logical volume
129     utils.sysexec( "lvcreate -L%s -nswap planetlab" % SWAP_SIZE, log )
130
131     # create root logical volume
132     utils.sysexec( "lvcreate -L%s -nroot planetlab" % ROOT_SIZE, log )
133
134     if vars['NODE_MODEL_OPTIONS'] & ModelOptions.RAWDISK and VSERVERS_SIZE != "-1":
135         utils.sysexec( "lvcreate -L%s -nvservers planetlab" % VSERVERS_SIZE, log )
136         remaining_extents= get_remaining_extents_on_vg( vars, log )
137         utils.sysexec( "lvcreate -l%s -nrawdisk planetlab" % remaining_extents, log )
138     else:
139         # create vservers logical volume with all remaining space
140         # first, we need to get the number of remaining extents we can use
141         remaining_extents= get_remaining_extents_on_vg( vars, log )
142         
143         utils.sysexec( "lvcreate -l%s -nvservers planetlab" % remaining_extents, log )
144
145     # activate volume group (should already be active)
146     #utils.sysexec( TEMP_PATH + "vgchange -ay planetlab", log )
147
148     # make swap
149     utils.sysexec( "mkswap -f %s" % PARTITIONS["swap"], log )
150
151     # check if badhd option has been set
152     option = ''
153     txt = ''
154     if NODE_MODEL_OPTIONS & ModelOptions.BADHD:
155         option = '-c'
156         txt = " with bad block search enabled, which may take a while"
157     
158     # filesystems partitions names and their corresponding
159     # reserved-blocks-percentages
160     filesystems = {"root":5,"vservers":0}
161
162     # make the file systems
163     for fs in filesystems.keys():
164         # get the reserved blocks percentage
165         rbp = filesystems[fs]
166         devname = PARTITIONS[fs]
167         log.write("formatting %s partition (%s)%s.\n" % (fs,devname,txt))
168         utils.sysexec( "mkfs.ext2 -q %s -m %d -j %s" % (option,rbp,devname), log )
169
170     # disable time/count based filesystems checks
171     for filesystem in ("root","vservers"):
172         utils.sysexec_noerr( "tune2fs -c -1 -i 0 %s" % PARTITIONS[filesystem], log)
173
174     # save the list of block devices in the log
175     log.write( "Block devices used (in lvm): %s\n" % repr(used_devices))
176
177     # list of block devices used may be updated
178     vars["INSTALL_BLOCK_DEVICES"]= used_devices
179
180     return 1
181
182
183 import parted
184 def single_partition_device( device, vars, log ):
185     """
186     initialize a disk by removing the old partition tables,
187     and creating a new single partition that fills the disk.
188
189     return 1 if sucessful, 0 otherwise
190     """
191
192     # two forms, depending on which version of pyparted we have
193     # v1 does not have a 'version' method
194     # v2 and above does, but to make it worse, 
195     # parted-3.4 on f14 has parted.version broken and raises SystemError
196     try:
197         parted.version()
198         return single_partition_device_2_x (device, vars, log)
199     except AttributeError:
200         # old parted does not have version at all
201         return single_partition_device_1_x (device, vars, log)
202     except SystemError:
203         # let's assume this is >=2
204         return single_partition_device_2_x (device, vars, log)
205     except:
206         raise
207
208 def single_partition_device_1_x ( device, vars, log):
209     
210     lvm_flag= parted.partition_flag_get_by_name('lvm')
211     
212     try:
213         log.write("Using pyparted 1.x\n")
214         # wipe the old partition table
215         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % device, log )
216
217         # get the device
218         dev= parted.PedDevice.get(device)
219
220         # create a new partition table
221         disk= dev.disk_new_fresh(parted.disk_type_get("msdos"))
222
223         # create one big partition on each block device
224         constraint= dev.constraint_any()
225
226         new_part= disk.partition_new(
227             parted.PARTITION_PRIMARY,
228             parted.file_system_type_get("ext2"),
229             0, 1 )
230
231         # make it an lvm partition
232         new_part.set_flag(lvm_flag,1)
233
234         # actually add the partition to the disk
235         disk.add_partition(new_part, constraint)
236
237         disk.maximize_partition(new_part,constraint)
238
239         disk.commit()
240         del disk
241             
242     except BootManagerException, e:
243         log.write( "BootManagerException while running: %s\n" % str(e) )
244         return 0
245
246     except parted.error, e:
247         log.write( "parted exception while running: %s\n" % str(e) )
248         return 0
249                    
250     return 1
251
252
253
254 def single_partition_device_2_x ( device, vars, log):
255     try:
256         log.write("Using pyparted 2.x\n")
257         # wipe the old partition table
258         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % device, log )
259         # get the device
260         dev= parted.Device(device)
261         # create a new partition table
262         # xxx -- Thierry june 2012
263         # original code was going for the msdos version only
264         # Marco Bicudo reported an error with a disk larger than 2TB
265         # and confirmed he node would take off by just changing 'msdos' into 'gpt'
266         # this version below has been tried but does not work
267         # as a matter of fact on the big node an exception gets thrown later
268         # at the maximizePartition stage only, which of course makes sense 
269         # so bottom line is, we need to find something smarter...
270         # xxx
271         try:
272             disk= parted.freshDisk(dev,'msdos')
273         # use gpt as a fallback for disks larger than 2TB
274         except:
275             disk= parted.freshDisk(dev,'gpt')
276         # create one big partition on each block device
277         constraint= parted.constraint.Constraint (device=dev)
278         geometry = parted.geometry.Geometry (device=dev, start=0, end=1)
279         fs = parted.filesystem.FileSystem (type="ext2",geometry=geometry)
280         new_part= parted.partition.Partition (disk, type=parted.PARTITION_NORMAL, 
281                                               fs=fs, geometry=geometry)
282         # make it an lvm partition
283         new_part.setFlag(parted.PARTITION_LVM)
284         # actually add the partition to the disk
285         disk.addPartition(new_part, constraint)
286         disk.maximizePartition(new_part,constraint)
287         disk.commit()
288         print >>log, 'Current disk for %s'%device,disk
289         print >>log, 'Current dev for %s'%device,dev
290         del disk
291     except Exception, e:
292         log.write( "Exception inside single_partition_device_2_x : %s\n" % str(e) )
293         import traceback
294         traceback.print_exc(file=log)
295         return 0
296                    
297     return 1
298
299
300
301 def create_lvm_physical_volume( part_path, vars, log ):
302     """
303     make the specificed partition a lvm physical volume.
304
305     return 1 if successful, 0 otherwise.
306     """
307
308     try:
309         # again, wipe any old data, this time on the partition
310         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % part_path, log )
311         ### patch Thierry Parmentelat, required on some hardware
312         import time
313         time.sleep(1)
314         utils.sysexec( "pvcreate -ffy %s" % part_path, log )
315     except BootManagerException, e:
316         log.write( "create_lvm_physical_volume failed.\n" )
317         return 0
318
319     return 1
320
321
322 def create_raid_partition(partitions, vars, log):
323     """
324     create raid array using specified partitions.  
325     """ 
326     raid_part = None
327     raid_enabled = False
328     node_tags = BootAPI.call_api_function( vars, "GetNodeTags",
329                                         ({'node_id': vars['NODE_ID']},))
330     for node_tag in node_tags:
331         if node_tag['tagname'] == 'raid_enabled' and \
332            node_tag['value'] == '1':
333             raid_enabled = True
334             break
335     if not raid_enabled:
336         return raid_part
337
338     try:
339         log.write( "Software raid enabled.\n" )
340         # wipe everything
341         utils.sysexec_noerr("mdadm --stop /dev/md0", log)
342         time.sleep(1)
343         for part_path in partitions:
344             utils.sysexec_noerr("mdadm --zero-superblock %s " % part_path, log)
345
346         # assume each partiton is on a separate disk
347         num_parts = len(partitions)
348         if num_parts < 2:
349             log.write( "Not enough disks for raid. Found: %s\n" % partitions )
350             raise BootManagerException("Not enough disks for raid. Found: %s\n" % partitions)  
351         if num_parts == 2:
352             lvl = 1
353         else:
354             lvl = 5   
355         
356         # make the array
357         part_list = " ".join(partitions)
358         raid_part = "/dev/md0"
359         cmd = "mdadm --create %(raid_part)s --chunk=128 --level=raid%(lvl)s " % locals() + \
360               "--raid-devices=%(num_parts)s %(part_list)s" % locals()
361         utils.sysexec(cmd, log)        
362
363     except BootManagerException, e:
364         log.write("create_raid_partition failed.\n")
365         raid_part = None
366
367     return raid_part  
368
369
370 def get_partition_path_from_device( device, vars, log ):
371     """
372     given a device, return the path of the first partition on the device
373     """
374
375     # those who wrote the cciss driver just had to make it difficult
376     cciss_test= "/dev/cciss"
377     if device[:len(cciss_test)] == cciss_test:
378         part_path= device + "p1"
379     else:
380         part_path= device + "1"
381
382     return part_path
383
384
385
386 def get_remaining_extents_on_vg( vars, log ):
387     """
388     return the free amount of extents on the planetlab volume group
389     """
390     
391     c_stdout, c_stdin = popen2.popen2("vgdisplay -c planetlab")
392     result= string.strip(c_stdout.readline())
393     c_stdout.close()
394     c_stdin.close()
395     remaining_extents= string.split(result,":")[15]
396     
397     return remaining_extents