Exemple #1
0
def do_image_hd(outf, hd, fslabel, target, grub_version, grub_fw_type=None):

    # pylint: disable=too-many-arguments
    # pylint: disable=too-many-locals
    # pylint: disable=too-many-branches

    sector_size = 512
    s = size_to_int(hd.text("size"))
    size_in_sectors = s / sector_size

    imagename = os.path.join(target, hd.text("name"))
    outf.do('rm -f "%s"' % imagename, allow_fail=True)
    f = open(imagename, "wb")
    f.truncate(size_in_sectors * sector_size)
    f.close()

    imag = parted.Device(imagename)
    if hd.tag == "gpthd":
        disk = parted.freshDisk(imag, "gpt")
    else:
        disk = parted.freshDisk(imag, "msdos")

    if grub_version == 199:
        grub = grubinstaller199(outf)
    elif grub_version == 202 and grub_fw_type == "efi":
        grub = grubinstaller202(outf, "efi")
    elif grub_version == 202 and grub_fw_type == "hybrid":
        grub = grubinstaller202(outf, "hybrid")
    elif grub_version == 202:
        grub = grubinstaller202(outf)
    else:
        grub = grubinstaller_base(outf)

    current_sector = 2048
    for part in hd:

        if part.tag == "partition":
            ppart = create_partition(disk, part, parted.PARTITION_NORMAL,
                                     fslabel, size_in_sectors, current_sector)
            if part.text("label") in fslabel:
                create_label(outf, disk, part, ppart, fslabel, target, grub)
        elif part.tag == "extended":
            ppart = create_partition(disk, part, parted.PARTITION_EXTENDED,
                                     fslabel, size_in_sectors, current_sector)
            create_logical_partitions(outf, disk, part, ppart, fslabel, target,
                                      grub)
        else:
            continue

        current_sector += ppart.getLength()

    disk.commit()

    if hd.has("grub-install") and grub_version:
        grub.install(target)

    return hd.text("name")
Exemple #2
0
def create_partitions(device_path, partitions):
    try:
        device = parted.getDevice(device_path)
        disk = parted.Disk(device)

        # prompt user before wiping out disk...
        disk.deleteAllPartitions()
        disk.commitToDevice()
        disk.commitToOS()
    except parted.DiskLabelException:
        print "disk is not initialized, ignoring"

    # create volatile store for new partition information
    # create fat, ext4 and swap partition
    disk = parted.freshDisk(device, _ped.disk_type_get("msdos"))

    constraint = parted.Constraint(device=device)
    max_length_sectors = disk.device.getLength()
    fat32_size = mb_to_sector(disk, partitions[0]['length'])
    swap_size = mb_to_sector(disk, partitions[2]['length'])
    ext4_size = max_length_sectors - (fat32_size+swap_size)
    fat32_geom = parted.Geometry(device=device, start=0, length=fat32_size)
    ext4_geom = parted.Geometry(device=device, start=fat32_size, length=ext4_size)
    swap_geom = parted.Geometry(device=device, start=ext4_size+fat32_size, length=swap_size)
    for part_type, geom in [("fat32", fat32_geom), ("ext4", ext4_geom), ("linux-swap", swap_geom)]:
        print "creating %s with geom: %s" % (part_type, geom)
        partition = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL, geometry=geom)
        disk.addPartition(partition,constraint=constraint)
        part_type_ped = _ped.file_system_type_get(part_type)
        partition.getPedPartition().set_system(part_type_ped)
    disk.commitToDevice()
    disk.commitToOS()
Exemple #3
0
    def maybeCreateLabel(self):
        """Set up an msdos label."""

        self.partedDevice = parted.getDevice(self.device)
        try:
            self.partedDisk = parted.newDisk(self.partedDevice)
            if self.partedDisk.type == 'msdos':
                self.log.info("disk %s is already msdos", self.device)
                return 0
            self.log.warn("disk %s has wrong label %s",
                          self.device, self.partedDisk.type)
        except (DiskException, PartedException) as ex:
            self.log.error("cannot get partition table from %s: %s",
                           self.device, str(ex))
        except Exception:
            self.log.exception("cannot get partition table from %s",
                               self.device)

        self.log.info("clobbering disk label on %s", self.device)
        self.partedDevice.clobber()

        self.log.info("creating msdos label on %s", self.device)
        self.partedDisk = parted.freshDisk(self.partedDevice, 'msdos')

        return 0
Exemple #4
0
def device_probe_all(mia, operid, dummy):
    def get_device_list():
        hd_list = filter(lambda d: d.type != parted.DEVICE_DM and \
                         d.readOnly != True, # CD-ROM will be read only. 
                         parted.getAllDevices())

        return hd_list

    mia.set_step(operid, 0, -1)
    result = []
    # The following commented code is implemented by kudzu.
    devlist = get_device_list()
    if devlist:
        for dev in devlist:
            newdisklabel = None
            try:
                disk = parted.Disk(dev)
            except _ped.DiskLabelException:
                # For the disk without any disk label, create it.
                # disk label is disk partition table format
                dltype = parted.diskType['msdos']
                disk = parted.freshDisk(device=dev, ty=dltype)
                #newdisklabel = 'y'
                #disk = dev.disk_new_fresh(parted.disk_type_get('msdos'))
            # Model might contain GB2312, it must be convert to Unicode.
            model = iconv.iconv('gb2312', 'utf8', dev.model).encode('utf8')
            result.append((dev.path, dev.length, model))
            CF.S.all_harddisks[dev.path] = (dev, disk, newdisklabel)
    dolog('operations.parted.device_probe_all: %s\n' % str(result))
    return result
Exemple #5
0
    def creeTablePartition(self):
        """Créer une nouvelle table d
		Efface signaturev disque   wipefs --all /dev/sdb2
		/dev/sdb2 : 2 octets ont été effacés à l'index 0x00000438 (ext4) : 53 ef
		Cree Systeme fichiers fat

		Créé le systeme de fichiers  mkfs.fat -F32 -v -I -n "BOOT" /dev/sdb1
		mkfs.fat 3.0.28 (2015-05-16)
		/dev/sdb1 has 255 heads and 63 sectors per track,
		hidden sectors 0x0800;
		logical sector size is 512,
		using 0xf8 media descriptor, with 2048000 sectors;
		drive number 0x80;
		filesystem has 2 32-bit FATs and 8 sectors per cluster.
		FAT size is 1997 sectors, and provides 255496 clusters.
		There are 32 reserved sectors.
		Volume ID is 2107cb40, volume label BOOT       .
		Cree Systeme fichiers ext4
		e partition sur un disque"""
        dev = parted.Device(self.disque)
        table = parted.freshDisk(dev, 'gpt')  #gpt msdos
        if not table.commit():  #Si c'est Vrai on le commit
            sys.exit()
        else:
            print("\nNouvelle table de partition " + self.disque)

        time.sleep(3)
