Thomas's fix about calling mkfs.btrfs with the -f option
[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         # use vs_ROOT_SIZE or lxc_ROOT_SIZE as appropriate
45         varname=vars['virt']+"_ROOT_SIZE"
46         ROOT_SIZE= vars[varname]
47         if ROOT_SIZE == "" or ROOT_SIZE == 0:
48             raise ValueError, "ROOT_SIZE invalid"
49
50         SWAP_SIZE= vars["SWAP_SIZE"]
51         if SWAP_SIZE == "" or SWAP_SIZE == 0:
52             raise ValueError, "SWAP_SIZE invalid"
53
54         NODE_MODEL_OPTIONS= vars["NODE_MODEL_OPTIONS"]
55
56         PARTITIONS= vars["PARTITIONS"]
57         if PARTITIONS == None:
58             raise ValueError, "PARTITIONS"
59
60         if NODE_MODEL_OPTIONS & ModelOptions.RAWDISK:
61             VSERVERS_SIZE= "-1"
62             if "VSERVERS_SIZE" in vars:
63                 VSERVERS_SIZE= vars["VSERVERS_SIZE"]
64                 if VSERVERS_SIZE == "" or VSERVERS_SIZE == 0:
65                     raise ValueError, "VSERVERS_SIZE"
66
67     except KeyError, var:
68         raise BootManagerException, "Missing variable in vars: %s\n" % var
69     except ValueError, var:
70         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
71
72     bs_request= BootServerRequest.BootServerRequest(vars)
73
74     
75     # disable swap if its on
76     utils.sysexec_noerr( "swapoff %s" % PARTITIONS["swap"], log )
77
78     # shutdown and remove any lvm groups/volumes
79     utils.sysexec_noerr( "vgscan", log )
80     utils.sysexec_noerr( "vgchange -ay", log )        
81     utils.sysexec_noerr( "lvremove -f %s" % PARTITIONS["root"], log )
82     utils.sysexec_noerr( "lvremove -f %s" % PARTITIONS["swap"], log )
83     utils.sysexec_noerr( "lvremove -f %s" % PARTITIONS["vservers"], log )
84     utils.sysexec_noerr( "vgchange -an", log )
85     utils.sysexec_noerr( "vgremove -f planetlab", log )
86
87     log.write( "Running vgscan for devices\n" )
88     utils.sysexec_noerr( "vgscan", log )
89     
90     used_devices= []
91
92     INSTALL_BLOCK_DEVICES.sort()
93     for device in INSTALL_BLOCK_DEVICES:
94
95         if single_partition_device( device, vars, log ):
96             if (len(used_devices) > 0 and
97                 (vars['NODE_MODEL_OPTIONS'] & ModelOptions.RAWDISK)):
98                 log.write( "Running in raw disk mode, not using %s.\n" % device )
99             else:
100                 used_devices.append( device )
101                 log.write( "Successfully initialized %s\n" % device )
102         else:
103             log.write( "Unable to partition %s, not using it.\n" % device )
104             continue
105
106     # list of devices to be used with vgcreate
107     vg_device_list= ""
108
109     # get partitions
110     partitions = []
111     for device in used_devices:
112         part_path= get_partition_path_from_device( device, vars, log )
113         partitions.append(part_path)
114    
115     # create raid partition
116     raid_partition = create_raid_partition(partitions, vars, log)
117     if raid_partition != None:
118         partitions = [raid_partition]      
119     log.write("PARTITIONS %s\n" %  str(partitions)) 
120     # initialize the physical volumes
121     for part_path in partitions:
122         if not create_lvm_physical_volume( part_path, vars, log ):
123             raise BootManagerException, "Could not create lvm physical volume " \
124                   "on partition %s" % part_path
125         vg_device_list = vg_device_list + " " + part_path
126
127     # create an lvm volume group
128     utils.sysexec( "vgcreate -s32M planetlab %s" % vg_device_list, log)
129
130     # create swap logical volume
131     utils.sysexec( "lvcreate -L%s -nswap planetlab" % SWAP_SIZE, log )
132
133     # create root logical volume
134     utils.sysexec( "lvcreate -L%s -nroot planetlab" % ROOT_SIZE, log )
135
136     if vars['NODE_MODEL_OPTIONS'] & ModelOptions.RAWDISK and VSERVERS_SIZE != "-1":
137         utils.sysexec( "lvcreate -L%s -nvservers planetlab" % VSERVERS_SIZE, log )
138         remaining_extents= get_remaining_extents_on_vg( vars, log )
139         utils.sysexec( "lvcreate -l%s -nrawdisk planetlab" % remaining_extents, log )
140     else:
141         # create vservers logical volume with all remaining space
142         # first, we need to get the number of remaining extents we can use
143         remaining_extents= get_remaining_extents_on_vg( vars, log )
144         
145         utils.sysexec( "lvcreate -l%s -nvservers planetlab" % remaining_extents, log )
146
147     # activate volume group (should already be active)
148     #utils.sysexec( TEMP_PATH + "vgchange -ay planetlab", log )
149
150     # make swap
151     utils.sysexec( "mkswap -f %s" % PARTITIONS["swap"], log )
152
153     # check if badhd option has been set
154     option = ''
155     txt = ''
156     if NODE_MODEL_OPTIONS & ModelOptions.BADHD:
157         option = '-c'
158         txt = " with bad block search enabled, which may take a while"
159     
160     # filesystems partitions names and their corresponding
161     # reserved-blocks-percentages
162     filesystems = {"root":5,"vservers":0}
163
164     # ROOT filesystem is always with ext2
165     fs = 'root'
166     rbp = filesystems[fs]
167     devname = PARTITIONS[fs]
168     log.write("formatting %s partition (%s)%s.\n" % (fs,devname,txt))
169     utils.sysexec( "mkfs.ext2 -q %s -m %d -j %s" % (option,rbp,devname), log )
170     # disable time/count based filesystems checks
171     utils.sysexec_noerr( "tune2fs -c -1 -i 0 %s" % devname, log)
172
173     # VSERVER filesystem with btrfs to support snapshoting and stuff
174     fs = 'vservers'
175     rbp = filesystems[fs]
176     devname = PARTITIONS[fs]
177     if vars['virt']=='vs':
178         log.write("formatting %s partition (%s)%s.\n" % (fs,devname,txt))
179         utils.sysexec( "mkfs.ext2 -q %s -m %d -j %s" % (option,rbp,devname), log )
180         # disable time/count based filesystems checks
181         utils.sysexec_noerr( "tune2fs -c -1 -i 0 %s" % devname, log)
182     else:
183         log.write("formatting %s btrfs partition (%s).\n" % (fs,devname))
184         utils.sysexec( "mkfs.btrfs -f %s" % (devname), log )
185         # as of 2013/02 it looks like there's not yet an option to set fsck frequency with btrfs
186
187     # save the list of block devices in the log
188     log.write( "Block devices used (in lvm): %s\n" % repr(used_devices))
189
190     # list of block devices used may be updated
191     vars["INSTALL_BLOCK_DEVICES"]= used_devices
192
193     return 1
194
195
196 import parted
197 def single_partition_device( device, vars, log ):
198     """
199     initialize a disk by removing the old partition tables,
200     and creating a new single partition that fills the disk.
201
202     return 1 if sucessful, 0 otherwise
203     """
204
205     # two forms, depending on which version of pyparted we have
206     # v1 does not have a 'version' method
207     # v2 and above does, but to make it worse, 
208     # parted-3.4 on f14 has parted.version broken and raises SystemError
209     try:
210         parted.version()
211         return single_partition_device_2_x (device, vars, log)
212     except AttributeError:
213         # old parted does not have version at all
214         return single_partition_device_1_x (device, vars, log)
215     except SystemError:
216         # let's assume this is >=2
217         return single_partition_device_2_x (device, vars, log)
218     except:
219         raise
220
221 def single_partition_device_1_x ( device, vars, log):
222     
223     lvm_flag= parted.partition_flag_get_by_name('lvm')
224     
225     try:
226         log.write("Using pyparted 1.x\n")
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         # create a new partition table
234         disk= dev.disk_new_fresh(parted.disk_type_get("msdos"))
235
236         # create one big partition on each block device
237         constraint= dev.constraint_any()
238
239         new_part= disk.partition_new(
240             parted.PARTITION_PRIMARY,
241             parted.file_system_type_get("ext2"),
242             0, 1 )
243
244         # make it an lvm partition
245         new_part.set_flag(lvm_flag,1)
246
247         # actually add the partition to the disk
248         disk.add_partition(new_part, constraint)
249
250         disk.maximize_partition(new_part,constraint)
251
252         disk.commit()
253         del disk
254             
255     except BootManagerException, e:
256         log.write( "BootManagerException while running: %s\n" % str(e) )
257         return 0
258
259     except parted.error, e:
260         log.write( "parted exception while running: %s\n" % str(e) )
261         return 0
262                    
263     return 1
264
265
266
267 def single_partition_device_2_x ( device, vars, log):
268     try:
269         log.write("Using pyparted 2.x\n")
270
271         # Thierry june 2012 -- for disks larger than 2TB
272         # calling this with part_type='msdos' would fail at the maximizePartition stage
273         # create a new partition table
274         def partition_table (device, part_type, fs_type):
275             # wipe the old partition table
276             utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % device, log )
277             # get the device
278             dev= parted.Device(device)
279             disk = parted.freshDisk(dev,part_type)
280             # create one big partition on each block device
281             constraint= parted.constraint.Constraint (device=dev)
282             geometry = parted.geometry.Geometry (device=dev, start=0, end=1)
283             fs = parted.filesystem.FileSystem (type=fs_type,geometry=geometry)
284             new_part= parted.partition.Partition (disk, type=parted.PARTITION_NORMAL,
285                                                   fs=fs, geometry=geometry)
286             # make it an lvm partition
287             new_part.setFlag(parted.PARTITION_LVM)
288             # actually add the partition to the disk
289             disk.addPartition(new_part, constraint)
290             disk.maximizePartition(new_part,constraint)
291             disk.commit()
292             log.write ("Current disk for %s - partition type %s\n%s\n"%(device,part_type,disk))
293             log.write ("Current dev for %s\n%s\n"%(device,dev))
294             del disk
295
296         try:
297             partition_table (device, 'msdos', 'ext2')
298         except:
299             partition_table (device, 'gpt', 'ext2')
300
301     except Exception, e:
302         log.write( "Exception inside single_partition_device_2_x : %s\n" % str(e) )
303         import traceback
304         traceback.print_exc(file=log)
305         return 0
306                    
307     return 1
308
309
310
311 def create_lvm_physical_volume( part_path, vars, log ):
312     """
313     make the specificed partition a lvm physical volume.
314
315     return 1 if successful, 0 otherwise.
316     """
317
318     try:
319         # again, wipe any old data, this time on the partition
320         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % part_path, log )
321         ### patch Thierry Parmentelat, required on some hardware
322         import time
323         time.sleep(1)
324         utils.sysexec( "pvcreate -ffy %s" % part_path, log )
325     except BootManagerException, e:
326         log.write( "create_lvm_physical_volume failed.\n" )
327         return 0
328
329     return 1
330
331
332 def create_raid_partition(partitions, vars, log):
333     """
334     create raid array using specified partitions.  
335     """ 
336     raid_part = None
337     raid_enabled = False
338     node_tags = BootAPI.call_api_function( vars, "GetNodeTags",
339                                         ({'node_id': vars['NODE_ID']},))
340     for node_tag in node_tags:
341         if node_tag['tagname'] == 'raid_enabled' and \
342            node_tag['value'] == '1':
343             raid_enabled = True
344             break
345     if not raid_enabled:
346         return raid_part
347
348     try:
349         log.write( "Software raid enabled.\n" )
350         # wipe everything
351         utils.sysexec_noerr("mdadm --stop /dev/md0", log)
352         time.sleep(1)
353         for part_path in partitions:
354             utils.sysexec_noerr("mdadm --zero-superblock %s " % part_path, log)
355
356         # assume each partiton is on a separate disk
357         num_parts = len(partitions)
358         if num_parts < 2:
359             log.write( "Not enough disks for raid. Found: %s\n" % partitions )
360             raise BootManagerException("Not enough disks for raid. Found: %s\n" % partitions)  
361         if num_parts == 2:
362             lvl = 1
363         else:
364             lvl = 5   
365         
366         # make the array
367         part_list = " ".join(partitions)
368         raid_part = "/dev/md0"
369         cmd = "mdadm --create %(raid_part)s --chunk=128 --level=raid%(lvl)s " % locals() + \
370               "--raid-devices=%(num_parts)s %(part_list)s" % locals()
371         utils.sysexec(cmd, log)        
372
373     except BootManagerException, e:
374         log.write("create_raid_partition failed.\n")
375         raid_part = None
376
377     return raid_part  
378
379
380 def get_partition_path_from_device( device, vars, log ):
381     """
382     given a device, return the path of the first partition on the device
383     """
384
385     # those who wrote the cciss driver just had to make it difficult
386     cciss_test= "/dev/cciss"
387     if device[:len(cciss_test)] == cciss_test:
388         part_path= device + "p1"
389     else:
390         part_path= device + "1"
391
392     return part_path
393
394
395
396 def get_remaining_extents_on_vg( vars, log ):
397     """
398     return the free amount of extents on the planetlab volume group
399     """
400     
401     c_stdout, c_stdin = popen2.popen2("vgdisplay -c planetlab")
402     result= string.strip(c_stdout.readline())
403     c_stdout.close()
404     c_stdin.close()
405     remaining_extents= string.split(result,":")[15]
406     
407     return remaining_extents