Exemple #1
0
def grubDiskAndPartitionIndicies(part):
    '''Grub defines disks and partitions by their indicies as they are found
    in the boot order.  It has no knowledge of sdX versus hdX versus CCISS
    versus DAC960.  It just knows the first, second, third, etc. and expects
    them to be indicated in its conf files in a format like (hd0,0)
    So this function, for a given partition, gets the index of the disk and
    the index of the partition on said disk.

    Raise a KeyError if it can not be found in the DiskSet.
    '''
    disks = devices.DiskSet()
    orderedDrives = disks.getOrderedDrives()

    for diskIndex, drive in enumerate(orderedDrives):
        for candidatePart in drive.partitions:
            if candidatePart == part:
                # logical partitions ALWAYS start at 4, so use partitionId
                grubPartitionNum = candidatePart.partitionId - 1
                log.debug('Disk/partition %s/%s enumerated as %d,%d '
                          'for grub' % (drive.name, candidatePart.name,
                                        diskIndex, grubPartitionNum))
                return (diskIndex, grubPartitionNum)

    nonStandardDisk = disks.findDiskContainingPartition(part)
    if nonStandardDisk:
        # XXX this should disappear...
        # logical partitions ALWAYS start at 4, so use partitionId
        grubPartitionNum = part.partitionId - 1
        log.debug('Non-standard disk/partition 0/%d' % (grubPartitionNum))
        return (0, grubPartitionNum)

    partName = part.getName()
    raise KeyError('Partition not found in disk set: %s' % partName)
Exemple #2
0
def findUSBMedia(showAll=False):
    """Scan attached USB devices for installation media.

    If showAll is True, all CD devices are returned even if they do not contain
    any installation media.
    """

    diskSet = devices.DiskSet(forceReprobe=True)

    retval = []

    util.umount(USB_MEDIA_PATH)
    for disk in diskSet.values():
        if disk.driverName != devices.DiskDev.DRIVER_USB_STORAGE:
            log.debug("skipping non-usb device -- %s" % disk.name)
            continue

        diskMedia = []
        for part in disk.partitions:
            if not part.consoleDevicePath:
                continue

            diskMedia += _tryDevice(disk, part)

        if not diskMedia and showAll:
            # No installation media was found on the device, but the caller
            # wants the list of potential media devices, so add that in.
            diskMedia = [media.MediaDescriptor(disk.name)]

        retval += diskMedia

    return retval
Exemple #3
0
def getKernelOptions(kernelMemInMB):
    '''Create the list of options that get appended onto the "kernel"
    line of the grub.conf file.
    '''
    disks = devices.DiskSet()
    rootPartition = disks.findPartitionContaining('/', searchVirtual=True)
    if not rootPartition:
        raise PartitionNotFound('/')

    devPartName = rootPartition.consoleDevicePath
    if not devPartName:
        # expected /dev/sda1 for the 1-disk case
        raise MissingConsoleDevicePath(rootPartition)
    rootPartUuid = getUuid(devPartName)

    # ro: mount "/" read-only in the initrd environment but when the init
    # scripts start up it magically gets remounted rw.
    options = 'ro'

    # root: tell the kernel where to find "/"
    options += ' root=UUID=' + rootPartUuid

    # mem: tell the kernel how much memory it can use
    options += ' mem=' + kernelMemInMB + 'M'

    choices = userchoices.getBoot()
    if choices and choices['kernelParams']:
        options += ' ' + choices['kernelParams']
    return options
Exemple #4
0
    def start(self):
        "Initial step."

        # ESX device is previous user choice or location of /boot.
        self.esxDeviceName = userchoices.getEsxPhysicalDevice()
        devs = userchoices.getPhysicalPartitionRequestsDevices()
        for dev in devs:
            request = userchoices.getPhysicalPartitionRequests(dev)
            if request.findRequestByMountPoint('/boot'):
                self.esxDeviceName = dev
        assert self.esxDeviceName

        self.clearDrives = [self.esxDeviceName]

        createNewDataStoreFunc = self.createNewDataStore
        if not devices.DiskSet()[self.esxDeviceName].supportsVmfs:
            createNewDataStoreFunc = self.createNewDataStoreDiffDev

        ui = {
            'title': title,
            'body': dataStoreText,
            'menu': {
                '1': createNewDataStoreFunc,
                '2': self.useExistingDataStore,
                '<': self.stepBack,
                '?': self.help,
            }
        }
        self.setSubstepEnv(ui)