Exemple #6
0
 def partition_table(device, part_type, fs_type):
     # wipe the old partition table
     utils.sysexec(
         "dd if=/dev/zero of={} bs=512 count=1".format(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 {} - partition type {}\n{}\n".format(
         device, part_type, disk))
     log.write("Current dev for {}\n{}\n".format(device, dev))
     del disk
    def partition(self):
        """
        Create a partition table on the block device.

        The newly created partition will have the following characteristics:
            - a primary partition using 100% of the device capacity
            - optimal alignment given the disk topology information
            - a MS-DOS disk label for simple BIOS booting on PC-type hardware
            - marked as bootable
        """
        self.logger.info('creating primary partition')
        device = parted.getDevice(self.path)
        self.logger.debug('created %s', device)
        disk = parted.freshDisk(device, 'msdos')
        self.logger.debug('created %s', disk)
        geometry = parted.Geometry(device=device, start=1,
                                   length=device.getLength() - 1)
        self.logger.debug('created %s', geometry)
        filesystem = parted.FileSystem(type='ext3', geometry=geometry)
        self.logger.debug('created %s', filesystem)
        partition = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL,
                                     fs=filesystem, geometry=geometry)
        self.logger.debug('created %s', partition)
        disk.addPartition(partition=partition,
                          constraint=device.optimalAlignedConstraint)
        partition.setFlag(parted.PARTITION_BOOT)
        disk.commit()
Exemple #8
0
def device_probe_all(mia, operid, dummy):

    def get_device_list():
        hd_list = filter(lambda d: d.type != parted.DEVICE_DM, parted.getAllDevices())
        
        return hd_list

    mia.set_step(operid, 0, -1)
    result = []
    # The following commented code is implemented by kudzu.
    devlist = get_device_list()
    if devlist:
        for dev in devlist:
            newdisklabel = None
            try:
                disk = parted.Disk(dev)
            except _ped.DiskLabelException:
                # For the disk without any disk label, create it.
                # disk label is disk partition table format
                dltype = parted.diskType['msdos']
                disk = parted.freshDisk(device=dev, ty=dltype)
                #newdisklabel = 'y'
                #disk = dev.disk_new_fresh(parted.disk_type_get('msdos'))
            # Model might contain GB2312, it must be convert to Unicode.
            model = iconv.iconv('gb2312', 'utf8', dev.model).encode('utf8')
            result.append((dev.path, dev.length, model))
            CONF.RUN.g_all_harddisks[dev.path] = (dev, disk, newdisklabel)
    #dolog('operations.parted.device_probe_all: %s\n' % str(result))
    return  result
Exemple #9
0
    def partition_primary_disk(self):
        """
        Create a partition table on the block device for the installer
        image (rescue disk).
        """
        self.logger.info('Creating partitions')
        device = parted.getDevice(self.path)
        self.logger.debug('created %s', device)
        disk = parted.freshDisk(device, 'msdos')
        self.logger.debug('created %s', disk)

        # create the rescue disk partition - the size has been chosen to d-i's liking, so
        # it doesn't attempt to truncate or override the partition
        partition_size = round(2099249152 / (device.sectorSize))  # 2 GB
        self._new_partition(
            device, disk, 2048, partition_size, True
        )  # 2048 padding is required to make d-i not override the rescue partition

        disk.commit()

        # wait for device nodes
        check_call(['udevadm', 'settle'])

        # create file system and labels
        check_call(['mkfs.ext4', '-F', self.path + '-part1'])
        check_call(['e2label', self.path + '-part1', 'rescue'])
    def putGeom(self, limPartList):
        #Write the disk geometry information
        #Template code @ https://bitbucket.org/rbistolfi/vinstall/wiki/pyparted
        disk = parted.freshDisk(self.dev, "msdos")
        for lpar in limPartList:
            if lpar.parttype != 'artificial':
                #TODO: should check that the geometry is within the disk
                g = parted.Geometry(device=self.dev, start=lpar.start, end=lpar.end)
                fs = parted.FileSystem(type=lpar.fstype, geometry=g)

                #TODO: eventually we should be able to handle logical/extended
                #partitions - right now it's primary only
                ptype = parted.PARTITION_NORMAL
                if lpar.parttype != 'primary':
                    raise errors.partError(lpar.parttype)

                p = parted.Partition(disk=disk, fs=fs, type=ptype, geometry=g)
                c = parted.Constraint(exactGeom = g)
                disk.addPartition(partition=p, constraint=c)
                setFlags(p, lpar.flags)
        disk.commit()

        #refresh the OS's view of the disk
        support.partprobe(self.node)

        #put file systems onto the new partitions
        for lpar in limPartList:
            if lpar.parttype != 'artificial':
                support.mkfs(lpar.composeNode(self.node), lpar.fstype)
Exemple #11
0
 def _makeVDisk(self):
     self.parts = [('p1', 'junk')]
     self.image_file = self.path
     os_call(['dd', 'bs=4096', 'count=5000', 'if=/dev/zero',
             'of=' + self.image_file])
     with subprocess.Popen(['sudo', 'losetup', '-f'],
                           stdout=subprocess.PIPE,
                           universal_newlines=True) as lo_list:
         out = lo_list.stdout.read().split('\n')[:-1]
         if len(out) > 0:
             self.path = out[0]
         else:
             self.path = '/dev/loop0'
         self.part_prefix = 'p'
     os_call(['sudo', 'losetup', '-P', self.path, self.image_file])
     self.device = parted.getDevice(self.path)
     disk = parted.freshDisk(self.device, 'msdos')
     geom = parted.Geometry(self.device, start=1,
                            length=self.device.getLength() - 1)
     fs = parted.FileSystem('fat16', geom)
     new_part = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL,
                                 fs=fs, geometry=geom)
     disk.addPartition(partition=new_part,
                       constraint=self.device.getConstraint())
     new_part.setFlag(parted.PARTITION_BOOT)
     try:
         disk.commit()
     except:
         pass
     self.format(mk_vfat(), 0)
     self.parts = self.partitions()
     self.__undoLo = ['sudo', 'losetup', '-d', self.path]
    def maybeCreateLabel(self):
        """Set up an msdos label."""

        self.partedDevice = parted.getDevice(self.device)
        try:
            self.partedDisk = parted.newDisk(self.partedDevice)
            if self.partedDisk.type == 'msdos':
                self.log.info("disk %s is already msdos", self.device)
                return 0
            self.log.warn("disk %s has wrong label %s",
                          self.device, self.partedDisk.type)
        except (DiskException, PartedException) as ex:
            self.log.error("cannot get partition table from %s: %s",
                           self.device, str(ex))
        except Exception:
            self.log.exception("cannot get partition table from %s",
                               self.device)

        self.log.info("clobbering disk label on %s", self.device)
        self.partedDevice.clobber()

        self.log.info("creating msdos label on %s", self.device)
        self.partedDisk = parted.freshDisk(self.partedDevice, 'msdos')

        return 0
