Example #1
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
Example #2
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
Example #3
0
def hostActionRebuildInitrd(context):
    context.cb.pushStatusGroup(1)
    context.cb.pushStatus('Checking if the initial ramdisk has to be rebuilt')
    # If nothing has changed then this is a noop.
    execCommand("%s --rebuild -b --update-trouble" % cmd_esxcfgboot,
                root=instRoot)
    context.cb.popStatus()
    context.cb.popStatusGroup()
Example #4
0
def hostActionRebuildInitrd(context):
    context.cb.pushStatusGroup(1)
    context.cb.pushStatus('Checking if the initial ramdisk has to be rebuilt')
    # If nothing has changed then this is a noop.
    execCommand("%s --rebuild -b --update-trouble" % cmd_esxcfgboot,
                root=instRoot)
    context.cb.popStatus()
    context.cb.popStatusGroup()
Example #5
0
def makeInitialRamdisk(stringSubstitutionDict):
    '''Makes the initial ramdisk.'''
    #these 2 should go away soon...
    os.system('touch %s/etc/vmware/sysboot.conf' % instRoot)

    # actually do the mkinitrd
    log.info('Making initrd: ' + cmd_esxcfgboot)
    execCommand("%s -b --update-trouble" % cmd_esxcfgboot, root=instRoot)
Example #6
0
def makeInitialRamdisk(stringSubstitutionDict):
    '''Makes the initial ramdisk.'''
    #these 2 should go away soon...
    os.system('touch %s/etc/vmware/sysboot.conf' % instRoot);

    # actually do the mkinitrd
    log.info('Making initrd: ' + cmd_esxcfgboot)
    execCommand("%s -b --update-trouble" % cmd_esxcfgboot, root=instRoot)
Example #7
0
def WriteMissingNetworkConfigFiles():
    # dhclient writes to /etc/ntp.conf with any ntp servers it 
    # discovers, but only if the ntp.conf file already exists.
    util.execCommand('touch /etc/ntp.conf')
    
    if not os.path.exists('/etc/xinetd.d'):
        # XXX Used by NetworkInfoImpl::SetCosIpv6Enabled().
        os.makedirs('/etc/xinetd.d')
Example #8
0
def WriteMissingNetworkConfigFiles():
    # dhclient writes to /etc/ntp.conf with any ntp servers it
    # discovers, but only if the ntp.conf file already exists.
    util.execCommand('touch /etc/ntp.conf')

    if not os.path.exists('/etc/xinetd.d'):
        # XXX Used by NetworkInfoImpl::SetCosIpv6Enabled().
        os.makedirs('/etc/xinetd.d')
Example #9
0
def hostActionPostScript(context):
    postScripts = userchoices.getPostScripts()
    if not postScripts:
        return

    # Setup /dev in the installed system.
    # XXX There still might be a few other things in rc.sysinit we'll need to
    # do.
    util.execCommand('/sbin/start_udev', root=HOST_ROOT)

    for postScript in postScripts:
        postScript['script'].run(HOST_ROOT)
Example #10
0
def hostActionPostScript(context):
    postScripts = userchoices.getPostScripts()
    if not postScripts:
        return

    # Setup /dev in the installed system.
    # XXX There still might be a few other things in rc.sysinit we'll need to
    # do.
    util.execCommand('/sbin/start_udev', root=HOST_ROOT)

    for postScript in postScripts:
        postScript['script'].run(HOST_ROOT)
Example #11
0
def hostActionMountPseudoFS(_context):
    '''Many executables/packages depend on the /proc filesystem to be present.
    For example, mkinitrd depends on /proc.
    This function creates the /proc, /sys, and /dev directories in the instRoot
    and mounts proc and sysfs.
    '''

    for fsdir in ["/proc", "/sys", "/dev"]:
        path = os.path.join(HOST_ROOT, fsdir.lstrip('/'))
        if not os.path.exists(path):
            os.makedirs(path)
    util.execCommand('/usr/bin/mount -t proc /proc %s/proc' % HOST_ROOT)
    util.execCommand('/usr/bin/mount -t sysfs /sys %s/sys' % HOST_ROOT)
