ROOT_SIZE is a string not a number
[bootmanager.git] / source / steps / InstallPartitionDisks.py
index 014fcd7..48884e4 100644 (file)
@@ -1,5 +1,5 @@
 #!/usr/bin/python
-
+#
 # Copyright (c) 2003 Intel Corporation
 # All rights reserved.
 #
 import os, sys
 import string
 import popen2
-
+import time
 
 from Exceptions import *
 import utils
 import BootServerRequest
-import compatibility
-
+import BootAPI
 import ModelOptions
 
 def Run( vars, log ):
@@ -28,7 +27,6 @@ def Run( vars, log ):
     TEMP_PATH                somewhere to store what we need to run
     ROOT_SIZE                the size of the root logical volume
     SWAP_SIZE                the size of the swap partition
-    BOOT_CD_VERSION          A tuple of the current bootcd version
     """
 
     log.write( "\n\nStep: Install: partitioning disks.\n" )
@@ -43,7 +41,9 @@ def Run( vars, log ):
         if( len(INSTALL_BLOCK_DEVICES) == 0 ):
             raise ValueError, "INSTALL_BLOCK_DEVICES is empty"
 
-        ROOT_SIZE= vars["ROOT_SIZE"]
+        # use vs_ROOT_SIZE or lxc_ROOT_SIZE as appropriate
+        varname=vars['virt']+"_ROOT_SIZE"
+        ROOT_SIZE= vars[varname]
         if ROOT_SIZE == "" or ROOT_SIZE == 0:
             raise ValueError, "ROOT_SIZE invalid"
 
@@ -51,28 +51,27 @@ def Run( vars, log ):
         if SWAP_SIZE == "" or SWAP_SIZE == 0:
             raise ValueError, "SWAP_SIZE invalid"
 
-        BOOT_CD_VERSION= vars["BOOT_CD_VERSION"]
-        if BOOT_CD_VERSION == "":
-            raise ValueError, "BOOT_CD_VERSION"
-
         NODE_MODEL_OPTIONS= vars["NODE_MODEL_OPTIONS"]
 
         PARTITIONS= vars["PARTITIONS"]
         if PARTITIONS == None:
             raise ValueError, "PARTITIONS"
 
+        if NODE_MODEL_OPTIONS & ModelOptions.RAWDISK:
+            VSERVERS_SIZE= "-1"
+            if "VSERVERS_SIZE" in vars:
+                VSERVERS_SIZE= vars["VSERVERS_SIZE"]
+                if VSERVERS_SIZE == "" or VSERVERS_SIZE == 0:
+                    raise ValueError, "VSERVERS_SIZE"
+
     except KeyError, var:
         raise BootManagerException, "Missing variable in vars: %s\n" % var
     except ValueError, var:
         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
 
-    bs_request= BootServerRequest.BootServerRequest()
+    bs_request= BootServerRequest.BootServerRequest(vars)
 
     
-    # old cds need extra utilities to partition disks and setup lvm
-    if BOOT_CD_VERSION[0] == 2:
-        compatibility.setup_partdisks_2x_cd( vars, log )
-
     # disable swap if its on
     utils.sysexec_noerr( "swapoff %s" % PARTITIONS["swap"], log )
 
@@ -83,18 +82,23 @@ def Run( vars, log ):
     utils.sysexec_noerr( "lvremove -f %s" % PARTITIONS["swap"], log )
     utils.sysexec_noerr( "lvremove -f %s" % PARTITIONS["vservers"], log )
     utils.sysexec_noerr( "vgchange -an", log )
-    utils.sysexec_noerr( "vgremove planetlab", log )
+    utils.sysexec_noerr( "vgremove -f planetlab", log )
 
     log.write( "Running vgscan for devices\n" )
     utils.sysexec_noerr( "vgscan", log )
     
     used_devices= []
 
+    INSTALL_BLOCK_DEVICES.sort()
     for device in INSTALL_BLOCK_DEVICES:
 
         if single_partition_device( device, vars, log ):
-            used_devices.append( device )
-            log.write( "Successfully initialized %s\n" % device )
+            if (len(used_devices) > 0 and
+                (vars['NODE_MODEL_OPTIONS'] & ModelOptions.RAWDISK)):
+                log.write( "Running in raw disk mode, not using %s.\n" % device )
+            else:
+                used_devices.append( device )
+                log.write( "Successfully initialized %s\n" % device )
         else:
             log.write( "Unable to partition %s, not using it.\n" % device )
             continue
@@ -102,15 +106,22 @@ def Run( vars, log ):
     # list of devices to be used with vgcreate
     vg_device_list= ""
 
-    # initialize the physical volumes
+    # get partitions
+    partitions = []
     for device in used_devices:
-
         part_path= get_partition_path_from_device( device, vars, log )
-        
+        partitions.append(part_path)
+   
+    # create raid partition
+    raid_partition = create_raid_partition(partitions, vars, log)
+    if raid_partition != None:
+        partitions = [raid_partition]      
+    log.write("PARTITIONS %s\n" %  str(partitions)) 
+    # initialize the physical volumes
+    for part_path in partitions:
         if not create_lvm_physical_volume( part_path, vars, log ):
             raise BootManagerException, "Could not create lvm physical volume " \
                   "on partition %s" % part_path
-        
         vg_device_list = vg_device_list + " " + part_path
 
     # create an lvm volume group
@@ -119,20 +130,28 @@ def Run( vars, log ):
     # create swap logical volume
     utils.sysexec( "lvcreate -L%s -nswap planetlab" % SWAP_SIZE, log )
 
-    # create root logical volume
-    utils.sysexec( "lvcreate -L%s -nroot planetlab" % ROOT_SIZE, log )
-
-    # create vservers logical volume with all remaining space
-    # first, we need to get the number of remaining extents we can use
-    remaining_extents= get_remaining_extents_on_vg( vars, log )
-    
-    utils.sysexec( "lvcreate -l%s -nvservers planetlab" % remaining_extents, log )
+    # check if we want a separate partition for VMs
+    one_partition = (ROOT_SIZE == "-1")
+    if (one_partition):
+        remaining_extents= get_remaining_extents_on_vg( vars, log )
+        utils.sysexec( "lvcreate -l%s -nroot planetlab" % remaining_extents, log )
+    else:
+        utils.sysexec( "lvcreate -L%s -nroot planetlab" % ROOT_SIZE, log )
+        if vars['NODE_MODEL_OPTIONS'] & ModelOptions.RAWDISK and VSERVERS_SIZE != "-1":
+            utils.sysexec( "lvcreate -L%s -nvservers planetlab" % VSERVERS_SIZE, log )
+            remaining_extents= get_remaining_extents_on_vg( vars, log )
+            utils.sysexec( "lvcreate -l%s -nrawdisk planetlab" % remaining_extents, log )
+        else:
+            # create vservers logical volume with all remaining space
+            # first, we need to get the number of remaining extents we can use
+            remaining_extents= get_remaining_extents_on_vg( vars, log )
+            utils.sysexec( "lvcreate -l%s -nvservers planetlab" % remaining_extents, log )
 
     # activate volume group (should already be active)
     #utils.sysexec( TEMP_PATH + "vgchange -ay planetlab", log )
 
     # make swap
-    utils.sysexec( "mkswap %s" % PARTITIONS["swap"], log )
+    utils.sysexec( "mkswap -f %s" % PARTITIONS["swap"], log )
 
     # check if badhd option has been set
     option = ''
@@ -145,13 +164,34 @@ def Run( vars, log ):
     # reserved-blocks-percentages
     filesystems = {"root":5,"vservers":0}
 
-    # make the file systems
-    for fs in filesystems.keys():
-        # get the reserved blocks percentage
-        rbp = filesystems[fs]
-        devname = PARTITIONS[fs]
+    # ROOT filesystem is always with ext2
+    fs = 'root'
+    rbp = filesystems[fs]
+    devname = PARTITIONS[fs]
+    log.write("formatting %s partition (%s)%s.\n" % (fs,devname,txt))
+    utils.sysexec( "mkfs.ext2 -q %s -m %d -j %s" % (option,rbp,devname), log )
+    # disable time/count based filesystems checks
+    utils.sysexec_noerr( "tune2fs -c -1 -i 0 %s" % devname, log)
+
+    # VSERVER filesystem with btrfs to support snapshoting and stuff
+    fs = 'vservers'
+    rbp = filesystems[fs]
+    devname = PARTITIONS[fs]
+    if vars['virt']=='vs':
         log.write("formatting %s partition (%s)%s.\n" % (fs,devname,txt))
         utils.sysexec( "mkfs.ext2 -q %s -m %d -j %s" % (option,rbp,devname), log )
+        # disable time/count based filesystems checks
+        utils.sysexec_noerr( "tune2fs -c -1 -i 0 %s" % devname, log)
+    else:
+        log.write("formatting %s btrfs partition (%s).\n" % (fs,devname))
+        # early BootCD's seem to come with a version of mkfs.btrfs that does not support -f
+        # let's check for that before invoking it
+        mkfs="mkfs.btrfs"
+        if os.system("mkfs.btrfs --help 2>&1 | grep force")==0:
+            mkfs+=" -f"
+        mkfs+=" %s"%devname
+        utils.sysexec( mkfs, log )
+        # as of 2013/02 it looks like there's not yet an option to set fsck frequency with btrfs
 
     # save the list of block devices in the log
     log.write( "Block devices used (in lvm): %s\n" % repr(used_devices))
@@ -162,7 +202,7 @@ def Run( vars, log ):
     return 1
 
 
-
+import parted
 def single_partition_device( device, vars, log ):
     """
     initialize a disk by removing the old partition tables,