Exemple #13
0
    def best_disklabel_type(self, device):
        """The best disklabel type for the specified device."""
        if flags.testing:
            return self.default_disklabel_type

        parted_device = parted.Device(path=device.path)

        # if there's a required type for this device type, use that
        label_type = self.required_disklabel_type(parted_device.type)
        log.debug("required disklabel type for %s (%s) is %s",
                  device.name, parted_device.type, label_type)
        if not label_type:
            # otherwise, use the first supported type for this platform
            # that is large enough to address the whole device
            label_type = self.default_disklabel_type
            log.debug("default disklabel type for %s is %s", device.name,
                      label_type)
            for lt in self.disklabel_types:
                l = parted.freshDisk(device=parted_device, ty=lt)
                if l.maxPartitionStartSector > parted_device.length:
                    label_type = lt
                    log.debug("selecting %s disklabel for %s based on size",
                              label_type, device.name)
                    break

        return label_type
Exemple #14
0
    def partition(self):
        """
        Create a partition table on the block device.

        The newly created partition will have the following characteristics:
            - a primary partition using 100% of the device capacity
            - optimal alignment given the disk topology information
            - a MS-DOS disk label for simple BIOS booting on PC-type hardware
            - marked as bootable
        """
        self.logger.info('creating primary partition')
        device = parted.getDevice(self.path)
        self.logger.debug('created %s', device)
        disk = parted.freshDisk(device, 'msdos')
        self.logger.debug('created %s', disk)
        geometry = parted.Geometry(device=device,
                                   start=1,
                                   length=device.getLength() - 1)
        self.logger.debug('created %s', geometry)
        filesystem = parted.FileSystem(type='ext3', geometry=geometry)
        self.logger.debug('created %s', filesystem)
        partition = parted.Partition(disk=disk,
                                     type=parted.PARTITION_NORMAL,
                                     fs=filesystem,
                                     geometry=geometry)
        self.logger.debug('created %s', partition)
        disk.addPartition(partition=partition,
                          constraint=device.optimalAlignedConstraint)
        partition.setFlag(parted.PARTITION_BOOT)
        disk.commit()
	def create(cls, device_path, start, end):
		"""
		Device_path is something like /dev/sda
		start and end are integers of start/end in bytes
		"""

		if start < 0:
			raise ValueError('partition must start at a positive offset')
		if end <= start:
			raise ValueError('partition size must be positive')

		device_name = device_path.split('/')[-1]
		device = parted.Device(device_path)
		disk = parted.freshDisk(device, 'msdos')

		constraint = parted.Constraint(device=device)
		# Geometry units are sectors <===#
		block_size = int(sys['class']['block'][device_name]['queue']['logical_block_size'])
		start_in_sectors = start / block_size
		end_in_sectors = end / block_size

		geometry = parted.Geometry(device=device, start=start_in_sectors, end=end_in_sectors)
		filesystem = parted.FileSystem(type="ext4", geometry=geometry)

		# Create the partition object using the objects we defined before
		partition = parted.Partition(disk=disk, fs=filesystem, type=parted.PARTITION_NORMAL, geometry=geometry)
		# Redefine constraint to snap to the exact limits
		constraint = parted.Constraint(exactGeom=geometry)

		# Add partition to the disk. Will return True if successful
		disk.addPartition(partition=partition, constraint=constraint)
		# All the stuff we just did needs to be committed to the disk.
		disk.commit()
		return cls(partition.getDeviceNodeName())
Exemple #16
0
    def __init__(self, path, arch="x86"):

        self._arch = arch
        self._path = ""
        self._device = None
        self._model = ""
        self._disk = None
        self._disklabel = ""
        self._length = 0       # total sectors
        self._sectorSize = 0
        self._isSetup = False

        device = parted.Device(path)

        self._model = device.model
        self._length = device.length
        self._sectorSize = device.sectorSize

        self._device = device
        try:
            self._disk = parted.Disk(device)
        except:
            label = archinfo[self._arch]["disklabel"]
            self._disk = parted.freshDisk(self._device, ty=label)

        self._disklabel = self._disk.type

        self._path = path
        self._partitions = None
        self._update()
Exemple #17
0
    def best_disklabel_type(self, device):
        """The best disklabel type for the specified device."""
        if flags.testing:
            return self.default_disklabel_type

        parted_device = parted.Device(path=device.path)

        # if there's a required type for this device type, use that
        label_type = self.required_disklabel_type(parted_device.type)
        log.debug("required disklabel type for %s (%s) is %s", device.name,
                  parted_device.type, label_type)
        if not label_type:
            # otherwise, use the first supported type for this platform
            # that is large enough to address the whole device
            label_type = self.default_disklabel_type
            log.debug("default disklabel type for %s is %s", device.name,
                      label_type)
            for lt in self.disklabel_types:
                l = parted.freshDisk(device=parted_device, ty=lt)
                if l.maxPartitionStartSector > parted_device.length:
                    label_type = lt
                    log.debug("selecting %s disklabel for %s based on size",
                              label_type, device.name)
                    break

        return label_type
Exemple #18
0
    def freshPartedDisk(self):
        """ Return a new, empty parted.Disk instance for this device. """
        log_method_call(self, device=self.device)
	from pyanaconda.platform import getPlatform
        platf = getPlatform(None)
        labelType = platf.diskLabelType(self.partedDevice.type)
        return parted.freshDisk(device=self.partedDevice, ty=labelType)
Exemple #19
0
def mkfakediskimg(disk_img):
    """Create a fake partitioned disk image

    :param disk_img: Full path to a partitioned disk image
    :type disk_img: str
    :returns: True if it was successful, False if something went wrong

    Include /boot, swap, and / partitions with fake kernel and /etc/passwd
    """
    try:
        mksparse(disk_img, 42 * 1024**2)
        # Make a /boot, / and swap partitions on it
        dev = parted.getDevice(disk_img)
        disk = parted.freshDisk(dev, "gpt")

        # (start, length, flags, name)
        for start, length, flags, name in [
                  (  1024**2,    1024**2, None, "boot"),
                  (2*1024**2,  2*1024**2, parted.PARTITION_SWAP, "swap"),
                  (4*1024**2, 38*1024**2, None, "root")]:
            geo = parted.Geometry(device=dev, start=start//dev.sectorSize, length=length//dev.sectorSize)
            part = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL, geometry=geo)
            part.getPedPartition().set_name(name)
            disk.addPartition(partition=part)
            if flags:
                part.setFlag(flags)
        disk.commit()
        os.sync()
    except parted.PartedException:
        return False

    # Mount the disk's partitions
    loop_devs = kpartx_disk_img(disk_img)

    try:
        # Format the partitions
        runcmd(["mkfs.ext4", "/dev/mapper/" + loop_devs[0][0]])
        runcmd(["mkswap", "/dev/mapper/" + loop_devs[1][0]])
        runcmd(["mkfs.ext4", "/dev/mapper/" + loop_devs[2][0]])

        # Mount the boot partition and make a fake kernel and initrd
        boot_mnt = mount("/dev/mapper/" + loop_devs[0][0])
        try:
            mkfakebootdir(boot_mnt)
        finally:
            umount(boot_mnt)

        # Mount the / partition and make a fake / filesystem with /etc/passwd
        root_mnt = mount("/dev/mapper/" + loop_devs[2][0])
        try:
            mkfakerootdir(root_mnt)
        finally:
            umount(root_mnt)
    except Exception:
        return False
    finally:
        # Remove the disk's mounted partitions
        runcmd(["kpartx", "-d", "-s", disk_img])

    return True