Example #12
0
def hostActionMountPseudoFS(_context):
    '''Many executables/packages depend on the /proc filesystem to be present.
    For example, mkinitrd depends on /proc.
    This function creates the /proc, /sys, and /dev directories in the instRoot
    and mounts proc and sysfs.
    '''

    for fsdir in ["/proc", "/sys", "/dev"]:
        path = os.path.join(HOST_ROOT, fsdir.lstrip('/'))
        if not os.path.exists(path):
            os.makedirs(path)
    util.execCommand('/usr/bin/mount -t proc /proc %s/proc' % HOST_ROOT)
    util.execCommand('/usr/bin/mount -t sysfs /sys %s/sys' % HOST_ROOT)
Example #13
0
def migrateClock(oldPath, newPath, accum):
    _rc, utc, _stderr = util.execCommand(". %s && echo $UTC" % oldPath)
    utc = utc.strip()
    
    isUTC = utc.lower() not in ["false", "0"]
    if isUTC:
        return migrateTimezone(oldPath, newPath, accum)

    shutil.copyfile(oldPath, oldPath + ".backup")
    
    # The vmkernel expects the hw clock to be set to UTC time, so we need
    # to update it.
    log.info("changing hardware clock to UTC time")
    newContents = ""
    for line in open(oldPath):
        if line.lstrip().startswith('UTC'):
            newContents += "# UTC changed to true during upgrade\n"
            newContents += "UTC=true\n"
        else:
            newContents += line
    # Change the file in 3.x, so the time is still right on rollback.
    open(oldPath, "w").write(newContents)

    retval = migrateTimezone(oldPath, newPath, accum)

    # migrateTimezone can write a new clock file with a different ZONE
    # value, so we have to read the new one in that case.
    if os.path.exists(newPath):
        clockPath = newPath
    else:
        clockPath = oldPath
    _rc, zoneName, _stderr = util.execCommand(
        ". %s && echo $ZONE" % clockPath)
    zoneName = zoneName.strip()

    # Change the timezone used by python.
    os.environ['TZ'] = zoneName
    time.tzset()

    # Get the current time in seconds, which is really in the current
    # timezone, and use the timezone to change the hwclock to UTC time.
    secsFromEpochLocal = time.time()
    secsFromEpochUTC = secsFromEpochLocal + time.timezone
    timeTuple = time.gmtime(secsFromEpochUTC)[:6]
    timedate.setHardwareClock(timeTuple)
    
    os.environ['TZ'] = ''
    time.tzset()
        
    return retval
Example #14
0
def migrateClock(oldPath, newPath, accum):
    _rc, utc, _stderr = util.execCommand(". %s && echo $UTC" % oldPath)
    utc = utc.strip()

    isUTC = utc.lower() not in ["false", "0"]
    if isUTC:
        return migrateTimezone(oldPath, newPath, accum)

    shutil.copyfile(oldPath, oldPath + ".backup")

    # The vmkernel expects the hw clock to be set to UTC time, so we need
    # to update it.
    log.info("changing hardware clock to UTC time")
    newContents = ""
    for line in open(oldPath):
        if line.lstrip().startswith('UTC'):
            newContents += "# UTC changed to true during upgrade\n"
            newContents += "UTC=true\n"
        else:
            newContents += line
    # Change the file in 3.x, so the time is still right on rollback.
    open(oldPath, "w").write(newContents)

    retval = migrateTimezone(oldPath, newPath, accum)

    # migrateTimezone can write a new clock file with a different ZONE
    # value, so we have to read the new one in that case.
    if os.path.exists(newPath):
        clockPath = newPath
    else:
        clockPath = oldPath
    _rc, zoneName, _stderr = util.execCommand(". %s && echo $ZONE" % clockPath)
    zoneName = zoneName.strip()

    # Change the timezone used by python.
    os.environ['TZ'] = zoneName
    time.tzset()

    # Get the current time in seconds, which is really in the current
    # timezone, and use the timezone to change the hwclock to UTC time.
    secsFromEpochLocal = time.time()
    secsFromEpochUTC = secsFromEpochLocal + time.timezone
    timeTuple = time.gmtime(secsFromEpochUTC)[:6]
    timedate.setHardwareClock(timeTuple)

    os.environ['TZ'] = ''
    time.tzset()

    return retval