Exemple #5
0
    def commit(self):
        """Commit updates.  By the time we get here, we assume:
        * volume name has been sanity checked
        * requested size has been checked
        """

        assert self.deviceName, 'datastore device name not set'
        assert self.volumeName, 'datastore volume name not set'
        log.debug("DataStoreWindow.commit device %s volume %s" %
                  (self.deviceName, self.volumeName))

        # Check if drives to clear are in use; if so stop this madness.
        diskSet = devices.DiskSet()
        if self.deviceName == self.esxDeviceName:
            clearDrives = [self.deviceName]
        else:
            clearDrives = [self.deviceName, self.esxDeviceName]
            # presumably self.choseCreateNewDatastoreOnEsxDevice == False

        log.debug("Cleared drives = %s" % (', '.join(clearDrives)))
        volumePath = os.path.join('/vmfs/volumes', self.volumeName)

        if (os.path.exists(volumePath) or os.path.islink(volumePath)) \
           and not checkForClearedVolume(clearDrives, self.datastoreSet,
                                         self.volumeName):
            log.debug("Volume name in use")
            self.setSubstepEnv({'next': self.warnInUse})
            return

        # build partition requests, add to userchoices
        partition.addDefaultPartitionRequests(diskSet[self.esxDeviceName],
                                              False)

        if self.choseCreateNewDatastore:
            physicalRequests = [
                (None, 100, 0, True, fsset.vmfs3FileSystem(self.volumeName)),
            ]
            dev = diskSet[self.deviceName]
            userchoices.addPhysicalPartitionRequests(
                self.deviceName,
                partition.createPartitionRequestSet(dev, physicalRequests))

            userchoices.setClearPartitions(drives=clearDrives)

            userchoices.setEsxDatastoreDevice(dev.name)
            userchoices.setVmdkDatastore(self.volumeName)
        else:  # use existing datastore
            userchoices.setClearPartitions(drives=[self.esxDeviceName])

            userchoices.clearVirtualDevices()

            userchoices.setEsxDatastoreDevice(None)
            userchoices.setVmdkDatastore(self.volumeName)

        # size check
        size = partition.getRequestsSize(partition.getDefaultVirtualRequests())
        if size > devices.runtimeActionFindMaxVmdkSize():
            self.setSubstepEnv({'next': self.warnTooSmall})
            return
        self.setSubstepEnv({'next': self.stepForward})
    def __init__(self, controlState, xml):
        controlState.displayHeaderBar = True
        controlState.windowTitle = "ESX Storage Device"
        controlState.windowText = "Select a location to install ESX"
        controlState.windowIcon = "drive.png"

        self.xml = xml

        self.controlState = controlState

        self.view = xml.get_widget("EsxlocationView")
        self.scrolled = xml.get_widget("EsxlocationScrolled")

        storage_widgets.setupStorageView(self.view)

        # only repopulate the esxlocation if we need to
        if userchoices.getResetEsxLocation():
            model = \
                storage_widgets.populateStorageModel(self.view, self.scrolled,
                                                     devices.DiskSet(),
                                                     vmfsSupport=False)
            storage_widgets.findFirstSelectableRow(model, self.view,
                                                   SUPPORTED_DISK_ENTRY)

        connectSignalHandlerByDict(
            self, EsxLocationWindow, self.xml, {
                ('EsxlocationDetailsButton', 'clicked'): 'showDetails',
            })
Exemple #7
0
    def bldStorDisplayList(self):
        " build displayable storage list"
        # only repopulate esxlocation if we need to
        if userchoices.getResetEsxLocation():
            self.storList = \
                storage_utils.getStorageList(devices.DiskSet(),
                                             vmfsSupport=(self.partMode=="basic"),
                                             esxAndCos=(self.partMode=="basic"))

        # build storage list
        storListText = []

        storEnumStr = "%2d) %-51s %3s %4s %11s"
        storEnumPath = "        %s"
        storListText.append(diskHeaderText)
        for num, storLine in enumerate(self.storList):
            deviceModel, lunid, disksize, entry, pathString, targetid = storLine
            storListText.append(
                storEnumStr %
                (num + 1, deviceModel, lunid, targetid, disksize))
            for path in pathString:
                tempEnumPath = storEnumPath % path
                while tempEnumPath:
                    storListText.append(tempEnumPath[:80])
                    tempEnumPath = tempEnumPath[80:]

        self.setScrollEnv(storListText, SCROLL_LIMIT)
        self.setSubstepEnv({'next': self.scrollDisplay})