Exemple #20
0
 def freshPartedDisk(self):
     """ Return a new, empty parted.Disk instance for this device. """
     log_method_call(self, device=self.device)
     from pyanaconda.platform import getPlatform
     platf = getPlatform(None)
     labelType = platf.diskLabelType(self.partedDevice.type)
     return parted.freshDisk(device=self.partedDevice, ty=labelType)
    def putGeom(self, limPartList):
        #Write the disk geometry information
        #Template code @ https://bitbucket.org/rbistolfi/vinstall/wiki/pyparted
        disk = parted.freshDisk(self.dev, "msdos")
        for lpar in limPartList:
            if lpar.parttype != 'artificial':
                #TODO: should check that the geometry is within the disk
                g = parted.Geometry(device=self.dev,
                                    start=lpar.start,
                                    end=lpar.end)
                fs = parted.FileSystem(type=lpar.fstype, geometry=g)

                #TODO: eventually we should be able to handle logical/extended
                #partitions - right now it's primary only
                ptype = parted.PARTITION_NORMAL
                if lpar.parttype != 'primary':
                    raise errors.partError(lpar.parttype)

                p = parted.Partition(disk=disk, fs=fs, type=ptype, geometry=g)
                c = parted.Constraint(exactGeom=g)
                disk.addPartition(partition=p, constraint=c)
                setFlags(p, lpar.flags)
        disk.commit()

        #refresh the OS's view of the disk
        support.partprobe(self.node)

        #put file systems onto the new partitions
        for lpar in limPartList:
            if lpar.parttype != 'artificial':
                support.mkfs(lpar.composeNode(self.node), lpar.fstype)