Example #15
0
def migrateTimezone(oldPath, newPath, _accum):
    zoneInfoPath = "/usr/share/zoneinfo/"

    # First, check to see if the clock file and localtime are in sync.
    _rc, zoneName, _stderr = util.execCommand(". %s && echo $ZONE" % oldPath)
    zoneName = zoneName.strip()
    
    zonePath = os.path.join(consts.HOST_ROOT,
                            consts.ESX3_INSTALLATION.lstrip('/'),
                            zoneInfoPath.lstrip('/'),
                            zoneName.lstrip('/'))
    oldLocaltime = os.path.join(consts.HOST_ROOT,
                                consts.ESX3_INSTALLATION.lstrip('/'),
                                "etc/localtime")

    if not os.path.lexists(oldLocaltime):
        log.debug("no /etc/localtime, assuming clock file is good")
        return True
    
    try:
        if filecmp.cmp(oldLocaltime, zonePath):
            log.debug("ZONE value in clock file matches /etc/localtime")
            return True
    except Exception, e:
        log.debug("unable to compare localtime with zoneinfo -- %s" % str(e))
Example #16
0
 def run(self, command=None):
     if not command:
         command = self.command
     if self.displayId != None:
         util.setDisplay(self.displayId)  # change to specific display
     else:
         print(f"ERROR: specified ({self.displayId}) display not found")
     util.setWorkspace(self.newWorkspace)  # optionally name new workspace
     return util.execCommand(command)
Example #17
0
def hostAction(_context):
    choices = userchoices.getESXFirewall()

    if choices:
        if choices['incoming'] == userchoices.ESXFIREWALL_ALLOW:
            incomingFlag = "--allowIncoming"
        else:
            incomingFlag = "--blockIncoming"
        if choices['outgoing'] == userchoices.ESXFIREWALL_ALLOW:
            outgoingFlag = "--allowOutgoing"
        else:
            outgoingFlag = "--blockOutgoing"

        try:
            util.execCommand("/usr/sbin/esxcfg-firewall %s %s" % (
                    incomingFlag, outgoingFlag),
                             root=HOST_ROOT,
                             raiseException=True)
        except Exception, e:
            raise InstallationError(
                "Could not change global firewall rules.", e)
Example #18
0
def hostAction(_context):
    choices = userchoices.getESXFirewall()

    if choices:
        if choices['incoming'] == userchoices.ESXFIREWALL_ALLOW:
            incomingFlag = "--allowIncoming"
        else:
            incomingFlag = "--blockIncoming"
        if choices['outgoing'] == userchoices.ESXFIREWALL_ALLOW:
            outgoingFlag = "--allowOutgoing"
        else:
            outgoingFlag = "--blockOutgoing"

        try:
            util.execCommand("/usr/sbin/esxcfg-firewall %s %s" %
                             (incomingFlag, outgoingFlag),
                             root=HOST_ROOT,
                             raiseException=True)
        except Exception, e:
            raise InstallationError("Could not change global firewall rules.",
                                    e)
Example #19
0
    def _checkNFSAvailable(self):
        if NFSMounter._nfsUp:
            return NFSMounter._nfsUp

        #TODO: this needs to change once these get sourced differently in scons
        execCommand('insmod /lib/sunrpc.ko')
        execCommand('insmod /lib/nfs_acl.ko')
        execCommand('insmod /lib/lockd.ko')
        execCommand('insmod /lib/nfs.ko')

        if not os.path.exists('/var/lock/subsys'):
            os.makedirs('/var/lock/subsys')
        NFSMounter._nfsUp = True
        return NFSMounter._nfsUp
