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