def single_partition_device_2_x(device, vars, log):
    try:
        log.write("Using pyparted 2.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.Device(device)
        # create a new partition table
        disk = parted.freshDisk(dev, "msdos")
        # 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="ext2", 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()
        print >> log, "Current disk for %s" % device, disk
        print >> log, "Current dev for %s" % device, dev
        del disk
    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
   def createPartitions(self, devicename, partitions, samesize):
      """
      Create the given partitions on the device devicename.
      @param partitions: the partitions to be created
      @type partitions: comoonics.storage.ComPartitions.Partition 
      """
      import parted
      dev=parted.getDevice(devicename)
      try:
         disk=parted.Disk(dev)
         disk.deleteAllPartitions()
      except self.disklabelexception:
         disk=parted.freshDisk(dev, parted.disk.diskType["msdos"])
      for part in partitions:
         partedtype=part.getPartedType()
         size=part.getAttribute("size")
         flags=part.getFlags()
         size=self.getSectorSize(size, dev)
         partedflags=list()
         for flag in flags:
            partedflags.append(flag.getFlagPartedNum())
         self.log.debug("creating partition: size: %i" % size )
         self.add_partition(disk, partedtype, size, flags, samesize=samesize)

      disk.commit()
def clobber_disk(device):
    """Reset drive"""
    common.eprint("DELETING PARTITIONS.")
    device.clobber()
    disk = parted.freshDisk(device, "gpt")
    disk.commit()
    return disk
def DevDisk():
    disks = {}
    disks_tag = {}
    blacklist = ["mapper", "sr"]  ##the device type not supported
    for dev in parted.getAllDevices():
        if test(dev.path.split("/")[2], blacklist) is False:
            continue
        disks_tag[dev.path] = False
        try:
            disks[dev.path] = parted.disk.Disk(dev)
        except:
            if dev.getSize("TB") >= 2:  ##larger than 2TiB
                disks[dev.path] = parted.freshDisk(dev, "gpt")
            else:
                disks[dev.path] = parted.freshDisk(dev, "msdos")
            continue
    return [disks, disks_tag]
Exemple #26
0
def disk_new_fresh(mia, operid, devpath, dltype):
    #dltype = parted.disk_type_get(dltype)
    dltype = parted.diskType[dltype]
    if dltype and CONF.RUN.g_all_harddisks.has_key(devpath):
        dev = CONF.RUN.g_all_harddisks[devpath][0]
        #CONF.RUN.g_all_harddisks[devpath] = (dev, dev.disk_new_fresh(dltype), 'y')
        CONF.RUN.g_all_harddisks[devpath] = (dev, parted.freshDisk(device=dev, ty=dltype), 'y')
    return 0
Exemple #27
0
    def create_empty(self):
        """create a new empty DOS partition table"""
        print """
Device contains no valid DOS partition table.
Building a new DOS disklabel.
Changes will remain in memory only, until you decide to write them.
After that, of course, the previous content won't be recoverable."""
        self.disk = parted.freshDisk(self.device, 'msdos')
Exemple #28
0
    def freshPartedDisk(self):
        """ Return a new, empty parted.Disk instance for this device. """
        if yali.util.isEfi():
            labelType = "gpt"
        else:
            labelType = "msdos"

        return parted.freshDisk(device=self.partedDevice, ty=labelType)
Exemple #29
0
 def new_table(self):
     """Create a new partition table on the device."""
     cancel = make_fn(None, "Don't create a new partition table.")
     fs = [make_fn(f) for f in parted.getLabels()]
     ty = self.sub_menu(tuple([(f(), f) for f in fs]) + (("Cancel", cancel),))
     if ty:
         self.disk = parted.freshDisk(self.device, ty)
     self.refresh_menu()
Exemple #30
0
    def freshPartedDisk(self):
        """ Return a new, empty parted.Disk instance for this device. """
        if yali.util.isEfi():
            labelType = "gpt"
        else:
            labelType = "msdos"

        return parted.freshDisk(device=self.partedDevice, ty=labelType)
Exemple #31
0
def raw_format(device_path, fstype, volume_label):

    do_umount(device_path)

    # First erase MBR and partition table , if any
    os.system("dd if=/dev/zero of=%s bs=512 count=1 >/dev/null 2>&1" %
              device_path)

    device = parted.getDevice(device_path)

    # Create a default partition set up
    disk = parted.freshDisk(device, 'msdos')
    disk.commit()
    regions = disk.getFreeSpaceRegions()

    if len(regions) > 0:
        #print "Build partition"
        # Define size
        region = regions[-1]
        start = parted.sizeToSectors(1, "MiB", device.sectorSize)
        #print "start %s" % start
        end = device.getLength() - start - 1024
        #print end

        # Alignment
        #cylinder = device.endSectorToCylinder(end)
        #end = device.endCylinderToSector(cylinder)
        #print end
        try:
            geometry = parted.Geometry(device=device, start=start, end=end)
        except:
            print "Geometry error - Can't create partition"
            sys.exit(5)

        # fstype
        fs = parted.FileSystem(type=fstype, geometry=geometry)

        # Create partition
        partition = parted.Partition(disk=disk,
                                     type=parted.PARTITION_NORMAL,
                                     geometry=geometry,
                                     fs=fs)
        constraint = parted.Constraint(exactGeom=geometry)
        disk.addPartition(partition=partition, constraint=constraint)
        disk.commit()

        # Format partition according to the fstype specified
        if fstype == "fat32":
            os.system("mkdosfs -F 32 -n \"%s\" %s >/dev/null 2>&1" %
                      (volume_label, partition.path))
        if fstype == "ntfs":
            os.system("mkntfs -f -L \"%s\" %s >/dev/null 2>&1" %
                      (volume_label, partition.path))
        elif fstype == "ext4":
            os.system("mkfs.ext4 -L \"%s\" %s >/dev/null 2>&1" %
                      (volume_label, partition.path))
    sys.exit(0)
Exemple #32
0
 def apply(self, unused_disk, simulate):
     """ Construct a new labeled disk """
     try:
         d = parted.freshDisk(self.device, self.label)
         self.disk = d
     except Exception as e:
         self.set_errors(e)
         return False
     return True
def disk_new_fresh(mia, operid, devpath, dltype):
    logger.d('disk_new_fresh %s %s' % (devpath, dltype))
    #dltype = parted.disk_type_get(dltype)
    dltype = parted.diskType[dltype]
    if dltype and CF.S.all_harddisks.has_key(devpath):
        dev = CF.S.all_harddisks[devpath][0]
        #CF.S.all_harddisks[devpath] = (dev, dev.disk_new_fresh(dltype), 'y')
        CF.S.all_harddisks[devpath] = (dev, parted.freshDisk(device=dev, ty=dltype), 'y')
    return 0
Exemple #34
0
 def apply(self, unused_disk, simulate):
     """ Construct a new labeled disk """
     try:
         d = parted.freshDisk(self.device, self.label)
         self.disk = d
     except Exception as e:
         self.set_errors(e)
         return False
     return True
def reload_partition_table(mia, operid, devpath):
    logger.d('reload_partition_table %s' % devpath)
    if CF.S.all_harddisks.has_key(devpath):
        dev = CF.S.all_harddisks[devpath][0]
        try:
            CF.S.all_harddisks[devpath] = (dev, parted.Disk(dev), None)
        except _ped.DiskLabelException:
            dltype = parted.diskType['msdos']
            CF.S.all_harddisks[devpath] = (dev, parted.freshDisk(device=dev, ty=dltype), 'y')
    return 0
Exemple #36
0
def raw_format(device_path, fstype, volume_label, uid, gid):

    do_umount(device_path)

    # First erase MBR and partition table , if any
    call(["dd", "if=/dev/zero", "of=%s" % device_path, "bs=512", "count=1"])

    device = parted.getDevice(device_path)

    # Create a default partition set up
    disk = parted.freshDisk(device, 'msdos')
    disk.commit()
    regions = disk.getFreeSpaceRegions()

    if len(regions) > 0:
        # Start partition at sector 2048
        offset = 2048
        # 1Mib grain size
        grain_size = kib_to_sectors(device, 1024)
        # Get first region
        region = regions[0]
        start = region.start
        end = region.end - start + 1

        align = parted.Alignment(offset=offset, grainSize=grain_size)
        if not align.isAligned(region, start):
            start = align.alignNearest(region, start)

        align = parted.Alignment(offset=offset -1, grainSize=grain_size)
        if not align.isAligned(region, end):
            end = align.alignNearest(region, end)
        try:
            geometry = parted.Geometry(device=device, start=start, end=end)
        except:
            print "Geometry error - Can't create partition"
            sys.exit(5)

        # fstype
        fs = parted.FileSystem(type=fstype, geometry=geometry)

        # Create partition
        partition = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL, geometry=geometry, fs=fs)
        constraint = parted.Constraint(exactGeom=geometry)
        disk.addPartition(partition=partition, constraint=constraint)
        partition.setFlag(parted.PARTITION_BOOT)
        disk.commit()

        # Format partition according to the fstype specified
        if fstype == "fat32":
            call(["mkdosfs", "-F", "32", "-n", volume_label, partition.path])
        if fstype == "ntfs":
            call(["mkntfs", "-f", "-L", volume_label, partition.path])
        elif fstype == "ext4":
            call(["mkfs.ext4", "-E", "root_owner=%s:%s" % (uid, gid), "-L", volume_label, partition.path])
    sys.exit(0)
Exemple #37
0
def main(argv=None):
    from argparse import ArgumentParser
    from os.path import isfile
    from yaml import load
    try:
        from yaml import CLoader as Loader
    except ImportError:
        from yaml import Loader

    parser = ArgumentParser(description="")
    parser.add_argument('-c', '--config', default=None, help='')

    args = parser.parse_args()

    if not args.config or not isfile(args.config):
        raise SystemExit("Error: must specify config file.")

    config = load(open(args.config, 'r'), Loader=Loader)

    # FIXME: should compute disk size automatically from partitions if not
    # specified, and sanity check otherwise
    for diskspec in config['disks']:
        dsize = sum(size_to_bytes(p['size']) for p in diskspec['partitions'])
        dsize = max(diskspec.get('size', dsize), dsize)

        # FIXME: add partition table type and gpt support
        # space for partition table
        dsize += 512
        # below for gpt...
        #dsize += 67*512

        # create empty disk file
        f = open('disk.img', 'w')
        f.seek(dsize - 1)
        f.write('\0')
        f.close()

        # create partitions and add file systems as appropriate
        device = parted.Device(path='disk.img')
        disk = parted.freshDisk(device, 'msdos')
        startsect = 1
        for partspec in diskspec['partitions']:
            length = size_to_bytes(partspec['size']) // device.sectorSize
            geometry = parted.Geometry(device, start=startsect, length=length)
            # FIXME: support for extended partitions?
            partition = parted.Partition(disk=disk, 
                                         type=parted.PARTITION_NORMAL, 
                                         geometry=geometry)
            if partspec['boot']:
                partition.setFlag(parted.PARTITION_BOOT)
            constraint = parted.Constraint(minGeom=geometry)
            disk.addPartition(partition=partition, constraint=constraint)
            startsect += length

        disk.commitToDevice()