Example #20
0
    def _checkNFSAvailable(self):
        if NFSMounter._nfsUp:
            return NFSMounter._nfsUp

        #TODO: this needs to change once these get sourced differently in scons
        execCommand('insmod /lib/sunrpc.ko')
        execCommand('insmod /lib/nfs_acl.ko')
        execCommand('insmod /lib/lockd.ko')
        execCommand('insmod /lib/nfs.ko')

        if not os.path.exists('/var/lock/subsys'):
            os.makedirs('/var/lock/subsys')
        NFSMounter._nfsUp = True
        return NFSMounter._nfsUp
Example #21
0
    def write(self, stringSubstitutionDict):
        choices = userchoices.getBoot()
        if choices and choices['doNotInstall']:
            log.info('Skipping the writing of the bootloader to disk')
            return

        self.__enter()

        cmd = cmd_grub % stringSubstitutionDict

        rc, stdout, stderr = execCommand(cmd)

        self.checkGrubOutput(stdout)

        self.__exit()
Example #22
0
    def write(self, stringSubstitutionDict):
        choices = userchoices.getBoot()
        if choices and choices['doNotInstall']:
            log.info('Skipping the writing of the bootloader to disk')
            return

        self.__enter()

        cmd = cmd_grub % stringSubstitutionDict

        rc, stdout, stderr = execCommand(cmd)

        self.checkGrubOutput(stdout)

        self.__exit()
Example #23
0
def runtimeActionMountMedia(uiDelegate=None):
    """Mounts the installation media."""

    if not uiDelegate:
        uiDelegate = MOUNT_MEDIA_DELEGATE

    log.info("attempting to mount install media")

    if userchoices.getMediaLocation():
        log.info("  remote media in use, nothing to mount...")
        return

    while True:
        media = userchoices.getMediaDescriptor()

        if not media:
            # Check for the default media setup by the init scripts.
            media = DEFAULT_MEDIA
            media.isMounted = isInstallMediaMounted()
            if not os.path.exists(media.partPath):
                # attempt to remount the cd-rom since it may have been a SCSI
                # CD-ROM drive
                rc, stdout, stderr = \
                    execCommand("cd / && INSTALLER=1 %s %s" % (INIT_WRAPPER,
                                CDROM_MOUNT_SCRIPT))
                if rc:
                    log.critical("%s was not created" % media.partPath)
                    uiDelegate.mountMediaNoDrive()
                    sys.exit(ExitCodes.IMMEDIATELY_REBOOT)
                else:
                    media.isMounted = True

        # Make sure the media is mounted up.
        try:
            media.mount()
            if isInstallMediaMounted():
                return
            media.umount()
        except Exception, e:
            log.error(str(e))
        media.eject()
        uiDelegate.mountMediaNoPackages()
Example #24
0
def migrateTimezone(oldPath, newPath, _accum):
    zoneInfoPath = "/usr/share/zoneinfo/"

    # First, check to see if the clock file and localtime are in sync.
    _rc, zoneName, _stderr = util.execCommand(". %s && echo $ZONE" % oldPath)
    zoneName = zoneName.strip()

    zonePath = os.path.join(consts.HOST_ROOT,
                            consts.ESX3_INSTALLATION.lstrip('/'),
                            zoneInfoPath.lstrip('/'), zoneName.lstrip('/'))
    oldLocaltime = os.path.join(consts.HOST_ROOT,
                                consts.ESX3_INSTALLATION.lstrip('/'),
                                "etc/localtime")

    if not os.path.lexists(oldLocaltime):
        log.debug("no /etc/localtime, assuming clock file is good")
        return True

    try:
        if filecmp.cmp(oldLocaltime, zonePath):
            log.debug("ZONE value in clock file matches /etc/localtime")
            return True
    except Exception, e:
        log.debug("unable to compare localtime with zoneinfo -- %s" % str(e))