@@ -171,78 +211,55 @@ def single_partition_device( device, vars, log ):
     return 1 if sucessful, 0 otherwise
     """
 
-    BOOT_CD_VERSION= vars["BOOT_CD_VERSION"]
-    if BOOT_CD_VERSION[0] == 2:
-        compatibility.setup_partdisks_2x_cd( vars, log )
-
-    import parted
+    # two forms, depending on which version of pyparted we have
+    # v1 does not have a 'version' method
+    # v2 and above does, but to make it worse, 
+    # parted-3.4 on f14 has parted.version broken and raises SystemError
+    try:
+        parted.version()
+        return single_partition_device_2_x (device, vars, log)
+    except AttributeError:
+        # old parted does not have version at all
+        return single_partition_device_1_x (device, vars, log)
+    except SystemError:
+        # let's assume this is >=2
+        return single_partition_device_2_x (device, vars, log)
+    except:
+        raise
+
+def single_partition_device_1_x ( device, vars, log):
     
     lvm_flag= parted.partition_flag_get_by_name('lvm')
     
     try:
+        log.write("Using pyparted 1.x\n")
         # wipe the old partition table
         utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % device, log )
 
         # get the device
         dev= parted.PedDevice.get(device)
 
-        # 2.x cds have different libparted that 3.x cds, and they have
-        # different interfaces
-        if BOOT_CD_VERSION[0] >= 3:
-
-            # create a new partition table
-            disk= dev.disk_new_fresh(parted.disk_type_get("msdos"))
-
-            # create one big partition on each block device
-            constraint= dev.constraint_any()
-
-            new_part= disk.partition_new(
-                parted.PARTITION_PRIMARY,
-                parted.file_system_type_get("ext2"),
-                0, 1 )
+        # create a new partition table
+        disk= dev.disk_new_fresh(parted.disk_type_get("msdos"))
 
-            # make it an lvm partition
-            new_part.set_flag(lvm_flag,1)
-
-            # actually add the partition to the disk
-            disk.add_partition(new_part, constraint)
-
-            disk.maximize_partition(new_part,constraint)
-
-            disk.commit()
-            del disk
-        else:
-            # create a new partition table
-            dev.disk_create(parted.disk_type_get("msdos"))
+        # create one big partition on each block device
+        constraint= dev.constraint_any()
 
-            # get the disk
-            disk= parted.PedDisk.open(dev)
+        new_part= disk.partition_new(
+            parted.PARTITION_PRIMARY,
+            parted.file_system_type_get("ext2"),
+            0, 1 )
 
-                # create one big partition on each block device
-            part= disk.next_partition()
-            while part:
-                if part.type == parted.PARTITION_FREESPACE:
-                    new_part= disk.partition_new(
-                        parted.PARTITION_PRIMARY,
-                        parted.file_system_type_get("ext2"),
-                        part.geom.start,
-                        part.geom.end )
+        # make it an lvm partition
+        new_part.set_flag(lvm_flag,1)
 
-                    constraint = disk.constraint_any()
+        # actually add the partition to the disk
+        disk.add_partition(new_part, constraint)
 
-                    # make it an lvm partition
-                    new_part.set_flag(lvm_flag,1)
+        disk.maximize_partition(new_part,constraint)
 
-                    # actually add the partition to the disk
-                    disk.add_partition(new_part, constraint)
-
-                    break
-
-                part= disk.next_partition(part)
-
-            disk.write()
-            disk.close()
-            del disk
+        disk.commit()
+        del disk
             
     except BootManagerException, e:
         log.write( "BootManagerException while running: %s\n" % str(e) )
@@ -256,6 +273,50 @@ def single_partition_device( device, vars, log ):
 
 
 
+def single_partition_device_2_x ( device, vars, log):
+    try:
+        log.write("Using pyparted 2.x\n")
+
+        # Thierry june 2012 -- for disks larger than 2TB
+        # calling this with part_type='msdos' would fail at the maximizePartition stage
+        # create a new partition table
+        def partition_table (device, part_type, fs_type):
+            # wipe the old partition table
+            utils.sysexec( "dd if=/dev/zero of=%s bs=512 count=1" % device, log )
+            # get the device
+            dev= parted.Device(device)
+            disk = parted.freshDisk(dev,part_type)
+            # create one big partition on each block device
+            constraint= parted.constraint.Constraint (device=dev)
+            geometry = parted.geometry.Geometry (device=dev, start=0, end=1)
+            fs = parted.filesystem.FileSystem (type=fs_type,geometry=geometry)
+            new_part= parted.partition.Partition (disk, type=parted.PARTITION_NORMAL,
+                                                  fs=fs, geometry=geometry)
+            # make it an lvm partition
+            new_part.setFlag(parted.PARTITION_LVM)
+            # actually add the partition to the disk
+            disk.addPartition(new_part, constraint)
+            disk.maximizePartition(new_part,constraint)
+            disk.commit()
+            log.write ("Current disk for %s - partition type %s\n%s\n"%(device,part_type,disk))
+            log.write ("Current dev for %s\n%s\n"%(device,dev))
+            del disk
+
+        try:
+            partition_table (device, 'msdos', 'ext2')
+        except:
+            partition_table (device, 'gpt', 'ext2')
+
+    except Exception, e:
+        log.write( "Exception inside single_partition_device_2_x : %s\n" % str(e) )
+        import traceback
+        traceback.print_exc(file=log)
+        return 0
+                   
+    return 1
+
+
+
 def create_lvm_physical_volume( part_path, vars, log ):
     """
     make the specificed partition a lvm physical volume.