Exemple #38
0
def raw_format(device_path, fstype, volume_label, uid, gid):

    do_umount(device_path)

    # First erase MBR and partition table , if any
    os.system ("dd if=/dev/zero of=%s bs=512 count=1 >/dev/null 2>&1" % device_path)

    device = parted.getDevice(device_path)

    # Create a default partition set up
    disk = parted.freshDisk(device, 'msdos')
    try:
        disk.commit()
    except:
        # Unable to write the new partition
        print "Can't create partition. The device could be read-only."
        sys.exit(5)
    regions = disk.getFreeSpaceRegions()

    if len(regions) > 0:
        #print "Build partition"
        # Define size
        start = parted.sizeToSectors(1, "MiB", device.sectorSize)
        #print "start %s" % start
        end = device.getLength() - start - 1024
        #print end

        # Alignment
        #cylinder = device.endSectorToCylinder(end)
        #end = device.endCylinderToSector(cylinder)
        #print end
        try:
            geometry = parted.Geometry(device=device, start=start, end=end)
        except:
            print "Geometry error - Can't create partition"
            sys.exit(5)

        # fstype
        fs = parted.FileSystem(type=fstype, geometry=geometry)

        # Create partition
        partition = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL, geometry=geometry, fs=fs)
        constraint = parted.Constraint(exactGeom=geometry)
        disk.addPartition(partition=partition, constraint=constraint)
        disk.commit()

        # Format partition according to the fstype specified
        if fstype == "fat32":
            os.system("mkdosfs -F 32 -n \"%s\" %s >/dev/null 2>&1" % (volume_label, partition.path))
        if fstype == "ntfs":
            os.system("mkntfs -f -L \"%s\" %s >/dev/null 2>&1" % (volume_label, partition.path))
        elif fstype == "ext4":
            os.system("mkfs.ext4 -E root_owner=%s:%s -L \"%s\" %s >/dev/null 2>&1" % (uid, gid, volume_label, partition.path))
    sys.exit(0)
Exemple #39
0
def disk_new_fresh(mia, operid, devpath, dltype):
    logger.d('disk_new_fresh %s %s' % (devpath, dltype))
    #dltype = parted.disk_type_get(dltype)
    dltype = parted.diskType[dltype]
    if dltype and CF.S.all_harddisks.has_key(devpath):
        dev = CF.S.all_harddisks[devpath][0]
        #CF.S.all_harddisks[devpath] = (dev, dev.disk_new_fresh(dltype), 'y')
        CF.S.all_harddisks[devpath] = (dev,
                                       parted.freshDisk(device=dev,
                                                        ty=dltype), 'y')
    return 0
    def nueva_tabla_particiones(self, drive, t):
        dev = parted.Device(drive)
        new = parted.freshDisk(dev, t)

        while True:
            if not dev.busy:
                break

        try:
            new.commit()
        except _ped.IOException, x:
            print x
Exemple #41
0
def reload_partition_table(mia, operid, devpath):
    logger.d('reload_partition_table %s' % devpath)
    if CF.S.all_harddisks.has_key(devpath):
        dev = CF.S.all_harddisks[devpath][0]
        try:
            CF.S.all_harddisks[devpath] = (dev, parted.Disk(dev), None)
        except _ped.DiskLabelException:
            dltype = parted.diskType['msdos']
            CF.S.all_harddisks[devpath] = (dev,
                                           parted.freshDisk(device=dev,
                                                            ty=dltype), 'y')
    return 0
Exemple #42
0
    def nueva_tabla_particiones(self, drive, t):
        dev = parted.Device(drive)
        new = parted.freshDisk(dev, t)

        while True:
            if not dev.busy:
                break

        try:
            new.commit()
        except _ped.IOException, x:
            print x
Exemple #43
0
 def disk_doldur(self, widget):
     self.ebeveyn.milis_ayarlari["takas_disk"] = ""
     self.ebeveyn.milis_ayarlari["sistem_disk"] = ""
     self.ebeveyn.milis_ayarlari["uefi_disk"] = ""
     if self.ebeveyn.stack_secili == 4:
         self.ebeveyn.ileri_dugme.set_sensitive(False)
     self.diskler_combo.remove_all()
     self.grub_combo.remove_all()
     self.diskler = parted.getAllDevices()
     for disk in self.diskler:
         try:
             if parted.Disk(disk).type == "msdos" or parted.Disk(
                     disk).type == "gpt":
                 self.diskler_liste[disk.path] = {
                     "parted": parted.Disk(disk),
                     "tum_boyut": format(disk.getSize(unit="GB"), '.2f'),
                     "bölüm": []
                 }
                 self.diskler_combo.append_text(
                     disk.path + " | " + disk.model + " | " +
                     format(disk.getSize(unit="GB"), '.2f') + "GB")
                 self.grub_combo.append_text(disk.path + " | " +
                                             disk.model + " | " +
                                             format(disk.getSize(
                                                 unit="GB"), '.2f') + "GB")
         except parted.DiskLabelException:
             disk = parted.freshDisk(disk, "msdos")
             # CDROM Aygıtları için
             try:
                 disk.commit()
             except parted.IOException:
                 pass
             else:
                 disk = disk.device
                 self.diskler_liste[disk.path] = {
                     "parted": parted.Disk(disk),
                     "tum_boyut": format(disk.getSize(unit="GB"), '.2f'),
                     "bölüm": []
                 }
                 self.diskler_combo.append_text(
                     disk.path + " | " + disk.model + " | " +
                     format(disk.getSize(unit="GB"), '.2f') + "GB")
                 self.grub_combo.append_text(disk.path + " | " +
                                             disk.model + " | " +
                                             format(disk.getSize(
                                                 unit="GB"), '.2f') + "GB")
         for bolum in parted.Disk(disk).partitions:
             gelen = self.bolumBilgi(bolum)
             if gelen:
                 self.diskler_liste[disk.path]["bölüm"].append(gelen)
     self.diskler_combo.set_active(0)
     self.grub_combo.set_active(0)
Exemple #44
0
    def diskPartitionList(self):
        self.treePartitionWidget.clear()
        for device in parted.getAllDevices():
            top_item = QTreeWidgetItem(self.treePartitionWidget)
            top_item.setExpanded(True)
            top_item.setText(0, device.path)
            self.treePartitionWidget.addTopLevelItem(top_item)
            try:
                for partition in parted.Disk(device).partitions:
                    try:
                        part_item = QTreeWidgetItem(top_item)
                        part_item.setText(0, partition.path)
                        part_item.setText(1, partition.fileSystem.type)
                        part_item.setText(2, "")
                        part_item.setText(3, partition.name or "")
                        part_item.setText(4, "✔")
                        part_item.setText(5, mbToGB(partition.getSize()))

                    except AttributeError:
                        part_item = QTreeWidgetItem(top_item)
                        part_item.setText(0, partition.path)
                        part_item.setText(1, self.tr("Unknown"))
                        part_item.setText(2, "")
                        part_item.setText(3, partition.name or "")
                        part_item.setText(4, "✔")
                        part_item.setText(5, mbToGB(partition.getSize()))

            except parted.DiskLabelException as err:

                if is_efi():
                    disk = parted.freshDisk(device, "gpt")
                else:
                    disk = parted.freshDisk(device, "msdos")

                try:
                    disk.commit()
                except parted.IOException as err:
                    print(err)
                    self.diskPartitionList()