Example #25
0
        "check for numeric input for keyboard selection"
        try:
            selected = self.getScrollChoice()
        except (IndexError, ValueError), msg:
            body = '\n'.join(['Input error', msg[0], TransMenu.Back])
            self.errorPushPop(self.uiTitle +' (Update)', body)
            return

        # register the choice
        try:
            name = self.scrollNames[selected]
            # TODO: handle kbd.runtimeAction
            kbd = self.keyboards.getKeyboardSettingsByName(name)
            userchoices.setKeyboard(kbd.keytable, kbd.name,
                kbd.model, kbd.layout, kbd.variant, kbd.options)
        except AttributeError:   # should only occur if keyboard.xml gets lost
            self.errorPushPop(self.uiTitle +' (Update)',
                exceptTextKeyboardNotFound + TransMenu.Back)
            return

        # if we get this far, set the keyboard
        table = str(kbd.keytable)       # convert from unicode to str.
        path = os.path.join(consoleKeymapDir, self.mapParent[table],
                            "%s.map.gz" % table)
        # want str here, not unicode; otherwise fails in caged_weasel.
        execCommand('loadkeys %s' % path)

        # choice accepted
        self.setSubstepEnv( {'next': self.askConfirm } )

Example #26
0
def hostAction(_context):
    for path in PATHS_TO_MIGRATE:
        migratePath(path)

    for cmd in CMDS_TO_RUN:
        util.execCommand(cmd, root=consts.HOST_ROOT)
Example #27
0
    def update(self):
        "check for numeric input for keyboard selection"
        try:
            selected = self.getScrollChoice()
        except (IndexError, ValueError), msg:
            body = '\n'.join(['Input error', msg[0], TransMenu.Back])
            self.errorPushPop(self.uiTitle + ' (Update)', body)
            return

        # register the choice
        try:
            name = self.scrollNames[selected]
            # TODO: handle kbd.runtimeAction
            kbd = self.keyboards.getKeyboardSettingsByName(name)
            userchoices.setKeyboard(kbd.keytable, kbd.name, kbd.model,
                                    kbd.layout, kbd.variant, kbd.options)
        except AttributeError:  # should only occur if keyboard.xml gets lost
            self.errorPushPop(self.uiTitle + ' (Update)',
                              exceptTextKeyboardNotFound + TransMenu.Back)
            return

        # if we get this far, set the keyboard
        table = str(kbd.keytable)  # convert from unicode to str.
        path = os.path.join(consoleKeymapDir, self.mapParent[table],
                            "%s.map.gz" % table)
        # want str here, not unicode; otherwise fails in caged_weasel.
        execCommand('loadkeys %s' % path)

        # choice accepted
        self.setSubstepEnv({'next': self.askConfirm})
Example #28
0
def extractDriver(fileName):
    args = 'cd "%s" && rpm2cpio "%s" | cpio -id' % (DRIVER_UNPACK_DIR, fileName)
    log.debug("extracting %s" % fileName)
    rc, stdout, stderr = execCommand(args, raiseException=True)
    return rc
Example #29
0
        macAddress.GetStringAddress():
            try:
                vswitch.AddUplink(pnic.GetName())
            except vmkctl.HostCtlException, ex:
                log.debug("vswitch.addUplink("+pnic.GetName()+"): " + \
                          str(ex.GetMessage()))
                raise

    try:
        newNic.Enable()
    except vmkctl.HostCtlException, ex:
        log.debug("newNic.Enable(): " + str(ex.GetMessage()))
        raise

    ## Used to be in /etc/rc.d/init.d
    util.execCommand('/init.d/41.vmkiscsi')
    log.debug("Just ran /init.d/41.vmkiscsi")

    log.debug("Rescanning LUNs...")
    iScsiIFs = vmkctl.StorageInfoImpl().GetiScsiInterfaces()
    if len(iScsiIFs) < 1:
        raise SystemError, "No iSCSI interfaces found, or found but their option "\
                           "ROMs are misconfigured.  Cannot configure iSCSI."
        # This could happen if 1) the NIC doesn't support iSCSI or (2) the data
        # in the NIC's option ROM doesn't make sense (in a way that the sanity
        # checks in validateIQN() didn't catch).

    ## TODO: we should scan only on sofware iScsi interfaces, but for the time being
    ## ScsiInterfaceImpl::IsSoftwareiScsi() doesn't work and Prasanna doesn't
    ## know when he'll be able to take care of that.
    for intf in iScsiIFs:
Example #30
0
def hostActionLoadDrivers(context):
    global DRIVERS_LOADED

    if DRIVERS_LOADED:
        return

    uiHook = context.cb

    # when in rome...
    f = open("/tmp/initscripts.sh", "w")
    f.write(FIND_INIT_SCRIPTS)
    f.close()

    initScripts = util.execWithCapture("/bin/bash", ["/bin/bash", "/tmp/initscripts.sh"])
    initScripts = initScripts.split()

    units = len(initScripts)
    uiHook.pushStatusGroup(units)

    criticalFailure = False

    scriptsFailed = []
    log.info("Starting driver load ...")
    for script in initScripts:
        script = os.path.basename(script)

        if _findBaseInitLevel(script) < INIT_START_LEVEL:
            continue

        log.info("Loading %s" % script)
        uiHook.pushStatus("Loading %s" % script)
        rc, stdout, stderr = execCommand("cd / && INSTALLER=1 %s %s" % (INIT_WRAPPER, script))

        if rc == 1:
            warningMessage = "The script %s returned status 1" % script
            log.warning(warningMessage)
        elif rc == 2:
            errorMessage = (
                "A non-critical error has happened in the "
                + "script %s.  The installation can continue " % script
                + "but you may experience reduced functionality."
            )
            log.error(errorMessage)
            scriptsFailed.append(script)
        elif rc == 3:
            errorMessage = "The script %s failed to execute " % (script) + "and the installation can not continue."
            criticalFailure = True
            break
        elif rc:
            errorMessage = "An unexpected error occurred in the " + "script %s." % script
            criticalFailure = True
            break

        uiHook.popStatus()

    if criticalFailure:
        log.error(errorMessage)
        uiHook.popStatus()
        uiHook.popStatusGroup()
        raise CriticalScriptLoadError(errorMessage)

    # XXX should be done by the init scripts...  the device nodes will get
    # created implicitly by devices.DiskSet() but not everything that needs
    # a device node goes through there.
    import partition

    partition.createDeviceNodes()

    DRIVERS_LOADED = True

    uiHook.popStatusGroup()

    if scriptsFailed:
        messageText = SCRIPT_ERROR_MSG % ", ".join(scriptsFailed)
        raise ScriptLoadError(messageText)
Example #31
0
 def control(self, value):
     return util.execCommand(self.command % (value, ))
Example #32
0
 def close(self):
     util.setDisplay(self.displayId)  # change to specific display
     util.execCommand("sway kill")
Example #33
0
 def close(self):
     util.execCommand(self.releaseCommand)
Example #34
0
def hostAction(_context):
    for path in PATHS_TO_MIGRATE:
        migratePath(path)

    for cmd in CMDS_TO_RUN:
        util.execCommand(cmd, root=consts.HOST_ROOT)
Example #35
0
def extractDriver(fileName):
    args = 'cd "%s" && rpm2cpio "%s" | cpio -id' % \
        (DRIVER_UNPACK_DIR, fileName)
    log.debug("extracting %s" % fileName)
    rc, stdout, stderr = execCommand(args, raiseException=True)
    return rc