Exemple #8
0
def hostActionClearPartitions(context):
    clearParts = userchoices.getClearPartitions()
    if 'drives' in clearParts and 'whichParts' in clearParts:
        # XXX A side-effect of getting the list of vmfs volumes in DatastoreSet
        # is that any existing vmfs volumes will get put into a cache in the
        # kernel.  While in this cache, some SCSI handles are left open which
        # prevent us from clearing the partition table completely.
        #
        # See pr 237236 for more information.
        fsset.flushVmfsVolumes()

        context.cb.pushStatusGroup(len(clearParts['drives']))
        for deviceName in clearParts['drives']:
            device = devices.DiskSet()[deviceName]
            if device.name in userchoices.getDrivesInUse():
                log.info("skipping clearing drive -- %s" % device.name)
                continue

            context.cb.pushStatus("Clearing Partition %s (%s)" %
                                  (device.name, device.path))
            if clearParts['whichParts'] == userchoices.CLEAR_PARTS_ALL:
                device.partitions.clear()
            else:
                #TODO: finish this for the other options.
                assert False, "clearPartitions not completely implemented"
            device.partitions.partedDisk.commit()  # XXX
            context.cb.popStatus()
        context.cb.popStatusGroup()

        # rescan the vmfs volumes in case we need to disconnect any since
        # we have a new partition table
        fsset.rescanVmfsVolumes()
Exemple #9
0
def runtimeActionExtractVmdkPathFromInitrd(driveName):
    '''Open the initrd.img file on a disk and find the location of the
       Console VMDK file from esx.conf.
    '''
    diskSet = devices.DiskSet()
    drive = diskSet[driveName]
    partition = drive.findFirstPartitionMatching(fsTypes=('ext3'))

    if not partition or partition.partitionId != 1:
        return ''

    tmpMntDir = tempfile.mkdtemp(prefix='weasel', dir='/mnt')
    partition.fsType.mount(partition.consoleDevicePath, tmpMntDir)

    tmpDir = tempfile.mkdtemp(prefix='weasel')

    initrdFilePath = os.path.join(tmpMntDir, 'initrd.img')

    cmd = "cd %s && zcat %s | cpio -id %s" % \
        (tmpDir, initrdFilePath, ESXCONF_FILE[1:])
    util.execCommand(cmd)

    vmdkPath = getValueFromConfig(os.path.join(tmpDir, ESXCONF_FILE[1:]),
                                  '/boot/cosvmdk')

    partition.fsType.umount(tmpMntDir)

    shutil.rmtree(tmpMntDir)
    shutil.rmtree(tmpDir)

    return vmdkPath
Exemple #10
0
def preserveDatastoreOnDrive(driveName):
    import userchoices

    diskSet = devices.DiskSet()
    datastoreSet = DatastoreSet()

    # find the /boot partition
    disk = diskSet[driveName]
    part = disk.findFirstPartitionMatching(
        fsTypes=('ext2', 'ext3'), minimumSize=partition.BOOT_MINIMUM_SIZE)

    assert part

    # wipe the partition
    part.mountPoint = "/boot"
    req = partition.PartitionRequest(mountPoint=part.mountPoint,
                                     minimumSize=part.getSizeInMegabytes(),
                                     fsType=part.fsType,
                                     consoleDevicePath=part.consoleDevicePath,
                                     clearContents=True)

    # get the datastores for a given drive
    datastores = datastoreSet.getEntriesByDriveName(driveName)

    userchoices.addPartitionMountRequest(req)
    userchoices.clearVirtualDevices()

    # XXX - assuming there is only one datastore on the drive
    partition.addDefaultVirtualDriveAndRequests(driveName,
                                                vmfsVolume=datastores[0].name)
