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