Example #36
0
def hostActionLoadDrivers(context):
    global DRIVERS_LOADED

    if DRIVERS_LOADED:
        return

    uiHook = context.cb

    # when in rome...
    f = open('/tmp/initscripts.sh', 'w')
    f.write(FIND_INIT_SCRIPTS)
    f.close()

    initScripts = util.execWithCapture('/bin/bash',
                                       ['/bin/bash', '/tmp/initscripts.sh'])
    initScripts = initScripts.split()

    units = len(initScripts)
    uiHook.pushStatusGroup(units)

    criticalFailure = False

    scriptsFailed = []
    log.info("Starting driver load ...")
    for script in initScripts:
        script = os.path.basename(script)

        if _findBaseInitLevel(script) < INIT_START_LEVEL:
            continue

        log.info("Loading %s" % script)
        uiHook.pushStatus("Loading %s" % script)
        rc, stdout, stderr = \
            execCommand("cd / && INSTALLER=1 %s %s" % (INIT_WRAPPER, script))

        if rc == 1:
            warningMessage = "The script %s returned status 1" % script
            log.warning(warningMessage)
        elif rc == 2:
            errorMessage = "A non-critical error has happened in the " + \
                    "script %s.  The installation can continue " % script + \
                    "but you may experience reduced functionality."
            log.error(errorMessage)
            scriptsFailed.append(script)
        elif rc == 3:
            errorMessage = "The script %s failed to execute " % (script) + \
                           "and the installation can not continue."
            criticalFailure = True
            break
        elif rc:
            errorMessage = "An unexpected error occurred in the " + \
                           "script %s." % script
            criticalFailure = True
            break

        uiHook.popStatus()

    if criticalFailure:
        log.error(errorMessage)
        uiHook.popStatus()
        uiHook.popStatusGroup()
        raise CriticalScriptLoadError(errorMessage)

    # XXX should be done by the init scripts...  the device nodes will get
    # created implicitly by devices.DiskSet() but not everything that needs
    # a device node goes through there.
    import partition
    partition.createDeviceNodes()

    DRIVERS_LOADED = True

    uiHook.popStatusGroup()

    if scriptsFailed:
        messageText = SCRIPT_ERROR_MSG % ", ".join(scriptsFailed)
        raise ScriptLoadError(messageText)
Example #37
0
        macAddress.GetStringAddress():
            try:
                vswitch.AddUplink(pnic.GetName())
            except vmkctl.HostCtlException, ex:
                log.debug("vswitch.addUplink("+pnic.GetName()+"): " + \
                          str(ex.GetMessage()))
                raise

    try:
        newNic.Enable()
    except vmkctl.HostCtlException, ex:
        log.debug("newNic.Enable(): " + str(ex.GetMessage()))
        raise

    ## Used to be in /etc/rc.d/init.d
    util.execCommand('/init.d/41.vmkiscsi')
    log.debug("Just ran /init.d/41.vmkiscsi")

    log.debug("Rescanning LUNs...")
    iScsiIFs = vmkctl.StorageInfoImpl().GetiScsiInterfaces()
    if len(iScsiIFs) < 1:
        raise SystemError, "No iSCSI interfaces found, or found but their option "\
                           "ROMs are misconfigured.  Cannot configure iSCSI."
        # This could happen if 1) the NIC doesn't support iSCSI or (2) the data
        # in the NIC's option ROM doesn't make sense (in a way that the sanity
        # checks in validateIQN() didn't catch).

    ## TODO: we should scan only on sofware iScsi interfaces, but for the time being
    ## ScsiInterfaceImpl::IsSoftwareiScsi() doesn't work and Prasanna doesn't
    ## know when he'll be able to take care of that.
    for intf in iScsiIFs:
Example #38
0

def runtimeAction(year, month, day, hour, minute, seconds):
    '''This will set the system clock.'''
    try:
        year = int(year)
        month = int(month)
        day = int(day)
        hour = int(hour)
        minute = int(minute)
        seconds = int(seconds)
    except ValueError, ex:
        raise ValueError('time/date must be set with integer arguments')
    # this is the format that works with busybox
    tzName = getTimezoneName()
    execCommand('TZ="%s" date -s "%02d%02d%02d%02d%d.%02d"' %
                (tzName, month, day, hour, minute, year, seconds))


def carefullyCloseSocket():
    global _openSocket
    if _openSocket:
        try:
            _openSocket.shutdown(socket.SHUT_RDWR)
            _openSocket.close()
        except (EnvironmentError, socket.error), ex:
            log.info('Error while shuting down / closing socket')
            log.info('Error details: ' + str(ex))


def ntpQueryStart(server):
    global _openSocket