Exemple #11
0
 def getName(self):
     """Get a descriptive name for this installation media."""
     
     if self.diskName:
         diskSet = devices.DiskSet()
         return diskSet[self.diskName].getVendorModelString()
     else:
         return self.partPath
Exemple #12
0
def _usbOption(match):
    '''Handle the "ks=usb" and "ks=usb:<path>" option.'''

    try:
        ksFile = match.group(1)
    except IndexError:
        ksFile = "ks.cfg"

    firstTime = True
    while True:
        if not firstTime:
            # XXX Maybe we should just stop retrying after awhile?
            log.info("Insert a USB storage device that contains '%s' "
                     "file to perform a scripted install..." % ksFile)
            util.rawInputCountdown("\rrescanning in %2d second(s), "
                                   "press <enter> to rescan immediately", 10)
        firstTime = False

        diskSet = devices.DiskSet(forceReprobe=True)

        usbDisks = [disk for disk in diskSet.values()
                    if disk.driverName == devices.DiskDev.DRIVER_USB_STORAGE]

        if not usbDisks:
            log.info("") # XXX just for spacing
            log.warn("No USB storage found.")
            continue

        kickstartPath = os.path.join(USB_MOUNT_PATH, ksFile.lstrip('/'))

        if not os.path.exists(USB_MOUNT_PATH):
            os.makedirs(USB_MOUNT_PATH)

        for disk in usbDisks:
            for part in disk.partitions:
                if part.partitionId == -1:
                    continue

                if (part.getFsTypeName() not in ("ext2", "ext3", "vfat")):
                    # Don't try mounting partitions with filesystems that aren't
                    # likely to be on a usb key.
                    continue

                if util.mount(part.consoleDevicePath,
                              USB_MOUNT_PATH,
                              fsTypeName=part.getFsTypeName()):
                    log.warn("Unable to mount '%s'" % part.consoleDevicePath)
                    continue

                if os.path.exists(kickstartPath):
                    userchoices.addDriveUse(disk.name, 'kickstart')
                    return [('-s', kickstartPath)]

                if util.umount(USB_MOUNT_PATH):
                    failWithLog("Unable to umount '%s'" % USB_MOUNT_PATH)

        log.info("")
        log.warn("%s was not found on any attached USB storage." % ksFile)
Exemple #13
0
    def __init__(self, parent, skipEsxDevice=True):
        """Initialize using parent's environment.
        Generates self.storDevList - list of allowable storage devices.
        """
        super(ChooseDataStoreDevice, self).__init__()
        self.substep = self.start = self.showDevices
        self.scrollable = None

        self.parent = parent
        self.selectedDevice = None

        if skipEsxDevice:
            allowedDiskSet = pruneDiskSet(devices.DiskSet(),
                                          [self.parent.esxDeviceName])
        else:
            allowedDiskSet = devices.DiskSet()
        self.storDevList = storage_utils.getStorageList(
            allowedDiskSet, esxAndCos=not skipEsxDevice)
Exemple #14
0
def findGrubInstallDevice(slashBootPartition):
    '''Find the device (the disk) to install grub onto (write the MBR).
    In the future, this might return something other than the disk
    containing the /boot partition.  For example, a userchoices attribute
    may override the selection, or the policy might change to
    "the first device in GetOrderedDrives()".
    '''
    disks = devices.DiskSet()
    disk = disks.findDiskContainingPartition(slashBootPartition)
    assert disk, "Just found /boot partition, but then it's disk vanished!"
    return disk
Exemple #15
0
def grubDiskIndex(disk):
    '''Operates like grubDiskAndPartitionIndicies but it only cares about
    the disk index.
    '''
    disks = devices.DiskSet()
    orderedDrives = disks.getOrderedDrives()

    for diskIndex, candidateDisk in enumerate(orderedDrives):
        if candidateDisk == disk:
            return diskIndex

    raise KeyError('Disk not found in disk set: %s' % disk.name)
Exemple #16
0
    def __init__(self, partMode="basic"):
        super(EsxLocationWindow, self).__init__()
        self.storList = \
            storage_utils.getStorageList(devices.DiskSet(),
                                         vmfsSupport=(partMode=="basic"),
                                         esxAndCos=(partMode=="basic"))
        self.partMode = partMode  # basic or advanced
        self.driveName = None

        self.start = self.bldStorDisplayList
        self.substep = self.start
        self.scrollable = None
