f36e2e9154aa5a28561421922304232bebd8801b
[bootmanager.git] / source / steps / InstallPartitionDisks.py
1 # Copyright (c) 2003 Intel Corporation
2 # All rights reserved.
3
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
6 # met:
7
8 #     * Redistributions of source code must retain the above copyright
9 #       notice, this list of conditions and the following disclaimer.
10
11 #     * Redistributions in binary form must reproduce the above
12 #       copyright notice, this list of conditions and the following
13 #       disclaimer in the documentation and/or other materials provided
14 #       with the distribution.
15
16 #     * Neither the name of the Intel Corporation nor the names of its
17 #       contributors may be used to endorse or promote products derived
18 #       from this software without specific prior written permission.
19
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
24 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32 # EXPORT LAWS: THIS LICENSE ADDS NO RESTRICTIONS TO THE EXPORT LAWS OF
33 # YOUR JURISDICTION. It is licensee's responsibility to comply with any
34 # export regulations applicable in licensee's jurisdiction. Under
35 # CURRENT (May 2000) U.S. export regulations this software is eligible
36 # for export from the U.S. and can be downloaded by or otherwise
37 # exported or reexported worldwide EXCEPT to U.S. embargoed destinations
38 # which include Cuba, Iraq, Libya, North Korea, Iran, Syria, Sudan,
39 # Afghanistan and any other country to which the U.S. has embargoed
40 # goods and services.
41
42
43 import os, sys
44 import string
45 import popen2
46
47
48 from Exceptions import *
49 import utils
50 import BootServerRequest
51 import compatibility
52
53 import ModelOptions
54
55 def Run( vars, log ):
56     """
57     Setup the block devices for install, partition them w/ LVM
58     
59     Expect the following variables from the store:
60     INSTALL_BLOCK_DEVICES    list of block devices to install onto
61     TEMP_PATH                somewhere to store what we need to run
62     ROOT_SIZE                the size of the root logical volume
63     SWAP_SIZE                the size of the swap partition
64     BOOT_CD_VERSION          A tuple of the current bootcd version
65     
66     Sets the following variables:
67     PARTITIONS               diction of generic part. types (root/swap)
68                              and their associated devices.
69                              Current keys/values:
70                                  root    /dev/planetlab/root
71                                  swap    /dev/planetlab/swap
72     
73     """
74
75     log.write( "\n\nStep: Install: partitioning disks.\n" )
76         
77     # make sure we have the variables we need
78     try:
79         TEMP_PATH= vars["TEMP_PATH"]
80         if TEMP_PATH == "":
81             raise ValueError, "TEMP_PATH"
82
83         INSTALL_BLOCK_DEVICES= vars["INSTALL_BLOCK_DEVICES"]
84         if( len(INSTALL_BLOCK_DEVICES) == 0 ):
85             raise ValueError, "INSTALL_BLOCK_DEVICES is empty"
86
87         ROOT_SIZE= vars["ROOT_SIZE"]
88         if ROOT_SIZE == "" or ROOT_SIZE == 0:
89             raise ValueError, "ROOT_SIZE invalid"
90
91         SWAP_SIZE= vars["SWAP_SIZE"]
92         if SWAP_SIZE == "" or SWAP_SIZE == 0:
93             raise ValueError, "SWAP_SIZE invalid"
94
95         BOOT_CD_VERSION= vars["BOOT_CD_VERSION"]
96         if BOOT_CD_VERSION == "":
97             raise ValueError, "BOOT_CD_VERSION"
98
99         NODE_MODEL_OPTIONS= vars["NODE_MODEL_OPTIONS"]
100
101     except KeyError, var:
102         raise BootManagerException, "Missing variable in vars: %s\n" % var
103     except ValueError, var:
104         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
105
106     bs_request= BootServerRequest.BootServerRequest()
107
108     
109     # old cds need extra utilities to partition disks and setup lvm
110     if BOOT_CD_VERSION[0] == 2:
111         compatibility.setup_partdisks_2x_cd( vars, log )
112
113     import parted
114         
115     # define the basic partition paths
116     PARTITIONS= {}
117     PARTITIONS["root"]= "/dev/planetlab/root"
118     PARTITIONS["swap"]= "/dev/planetlab/swap"
119     PARTITIONS["vservers"]= "/dev/planetlab/vservers"
120     # Linux 2.6 mounts LVM with device mapper
121     PARTITIONS["mapper-root"]= "/dev/mapper/planetlab-root"
122     PARTITIONS["mapper-swap"]= "/dev/mapper/planetlab-swap"
123     PARTITIONS["mapper-vservers"]= "/dev/mapper/planetlab-vservers"
124     vars["PARTITIONS"]= PARTITIONS
125
126     
127     # disable swap if its on
128     utils.sysexec_noerr( "swapoff %s" % PARTITIONS["swap"], log )
129
130     # shutdown and remove any lvm groups/volumes
131     utils.sysexec_noerr( "vgscan", log )
132     utils.sysexec_noerr( "vgchange -ay", log )        
133     utils.sysexec_noerr( "lvremove -f /dev/planetlab/root", log )
134     utils.sysexec_noerr( "lvremove -f /dev/planetlab/swap", log )
135     utils.sysexec_noerr( "lvremove -f /dev/planetlab/vservers", log )
136     utils.sysexec_noerr( "vgchange -an", log )
137     utils.sysexec_noerr( "vgremove planetlab", log )
138
139     log.write( "Running vgscan for devices\n" )
140     utils.sysexec_noerr( "vgscan", log )
141     
142     used_devices= []
143
144     for device in INSTALL_BLOCK_DEVICES:
145
146         if single_partition_device( device, vars, log ):
147             used_devices.append( device )
148             log.write( "Successfully initialized %s\n" % device )
149         else:
150             log.write( "Unable to partition %s, not using it.\n" % device )
151             continue
152
153     # list of devices to be used with vgcreate
154     vg_device_list= ""
155
156     # initialize the physical volumes
157     for device in used_devices:
158
159         part_path= get_partition_path_from_device( device, vars, log )
160         
161         if not create_lvm_physical_volume( part_path, vars, log ):
162             raise BootManagerException, "Could not create lvm physical volume " \
163                   "on partition %s" % part_path
164         
165         vg_device_list = vg_device_list + " " + part_path
166
167     # create an lvm volume group
168     utils.sysexec( "vgcreate -s32M planetlab %s" % vg_device_list, log)
169
170     # create swap logical volume
171     utils.sysexec( "lvcreate -L%s -nswap planetlab" % SWAP_SIZE, log )
172
173     # create root logical volume
174     utils.sysexec( "lvcreate -L%s -nroot planetlab" % ROOT_SIZE, log )
175
176     # create vservers logical volume with all remaining space
177     # first, we need to get the number of remaining extents we can use
178     remaining_extents= get_remaining_extents_on_vg( vars, log )
179     
180     utils.sysexec( "lvcreate -l%s -nvservers planetlab" % remaining_extents, log )
181
182     # activate volume group (should already be active)
183     #utils.sysexec( TEMP_PATH + "vgchange -ay planetlab", log )
184
185     # make swap
186     utils.sysexec( "mkswap %s" % PARTITIONS["swap"], log )
187
188     # check if badhd option has been set
189     option = ''
190     txt = ''
191     if NODE_MODEL_OPTIONS & ModelOptions.BADHD:
192         option = '-c'
193         txt = " with bad block search enabled, which may take a while"
194     
195     # filesystems partitions names and their corresponding
196     # reserved-blocks-percentages
197     filesystems = {"root":5,"vservers":0}
198
199     # make the file systems
200     for fs in filesystems.keys():
201         # get the reserved blocks percentage
202         rbp = filesystems[fs]
203         devname = PARTITIONS[fs]
204         log.write("formatting %s partition (%s)%s.\n" % (fs,devname,txt))
205         utils.sysexec( "mkfs.ext2 -q %s -m %d -j %s" % (option,rbp,devname), log )
206
207     # save the list of block devices in the log
208     log.write( "Block devices used (in lvm):\n" )
209     log.write( repr(used_devices) + "\n" )
210     log.write( "End of block devices used (in lvm).\n" )
211
212     # list of block devices used may be updated
213     vars["INSTALL_BLOCK_DEVICES"]= used_devices
214
215     return 1
216
217
218
219 def single_partition_device( device, vars, log ):
220     """
221     initialize a disk by removing the old partition tables,
222     and creating a new single partition that fills the disk.
223
224     return 1 if sucessful, 0 otherwise
225     """
226
227     BOOT_CD_VERSION= vars["BOOT_CD_VERSION"]
228     if BOOT_CD_VERSION[0] == 2:
229         compatibility.setup_partdisks_2x_cd( vars, log )
230
231     import parted
232     
233     lvm_flag= parted.partition_flag_get_by_name('lvm')
234     
235     try:
236         # wipe the old partition table
237         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % device, log )
238
239         # get the device
240         dev= parted.PedDevice.get(device)
241
242         # 2.x cds have different libparted that 3.x cds, and they have
243         # different interfaces
244         if BOOT_CD_VERSION[0] == 3:
245
246             # create a new partition table
247             disk= dev.disk_new_fresh(parted.disk_type_get("msdos"))
248
249             # create one big partition on each block device
250             constraint= dev.constraint_any()
251
252             new_part= disk.partition_new(
253                 parted.PARTITION_PRIMARY,
254                 parted.file_system_type_get("ext2"),
255                 0, 1 )
256
257             # make it an lvm partition
258             new_part.set_flag(lvm_flag,1)
259
260             # actually add the partition to the disk
261             disk.add_partition(new_part, constraint)
262
263             disk.maximize_partition(new_part,constraint)
264
265             disk.commit()
266             del disk
267         else:
268             # create a new partition table
269             dev.disk_create(parted.disk_type_get("msdos"))
270
271             # get the disk
272             disk= parted.PedDisk.open(dev)
273
274                 # create one big partition on each block device
275             part= disk.next_partition()
276             while part:
277                 if part.type == parted.PARTITION_FREESPACE:
278                     new_part= disk.partition_new(
279                         parted.PARTITION_PRIMARY,
280                         parted.file_system_type_get("ext2"),
281                         part.geom.start,
282                         part.geom.end )
283
284                     constraint = disk.constraint_any()
285
286                     # make it an lvm partition
287                     new_part.set_flag(lvm_flag,1)
288
289                     # actually add the partition to the disk
290                     disk.add_partition(new_part, constraint)
291
292                     break
293
294                 part= disk.next_partition(part)
295
296             disk.write()
297             disk.close()
298             del disk
299             
300     except BootManagerException, e:
301         log.write( "BootManagerException while running: %s\n" % str(e) )
302         return 0
303
304     except parted.error, e:
305         log.write( "parted exception while running: %s\n" % str(e) )
306         return 0
307                    
308     return 1
309
310
311
312 def create_lvm_physical_volume( part_path, vars, log ):
313     """
314     make the specificed partition a lvm physical volume.
315
316     return 1 if successful, 0 otherwise.
317     """
318
319     try:
320         # again, wipe any old data, this time on the partition
321         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % part_path, log )
322         ### patch Thierry Parmentelat, required on some hardware
323         import time
324         time.sleep(1)
325         utils.sysexec( "pvcreate -ffy %s" % part_path, log )
326     except BootManagerException, e:
327         log.write( "create_lvm_physical_volume failed.\n" )
328         return 0
329
330     return 1
331
332
333
334 def get_partition_path_from_device( device, vars, log ):
335     """
336     given a device, return the path of the first partition on the device
337     """
338
339     BOOT_CD_VERSION= vars["BOOT_CD_VERSION"]
340         
341     # those who wrote the cciss driver just had to make it difficult
342     if BOOT_CD_VERSION[0] == 3:
343         cciss_test= "/dev/cciss"
344         if device[:len(cciss_test)] == cciss_test:
345             part_path= device + "p1"
346         else:
347             part_path= device + "1"
348     else:
349         # since device ends in /disc, we need to make it end in
350         # /part1 to indicate the first partition (for devfs based 2.x cds)
351         dev_parts= string.split(device,"/")
352         dev_parts[len(dev_parts)-1]= "part1"
353         part_path= string.join(dev_parts,"/")
354
355     return part_path
356
357
358
359 def get_remaining_extents_on_vg( vars, log ):
360     """
361     return the free amount of extents on the planetlab volume group
362     """
363     
364     c_stdout, c_stdin = popen2.popen2("vgdisplay -c planetlab")
365     result= string.strip(c_stdout.readline())
366     c_stdout.close()
367     c_stdin.close()
368     remaining_extents= string.split(result,":")[15]
369     
370     return remaining_extents