Exemple #45
0
    def runTest(self):
        # Make sure we get SyntaxError when using an invalid disk type
        self.assertRaises(KeyError, parted.freshDisk, self.device, 'cheese')
        self.assertRaises(KeyError, parted.freshDisk, self.device, 'crackers')

        # Create a new disk for each disk type key, verify each one
        # XXX: Skip over dvh for now (SGI disk label), which doesn't seem to have
        # working libparted support.  If anyone with an SGI cares, patches welcome.
        for key in parted.diskType.keys():
            if key in ['dvh', 'aix']:
                continue
            disk = parted.freshDisk(self.device, key)
            self.assertIsInstance(disk, parted.Disk)
            self.assertEqual(disk.type, key)

        # Create a new disk each disk type value, verify each one
        for value in parted.diskType.values():
            if value.name in ['dvh', 'aix']:
                continue
            disk = parted.freshDisk(self.device, value)
            self.assertIsInstance(disk, parted.Disk)
            self.assertEqual(parted.diskType[disk.type], value)
Exemple #46
0
def blockPartitions(path):
    device = parted.Device(path)
    try:
        disk = parted.Disk(device)
    except:
        # FIXME: This is suck! Must be changed!
        disk = parted.freshDisk(device, parted.diskType['msdos'])

    partition = disk.getFirstPartition()
    while partition:
        if partition.fileSystem and partition.fileSystem.type != "linux-swap":
            yield partition.path, partition.fileSystem.type
        partition = partition.nextPartition()
    def runTest(self):
        # Make sure we get SyntaxError when using an invalid disk type
        self.assertRaises(KeyError, parted.freshDisk, self.device, 'cheese')
        self.assertRaises(KeyError, parted.freshDisk, self.device, 'crackers')

        # Create a new disk for each disk type key, verify each one
        # XXX: Skip over dvh for now (SGI disk label), which doesn't seem to have
        # working libparted support.  If anyone with an SGI cares, patches welcome.
        for key in parted.diskType.keys():
            if key == 'dvh':
                continue
            disk = parted.freshDisk(self.device, key)
            self.assert_(isinstance(disk, parted.Disk))
            self.assertTrue(disk.type == key)

        # Create a new disk each disk type value, verify each one
        for value in parted.diskType.values():
            if value.name == 'dvh':
                continue
            disk = parted.freshDisk(self.device, value)
            self.assert_(isinstance(disk, parted.Disk))
            self.assertTrue(parted.diskType[disk.type] == value)
Exemple #48
0
def blockPartitions(path):
    device = parted.Device(path)
    try:
        disk = parted.Disk(device)
    except:
        # FIXME: This is suck! Must be changed!
        disk = parted.freshDisk(device, parted.diskType['msdos'])

    partition = disk.getFirstPartition()
    while partition:
        if partition.fileSystem and partition.fileSystem.type != "linux-swap":
            yield partition.path, partition.fileSystem.type
        partition = partition.nextPartition()
Exemple #49
0
 def __init__(self, number, path):
     self.number = number
     self.path = path
     self.pdev = parted.getDevice(path)
     self.pdisk = parted.freshDisk(self.pdev, 'msdos')
     if self.pdisk.deleteAllPartitions():
         self.pdisk.commit()
         logging.info('%s cleared all prexisting partitions from disk' % (
             self.__class__.__name__))
     self.size_bytes = get_disk_size(path)
     self.size_sectors = bytes_to_sectors(size_bytes_to_int(self.size_bytes),
                                          self.pdev.sectorSize)
     self.grow_part = False
     self._partitions = []
Exemple #50
0
def reload_partition_table(mia, operid, devpath):
    if CONF.RUN.g_all_harddisks.has_key(devpath):
        dev = CONF.RUN.g_all_harddisks[devpath][0]
        try:
            CONF.RUN.g_all_harddisks[devpath] = (dev, parted.Disk(dev), None)
        except _ped.DiskLabelException:
            dltype = parted.diskType['msdos']
            CONF.RUN.g_all_harddisks[devpath] = (dev, parted.freshDisk(device=dev, ty=dltype), 'y')
        #try:
        #    CONF.RUN.g_all_harddisks[devpath] = (dev, parted.PedDisk.new(dev), None)
        #except parted.error:
        #    dltype = parted.disk_type_get('msdos')
        #    CONF.RUN.g_all_harddisks[devpath] = (dev, dev.disk_new_fresh(dltype), 'y')
    return 0
Exemple #51
0
 def createpartitions(self):
     ''' Partition the LVM volume into persistent and swap partitions
         using the parted module.
     '''
     dev = parted.Device(path=self.lvpath)
     dev.removeFromCache()
     disk = parted.freshDisk(dev, 'msdos')
     constraint = parted.Constraint(device=dev)
     persist_size = int(0.75 * constraint.maxSize);
     self.createpartition(device=dev, disk=disk, start=1,
                      end=(persist_size - 1) , type="ext4")
     self.createpartition(device=dev, disk=disk, start=persist_size,
                      end=(constraint.maxSize - 1) , type="linux-swap(v1)")
     disk.commit()
Exemple #52
0
 def createpartitions(self):
     ''' Partition the LVM volume into persistent and swap partitions
         using the parted module.
     '''
     dev = parted.Device(path=self.lvpath)
     dev.removeFromCache()
     disk = parted.freshDisk(dev, 'msdos')
     constraint = parted.Constraint(device=dev)
     persist_size = int(0.75 * constraint.maxSize);
     self.createpartition(device=dev, disk=disk, start=1,
                      end=(persist_size - 1) , type="ext4")
     self.createpartition(device=dev, disk=disk, start=persist_size,
                      end=(constraint.maxSize - 1) , type="linux-swap(v1)")
     disk.commit()
Exemple #53
0
    def init_disk(self, disk, ptable):
        """
        Initial and wipe the disk, and set the new partition table to ptable.
        :param disk: Device to initialize.
        :param ptable: Partition table to use msdos/gpt.
        :return:
        """
        self.log.debug(f"parted: init_disk: disk:{disk} ptable:{ptable}")
        # Set the device.
        self.device = parted.getDevice(disk)

        # Wipe the device.
        self.device.clobber()

        # Create label on the disk.
        self.pdisk = parted.freshDisk(self.device, ptable)