Exemple #17
0
    def __init__(self, controlState, xml):
        controlState.displayHeaderBar = True
        controlState.windowIcon = 'partitioning.png'
        controlState.windowTitle = "Service Console Virtual Disk Image"
        controlState.windowText = \
            "Configure the service console virtual disk image"

        global _resetPartitions, _datastoreDevice

        # reset the vmdk partitions if the datastore device has been changed
        if userchoices.getEsxDatastoreDevice() != _datastoreDevice:
            _resetPartitions = True

        _datastoreDevice = userchoices.getEsxDatastoreDevice()

        self.xml = xml
        self.diskSet = devices.DiskSet()

        self.maxVmdkSize = devices.runtimeActionFindMaxVmdkSize()

        self.consoleVMSizeLabel = xml.get_widget("SetupvmdksizeLabel")
        self.view = xml.get_widget("SetupvmdkTreeView")
        self.scrolled = xml.get_widget("SetupvmdkScrolledWindow")

        # Download the package data so we can figure out the minimum partition
        # sizes
        weaselConfig = systemsettings.WeaselConfig()
        packagesXML = packages.getPackagesXML(weaselConfig.packageGroups)
        packageData = packages.PackageData(packagesXML.fullInstallDepot)

        self.fileSizes = packageData.fileDict

        self.requests = None
        self.newButton = xml.get_widget("SetupvmdkNewButton")
        self.deleteButton = xml.get_widget("SetupvmdkDeleteButton")

        if _resetPartitions:
            self._resetPartitions()
            _resetPartitions = False
            
        self.setupVirtualDevice()

        connectSignalHandlerByDict(self, SetupVmdkWindow, self.xml,
          { ('SetupvmdkNewButton', 'clicked') : 'newPartition',
            ('SetupvmdkEditButton', 'clicked') : 'editPartition',
            ('SetupvmdkDeleteButton', 'clicked') : 'deletePartition',
            ('SetupvmdkResetButton', 'clicked') : 'resetPartitions',
          })

        self.partitionWindow = PartitionWindow(xml, self)

        self.setButtons()
def getDeviceHasExistingDataText(deviceName):
    foundEsx = devices.runtimeActionFindExistingEsx(deviceName)

    foundVmfs = False

    for part in devices.DiskSet()[deviceName].partitions:
        if part.nativeType == 0xfb:
            foundVmfs = True
            break

    if foundEsx and foundVmfs:
        warnText = """ARE YOU TRYING TO PERFORM AN UPGRADE?

The selected storage device contains an existing ESX installation and
datastore. Continuing installation on this storage device will RESULT IN
DATA LOSS, causing any ESX settings and virtual machines to be lost.

To UPGRADE the existing installation without incurring data loss, use
the vSphere Host Update Utility installed along with vSphere Client or
use vCenter Update Manager.\n"""
    elif foundEsx:
        warnText = """ARE YOU TRYING TO PERFORM AN UPGRADE?

The selected storage device contains an existing ESX installation.
Continuing installation on this storage device will RESULT IN DATA LOSS,
causing any ESX settings to be lost.

To UPGRADE the existing installation without incurring data loss, use
the vSphere Host Update Utility installed along with vSphere Client or
use vCenter Update Manager.\n"""
    elif foundVmfs:
        warnText = """DATA LOSS WARNING:

The selected storage device contains a datastore that will be erased 
before installing ESX. Continuing installation will cause any virtual
machines on this datastore to be lost. If you want to save this content,
please cancel out and choose another option.\n"""
    else:
        warnText = """DATA LOSS WARNING:

The contents of the selected storage device will be erased before
installing ESX. All existing data will be lost. If you want to save this
content, please cancel out and choose another option.\n"""

    return warnText