@@ -277,30 +338,65 @@ def create_lvm_physical_volume( part_path, vars, log ):
     return 1
 
 
+def create_raid_partition(partitions, vars, log):
+    """
+    create raid array using specified partitions.  
+    """ 
+    raid_part = None
+    raid_enabled = False
+    node_tags = BootAPI.call_api_function( vars, "GetNodeTags",
+                                        ({'node_id': vars['NODE_ID']},))
+    for node_tag in node_tags:
+        if node_tag['tagname'] == 'raid_enabled' and \
+           node_tag['value'] == '1':
+            raid_enabled = True
+            break
+    if not raid_enabled:
+        return raid_part
+
+    try:
+        log.write( "Software raid enabled.\n" )
+        # wipe everything
+        utils.sysexec_noerr("mdadm --stop /dev/md0", log)
+        time.sleep(1)
+        for part_path in partitions:
+            utils.sysexec_noerr("mdadm --zero-superblock %s " % part_path, log)
+
+        # assume each partiton is on a separate disk
+        num_parts = len(partitions)
+        if num_parts < 2:
+            log.write( "Not enough disks for raid. Found: %s\n" % partitions )
+            raise BootManagerException("Not enough disks for raid. Found: %s\n" % partitions)  
+        if num_parts == 2:
+            lvl = 1
+        else:
+            lvl = 5   
+        
+        # make the array
+        part_list = " ".join(partitions)
+        raid_part = "/dev/md0"
+        cmd = "mdadm --create %(raid_part)s --chunk=128 --level=raid%(lvl)s " % locals() + \
+              "--raid-devices=%(num_parts)s %(part_list)s" % locals()
+        utils.sysexec(cmd, log)        
+
+    except BootManagerException, e:
+        log.write("create_raid_partition failed.\n")
+        raid_part = None
+
+    return raid_part  
+
 
 def get_partition_path_from_device( device, vars, log ):
     """
     given a device, return the path of the first partition on the device
     """
 
-    BOOT_CD_VERSION= vars["BOOT_CD_VERSION"]
-        
     # those who wrote the cciss driver just had to make it difficult
-    if BOOT_CD_VERSION[0] >= 3:
-        cciss_test= "/dev/cciss"
-        if device[:len(cciss_test)] == cciss_test:
-            part_path= device + "p1"
-        else:
-            part_path= device + "1"
+    cciss_test= "/dev/cciss"
+    if device[:len(cciss_test)] == cciss_test:
+        part_path= device + "p1"
     else:
-        # if device ends in /disc, we need to make it end in
-        # /part1 to indicate the first partition (for devfs based 2.x cds)
-        dev_parts= string.split(device,"/")
-        if dev_parts[-1] == "disc":
-            dev_parts[-1]= "part1"
-            part_path= string.join(dev_parts,"/")
-        else:
-            part_path= device + "1"
+        part_path= device + "1"
 
     return part_path