def partition(diskname, specs, force=False, check_mode=False):
    """
    Create requested partitions.
    Returns nr. of created partitions or 0 when the disk was already partitioned.
    """
    count = 0

    dev = parted.getDevice(diskname)
    try:
        disk = parted.newDisk(dev)
    except parted.DiskException:
        # unrecognizable format, treat as empty disk
        disk = None

    if disk and len(disk.partitions) > 0 and not force:
        print "skipping", diskname
        return 0

    # create new partition table, wiping all existing data
    disk = parted.freshDisk(dev, 'gpt')
    # calculate nr. of partitions of each size
    assign_space(dev.getSize(), specs)
    last_megabyte = 1
    for spec in specs:
        for _ in range(spec.count):
            # create the partition
            start = parted.sizeToSectors(last_megabyte, "MiB", dev.sectorSize)
            length = parted.sizeToSectors(spec.size, "MiB", dev.sectorSize)
            geo = parted.Geometry(device=dev, start=start, length=length)
            filesystem = parted.FileSystem(type='ext4', geometry=geo)
            part = parted.Partition(disk=disk,
                                    type=parted.PARTITION_NORMAL,
                                    fs=filesystem,
                                    geometry=geo)
            disk.addPartition(partition=part,
                              constraint=dev.optimalAlignedConstraint)
            last_megabyte += spec.size
            count += 1
    try:
        if not check_mode:
            disk.commit()
    except parted.IOException:
        # partitions have been written, but we have been unable to inform the
        # kernel of the change, probably because they are in use.
        # Ignore it and hope for the best...
        pass
    return count
def partition(diskname, specs, force=False, check_mode=False):
    """
    Create requested partitions.
    Returns nr. of created partitions or 0 when the disk was already partitioned.
    """
    count = 0

    dev = parted.getDevice(diskname)
    try:
        disk = parted.newDisk(dev)
    except parted.DiskException:
        # unrecognizable format, treat as empty disk
        disk = None

    if disk and len(disk.partitions) > 0 and not force:
        print "skipping", diskname
        return 0

    # create new partition table, wiping all existing data
    disk = parted.freshDisk(dev, 'gpt')
    # calculate nr. of partitions of each size
    assign_space(dev.getSize(), specs)
    last_megabyte = 1
    for spec in specs:
        for _ in range(spec.count):
            # create the partition
            start = parted.sizeToSectors(last_megabyte, "MiB", dev.sectorSize)
            length = parted.sizeToSectors(spec.size, "MiB", dev.sectorSize)
            geo = parted.Geometry(device=dev, start=start, length=length)
            filesystem = parted.FileSystem(type='ext4', geometry=geo)
            part = parted.Partition(
                disk=disk,
                type=parted.PARTITION_NORMAL,
                fs=filesystem,
                geometry=geo)
            disk.addPartition(partition=part, constraint=dev.optimalAlignedConstraint)
            last_megabyte += spec.size
            count += 1
    try:
        if not check_mode:
            disk.commit()
    except parted.IOException:
        # partitions have been written, but we have been unable to inform the
        # kernel of the change, probably because they are in use.
        # Ignore it and hope for the best...
        pass
    return count
Exemple #56
0
def main():
    opt = opciones()
    verifica(opt)
    #Inicializando dispositivo
    try:
        print '\nVerificando dispositivo............',
        sdb = parted.getDevice(opt.device)
    except Exception:
        print '[ERROR]'
        exit(1)
    print '[OK]'
    print '\nDispositivo seleccionado: ' + opt.device
    c = ''
    while c != 'y':
        c = raw_input(
            '\nAl dispositivo ' + opt.device +
            ' se le eliminara la tabla de particion actual, quieres continuar? [Y/n] '
        )
        c = c.lower()
        if c == 'n':
            print '\nSaliendo ...\n'
            exit(1)
        elif c == '' or c == 'y':
            c = 'y'
            sdb.clobber()
            print ''
            pass
    try:
        disk = parted.newDisk(sdb)
    except Exception:
        pass
    print 'Creando dispositivo msdos\n'
    disk = parted.freshDisk(sdb, 'msdos')
    print 'Tipos aceptados'
    for x in parted.fileSystemType.keys():
        print x + ' ',
    print ''
    fin = 0
    n = raw_input('\nCuantas particiones van a ser? (maximo 4)> ')
    print ''
    for x in range(int(n)):
        print 'Particion primaria ' + str(x + 1) + ':'
        t = raw_input('Tipo> ')
        s = long(raw_input('Tamaño en MiB> '))
        print ''
        fin = particion_pri(sdb, disk, s, t, fin)
Exemple #57
0
    def partition(device):
        dev = parted.Device(path=device)
        disk = parted.freshDisk(dev, 'msdos')
        constraint = parted.Constraint(device=dev)

        new_geom = parted.Geometry(device=dev,
                                   start=1,
                                   end=(constraint.maxSize - 1))
        filesystem = parted.FileSystem(type="ext2", geometry=new_geom)
        partition = parted.Partition(disk=disk,
                                     fs=filesystem,
                                     type=parted.PARTITION_NORMAL,
                                     geometry=new_geom)
        constraint = parted.Constraint(exactGeom=new_geom)
        partition.setFlag(parted.PARTITION_BOOT)
        disk.addPartition(partition=partition, constraint=constraint)

        disk.commit()
def create_partitioning(device):
    """Returns a suitable partitioning (a disk) of the given
    device. You must specify device path (e.g. "/dev/sda"). Note that
    no changes will be made to the device. To write the partition to
    device use commit."""
    disk = parted.freshDisk(device, 'gpt')
    geometries = _compute_geometries(device)
    # Create ESP
    esp = parted.Partition(disk=disk,
                           type=parted.PARTITION_NORMAL,
                           fs=parted.FileSystem(type='fat32',
                                                geometry=geometries['esp']),
                           geometry=geometries['esp'])
    esp.setFlag(parted.PARTITION_BOOT)
    disk.addPartition(partition=esp,
                      constraint=device.optimalAlignedConstraint)
    # Create Data partition
    data = parted.Partition(disk=disk,
                            type=parted.PARTITION_NORMAL,
                            fs=parted.FileSystem(type='ext4',
                                                 geometry=geometries['data']),
                            geometry=geometries['data'])
    disk.addPartition(partition=data,
                      constraint=device.optimalAlignedConstraint)
    # Create system.a partition
    systemA = parted.Partition(
        disk=disk,
        type=parted.PARTITION_NORMAL,
        fs=parted.FileSystem(type='ext4', geometry=geometries['systemA']),
        geometry=geometries['systemA'])
    disk.addPartition(partition=systemA,
                      constraint=device.optimalAlignedConstraint)
    # Create system.b partition
    systemB = parted.Partition(
        disk=disk,
        type=parted.PARTITION_NORMAL,
        fs=parted.FileSystem(type='ext4', geometry=geometries['systemB']),
        geometry=geometries['systemB'])
    disk.addPartition(partition=systemB,
                      constraint=device.optimalAlignedConstraint)
    return (disk)