Exemple #19
0
def promptDeviceHasExistingData(deviceName, allowPreserve=True):
    foundVmfs = False
    foundEsx = False
    foundVmfs2 = False

    datastoreName = ""

    foundEsx = devices.runtimeActionFindExistingEsx(deviceName)

    datastoreSet = datastore.DatastoreSet()

    for part in devices.DiskSet()[deviceName].partitions:
        if part.nativeType == 0xfb:
            foundVmfs = True
            break

    # if we found vmfs2 partitions don't attempt to preserve them
    if foundVmfs:
        datastores = datastoreSet.getEntriesByDriveName(deviceName)
        if len(datastores) > 0:
            datastoreName = datastores[0].name
        else:
            foundVmfs2 = True

    if foundEsx and foundVmfs and allowPreserve and not foundVmfs2:
        return PreserveDatastoreWindow(datastoreName).run()
    elif foundEsx and foundVmfs and not foundVmfs2:
        text = STORAGE_DATASTORE_TEXT % datastoreName
        return ConfirmDatastoreDeletionWindow(text).run()
    elif foundEsx and not foundVmfs2:
        text = STORAGE_ESX_TEXT
    elif foundVmfs:
        text = STORAGE_DATASTORE_VMFS2_TEXT
        if datastoreName:
            text = STORAGE_DATASTORE_TEXT % datastoreName
        return ConfirmDatastoreDeletionWindow(text).run()
    else:
        text = STORAGE_TEXT

    window = MessageWindow(None, '', text, type='okcancel', useMarkup=True)
    if window.affirmativeResponse:
        return EXISTING_DATA_CLEAR_DRIVE

    return EXISTING_DATA_STAY_ON_SCREEN
def validateScriptedInstallValidate(fileName, 
                                    expResult=Result.SUCCESS, 
                                    expErrors=[], expWarnings=[],
                                    expVerify=[]):
    configToLoad = DEFAULT_CONFIG_NAME
    
    # XXX Need to do a reload here to restore defaults since the tests will
    # update userchoices.
    reload(userchoices)

    try:
        fauxroot.FAUXROOT = [configToLoad]
        # XXX Need to force a reprobe since the disk config might change.
        devices.DiskSet(forceReprobe=True)
        si = ScriptedInstallPreparser(fileName)
        si.warnedPhysicalPartition = True # XXX Take this out
        (result, errors, warnings) = si.parseAndValidate()

        if not errors:
            writeAction(None)
    finally:
        # Leave the fauxroot turned on if it's needed by the test, mostly we
        # just need it for the device scan.
        fauxroot.FAUXROOT = None
    
    print "Expected...."
    print expResult.__str__()
    print expErrors.__str__()
    print expWarnings.__str__()

    print "Actuall...."
    print fileName
    print result.__str__()
    print errors.__str__()
    print warnings.__str__()

    assert result == expResult
    assert validateListContents(errors, expErrors) == 1
    assert validateListContents(warnings, expWarnings) == 1

    for v in expVerify:
        # Evaluate the verify expression, use the current globals and add a
        # local named 'sip' that contains a reference to the parser object.
        assert eval(v, globals(), { 'sip' : si }), v
Exemple #21
0
    def __init__(self, drive):
        CommonWindow.__init__(self)
        gladePath = os.path.join(os.path.dirname(__file__),
                                 'glade/storage-widgets.glade')
        self.xml = gtk.glade.XML(gladePath)

        self.drive = drive
        self.diskSet = devices.DiskSet()
        self.disk = self.diskSet[drive]
        self.datastoreSet = datastore.DatastoreSet()

        self.dialog = self.xml.get_widget('details')

        self.setLabels()

        self.addFrameToWindow()

        self.dialog.set_position(gtk.WIN_POS_CENTER)
        self.dialog.show_all()
Exemple #22
0
def getEligibleDisks(disks=None, vmfsSupport=True, esxAndCos=True):
    '''Return a list of DiskDevs that are supported and large enough to
    support the default installation.'''

    if disks is None:
        disks = devices.DiskSet()

    defaultRequests = list(DEFAULT_PHYSICAL_REQUESTS)
    if vmfsSupport and esxAndCos:
        minSizeInMB = getRequestsSize(defaultRequests + getDefaultVirtualRequests()) + \
                      devices.VMDK_OVERHEAD_SIZE
    elif vmfsSupport and not esxAndCos:
        minSizeInMB = getRequestsSize(getDefaultVirtualRequests()) + \
                      devices.VMDK_OVERHEAD_SIZE
    else:
        minSizeInMB = getRequestsSize(defaultRequests)

    maxSizeInMB = 2 * 1024 * 1024  # 2 TB

    retval = []
    for disk in disks.values():
        log.debug("checking disk for install eligibility -- %s" % str(disk))

        if vmfsSupport and not disk.supportsVmfs:
            log.debug("  vmfs not supported")
            continue

        if disk.getSizeInMegabytes() < minSizeInMB:
            log.debug("  too small")
            continue

        if disk.getSizeInMegabytes() >= maxSizeInMB:  # XXX bug #290262
            log.debug("  too big")
            continue

        if disk.name in userchoices.getDrivesInUse():
            log.debug("  already in use")
            continue

        log.debug("  disk is eligible")
        retval.append(disk)

    return retval
Exemple #23
0
def _ksFileUUIDOption(match):
    uuid = match.group(1)
    path = match.group(2)

    diskSet = devices.DiskSet(forceReprobe=True)
    diskPartTuple = diskSet.findFirstPartitionMatching(uuid=uuid)
    if diskPartTuple:
        disk, _part = diskPartTuple
        userchoices.addDriveUse(disk.name, 'kickstart')
        
    mountPath = os.path.join(UUID_MOUNT_PATH, uuid)
    if not os.path.exists(mountPath):
        os.makedirs(mountPath)
        if util.mount(uuid, mountPath, isUUID=True):
            os.rmdir(mountPath)
            failWithLog("error: cannot mount partition with UUID: %s\n" % uuid)

    ksPath = os.path.join(mountPath, path[1:])
    return [('-s', ksPath)]
Exemple #24
0
    def __init__(self):
        super(SetupVmdkWindow, self).__init__()
        self.substep = self.start

        self.diskSet = devices.DiskSet()
        self.maxVmdkSize = devices.runtimeActionFindMaxVmdkSize()

        self.requests = None

        # Download the package data so we can figure out the minimum partition
        # sizes
        weaselConfig = systemsettings.WeaselConfig()
        packagesXML = packages.getPackagesXML(weaselConfig.packageGroups)
        packageData = packages.PackageData(packagesXML.fullInstallDepot)

        self.fileSizes = packageData.fileDict

        if not userchoices.getVirtualDevices():
            self.reset()
        else:
            self.setupVirtualDevice()
    def __init__(self, controlState, xml):
        controlState.displayHeaderBar = True
        controlState.windowIcon = 'datastore.png'
        controlState.windowTitle = "Datastore"
        controlState.windowText = "Specify a datastore for ESX"

        self.xml = xml

        self.diskSet = devices.DiskSet()
        self.datastoreSet = datastore.DatastoreSet()

        self.datastoreExistTable = xml.get_widget("DatastoreexistingTable")
        self.datastoreCreateTable = xml.get_widget("DatastorecreateTable")

        connectSignalHandlerByDict(
            self, DataStoreWindow, self.xml, {
                ('DatastoredeviceButton', 'clicked'): 'createNewDatastore',
                ('DatastorepartitionButton', 'clicked'): 'selectDatastore',
                ('DatastorecreateRadioButton', 'toggled'):
                'toggleDatastoreChoice',
                ('DatastoreCheckButton', 'toggled'): 'toggleSameDevice',
            })

        self.defaultDeviceName = userchoices.getEsxPhysicalDevice()

        # set up the aux. helper windows
        self.createDataStoreWindow = \
            CreateDataStoreWindow(self.xml, self.diskSet, self)
        self.selectDataStoreWindow = \
            SelectDataStoreWindow(self.xml, self.datastoreSet, self)

        # find the existing vmdk size that we're going to remove
        vmdkPath = userchoices.getExistingVmdkLocation().get('vmdkLocation')
        self.vmdkSize = devices.runtimeActionFindExistingVmdkSize(vmdkPath)

        self.preserveVmfs = bool(userchoices.getPartitionMountRequests())

        if userchoices.getResetEsxLocation():
            self.setup()
            userchoices.setResetEsxLocation(False)
Exemple #26
0
    def addPartRequest(self):
        """Add the default partition request.  May be configured for
        basic or advanced."""

        self.popSubstep()  # kludge, pop state from warn()

        # schedule default partition operation
        request = devices.DiskSet()[self.driveName]
        if self.partMode == 'basic':
            partition.addDefaultPartitionRequests(request)
        else:  # partMode == 'advanced'
            partition.addDefaultPartitionRequests(request,
                                                  addVirtualPartitions=False)

        # If ESX location is changing (or this is first time), tell
        # DataStoreWindow via userchoices so it can clear options.
        if self.driveName != userchoices.getEsxPhysicalDevice():
            userchoices.setResetEsxLocation(True)
        else:
            userchoices.setResetEsxLocation(False)

        self.setSubstepEnv({'next': self.stepForward})
def validateComplexValidate(fileName):
    (result, errors, warnings, verify) = \
             buildExpectedResultSet(fileName)
    validateScriptedInstallValidate(fileName, result, errors, warnings, verify)

    if False and not errors:
        # XXX The following should check the generated ks.cfg file, but it does
        # not work quite right.  Just checking the results is not enough and
        # any default settings will be filled so there won't be any warnings
        # about the defaults being used (same for deprecated commands, unknown
        # commands, and so on).  Checking userchoices does not quite work
        # because we don't have __str__ methods on all the objects and some
        # unrelated quirks cause other problems (unicode and shlex not getting
        # along).
        
        savedChoices = re.sub(r'0x\w+', 'XXX', userchoices.dumpToString())
        reload(userchoices)

        try:
            fauxroot.FAUXROOT = [DEFAULT_CONFIG_NAME]
            # XXX Need to force a reprobe since the disk config might change.
            devices.DiskSet(forceReprobe=True)
            si = ScriptedInstallPreparser("/mnt/sysimage/root/ks.cfg")
            (result, errors, warnings) = si.parseAndValidate()
            
            newChoices = re.sub(r'0x\w+', 'XXX', userchoices.dumpToString())

            import difflib
            for line in difflib.unified_diff(
                savedChoices.split('\n'), newChoices.split('\n')):
                print line
            assert savedChoices == newChoices
        finally:
            fauxroot.FAUXROOT = None

    # XXX Need to be nice to other tests, do another reload...
    reload(userchoices)
    def __init__(self, controlState, xml):
        controlState.displayHeaderBar = True
        controlState.windowTitle = "ESX Storage Device"
        controlState.windowText = "Select a location to install ESX"
        controlState.windowIcon = "drive.png"

        self.controlState = controlState
        self.xml = xml

        self.view = xml.get_widget("InstalllocationView")
        self.scrolled = xml.get_widget("InstalllocationScrolled")

        storage_widgets.setupStorageView(self.view)

        model = storage_widgets.populateStorageModel(self.view, self.scrolled,
                                                     devices.DiskSet())

        storage_widgets.findFirstSelectableRow(model, self.view,
                                               SUPPORTED_DISK_ENTRY)

        connectSignalHandlerByDict(
            self, InstallLocationWindow, self.xml, {
                ('InstalllocationDetailsButton', 'clicked'): 'showDetails',
            })
Exemple #29
0
 def _getDevice(self):
     if self._deviceObj or self.deviceName:
         return self._deviceObj or devices.DiskSet()[self.deviceName]
     else:
         return None
Exemple #30
0
    for request in requests:
        if not request.mountPoint:
            continue

        mountPoint = os.path.normpath(consts.HOST_ROOT + request.mountPoint)
        if os.path.exists(mountPoint):
            log.debug("Unmounting %s" % (mountPoint))
            util.umount(mountPoint)


if __name__ == "__main__":
    import doctest
    doctest.testmod()

    diskSet = devices.DiskSet()
    disks = diskSet.keys()
    disks.sort()

    #    for entry in diskSet["vmhba32:0:0"].partitions:
    #        print "%d: start=%d end=%d size=%d" % (entry.partitionId, entry.startSector, entry.endSector, entry.getLength())

    requests = PartitionRequestSet(deviceName="vmhba32:0:0")

    #requests.append(PartitionRequest(minimumSize=100, maximumSize=100))
    #requests.append(PartitionRequest(minimumSize=256, maximumSize=256))
    #requests.append(PartitionRequest(minimumSize=3000, maximumSize=3000))

    requests.append(PartitionRequest(minimumSize=100, grow=True))
    requests.append(PartitionRequest(minimumSize=100, maximumSize=100))
    requests.append(