Exemple #1
0
    def installVirtualBox(self, oSession, oTxsSession):
        """
        Install VirtualBox in the guest.
        """
        fRc = False

        if self.sTestBuild is not None:
            reporter.log("Testing build: %s" % (self.sTestBuild))
            sTestBuildFilename = os.path.basename(self.sTestBuild)

            # Construct the .pkg filename from the tar.gz name.
            oMatch = re.search(r"\d+.\d+.\d+-SunOS-r\d+", sTestBuildFilename)
            if oMatch is not None:
                sPkgFilename = "VirtualBox-" + oMatch.group() + ".pkg"

                reporter.log("Extracted package filename: %s" % (sPkgFilename))

                fRc = self.oTestDriver.txsUploadFile(
                    oSession, oTxsSession, self.sTestBuild, "${SCRATCH}/" + sTestBuildFilename, cMsTimeout=120 * 1000
                )
                fRc = fRc and self.oTestDriver.txsUnpackFile(
                    oSession, oTxsSession, "${SCRATCH}/" + sTestBuildFilename, "${SCRATCH}", cMsTimeout=120 * 1000
                )
                fRc = fRc and self.oTestDriver.txsRunTest(
                    oTxsSession,
                    "Installing package",
                    240 * 1000,
                    "/usr/sbin/pkgadd",
                    ("pkgadd", "-d", "${SCRATCH}/" + sPkgFilename, "-n", "-a", "${SCRATCH}/autoresponse", "SUNWvbox"),
                )
        return fRc
Exemple #2
0
    def testIGuest_additionsVersion(self, oGuest):
        """
        Returns False if no version string could be obtained, otherwise True
        even though errors are logged.
        """
        try:
            sVer = oGuest.additionsVersion
        except:
            reporter.errorXcpt("Getting the additions version failed.")
            return False
        reporter.log('IGuest::additionsVersion="%s"' % (sVer,))

        if sVer.strip() == "":
            reporter.error("IGuest::additionsVersion is empty.")
            return False

        if sVer != sVer.strip():
            reporter.error('IGuest::additionsVersion is contains spaces: "%s".' % (sVer,))

        asBits = sVer.split(".")
        if len(asBits) < 3:
            reporter.error(
                'IGuest::additionsVersion does not contain at least tree dot separated fields: "%s" (%d).'
                % (sVer, len(asBits))
            )

        ## @todo verify the format.
        return True
    def _installExtPack(self):
        """ Installs the extension pack. """
        sVBox = self._getVBoxInstallPath(fFailIfNotFound = True);
        if sVBox is None:
            return False;
        sExtPackDir = os.path.join(sVBox, 'ExtensionPacks');

        if self._uninstallAllExtPacks() is not True:
            return False;

        sExtPack = self._findFile('Oracle_VM_VirtualBox_Extension_Pack.vbox-extpack');
        if sExtPack is None:
            sExtPack = self._findFile('Oracle_VM_VirtualBox_Extension_Pack.*.vbox-extpack');
        if sExtPack is None:
            return True;

        sDstDir = os.path.join(sExtPackDir, 'Oracle_VM_VirtualBox_Extension_Pack');
        reporter.log('Installing extension pack "%s" to "%s"...' % (sExtPack, sExtPackDir));
        fRc, _ = self._sudoExecuteSync([ self.getBinTool('vts_tar'),
                                         '--extract',
                                         '--verbose',
                                         '--gzip',
                                         '--file',                sExtPack,
                                         '--directory',           sDstDir,
                                         '--file-mode-and-mask',  '0644',
                                         '--file-mode-or-mask',   '0644',
                                         '--dir-mode-and-mask',   '0755',
                                         '--dir-mode-or-mask',    '0755',
                                         '--owner',               '0',
                                         '--group',               '0',
                                       ]);
        return fRc;
    def impersonate(self, sImpersonation):
        """
        Impersonate a given device.
        """

        # Clear any previous impersonation
        self._clearImpersonation();
        self.sImpersonation = sImpersonation;

        if sImpersonation == g_ksGadgetImpersonationInvalid:
            return False;
        elif sImpersonation == g_ksGadgetImpersonationTest:
            return self._loadModule('g_zero');
        elif sImpersonation == g_ksGadgetImpersonationMsd:
            # @todo: Not complete
            return self._loadModule('g_mass_storage');
        elif sImpersonation == g_ksGadgetImpersonationWebcam:
            # @todo: Not complete
            return self._loadModule('g_webcam');
        elif sImpersonation == g_ksGadgetImpersonationEther:
            return self._loadModule('g_ether');
        else:
            reporter.log('Invalid impersonation');

        return False;
Exemple #5
0
def logMemoryStats():
    """
    Logs windows memory stats.
    """
    class MemoryStatusEx(ctypes.Structure):
        """ MEMORYSTATUSEX """
        kaFields = [
            ( 'dwLength',                    ctypes.c_ulong ),
            ( 'dwMemoryLoad',                ctypes.c_ulong ),
            ( 'ullTotalPhys',                ctypes.c_ulonglong ),
            ( 'ullAvailPhys',                ctypes.c_ulonglong ),
            ( 'ullTotalPageFile',            ctypes.c_ulonglong ),
            ( 'ullAvailPageFile',            ctypes.c_ulonglong ),
            ( 'ullTotalVirtual',             ctypes.c_ulonglong ),
            ( 'ullAvailVirtual',             ctypes.c_ulonglong ),
            ( 'ullAvailExtendedVirtual',     ctypes.c_ulonglong ),
        ];
        _fields_ = kaFields; # pylint: disable=invalid-name

        def __init__(self):
            super(MemoryStatusEx, self).__init__();
            self.dwLength = ctypes.sizeof(self);

    try:
        oStats = MemoryStatusEx();
        ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(oStats));
    except:
        reporter.logXcpt();
        return False;

    reporter.log('Memory statistics:');
    for sField, _ in MemoryStatusEx.kaFields:
        reporter.log('  %32s: %s' % (sField, getattr(oStats, sField)));
    return True;
    def testSnapshotTreeDepth(self):
        """
        Test snapshot tree depth.
        """
        reporter.testStart('snapshotTreeDepth')

        try:
            oVM = self.createTestVM('test-snap', 1, None, 4)
            assert oVM is not None

            # modify the VM config, create and attach empty HDD
            oSession = self.openSession(oVM)
            sHddPath = os.path.join(self.sScratchPath, 'TestSnapEmpty.vdi')
            fRc = True
            fRc = fRc and oSession.createAndAttachHd(sHddPath, cb=1024*1024, sController='SATA Controller', fImmutable=False)
            fRc = fRc and oSession.saveSettings()

            # take 250 snapshots (snapshot tree depth limit)
            for i in range(1, 251):
                fRc = fRc and oSession.takeSnapshot('Snapshot ' + str(i))
            fRc = oSession.close() and fRc

            # unregister and re-register to test loading of settings
            sSettingsFile = oVM.settingsFilePath
            reporter.log('unregistering VM')
            oVM.unregister(vboxcon.CleanupMode_DetachAllReturnNone)
            oVBox = self.oVBoxMgr.getVirtualBox()
            reporter.log('opening VM %s, testing config reading' % (sSettingsFile))
            oVM = oVBox.openMachine(sSettingsFile)

            assert fRc is True
        except:
            reporter.errorXcpt()

        return reporter.testDone()[1] == 0
    def _sudoExecuteSync(self, asArgs, sInput):
        """
        Executes a sudo child process synchronously.
        Returns a tuple [True, 0] if the process executed successfully
        and returned 0, otherwise [False, rc] is returned.
        """
        reporter.log('Executing [sudo]: %s' % (asArgs, ));
        reporter.flushall();
        fRc = True;
        sOutput = '';
        sError = '';
        try:
            oProcess = utils.sudoProcessPopen(asArgs, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
                                              stderr=subprocess.PIPE, shell = False, close_fds = False);

            sOutput, sError = oProcess.communicate(sInput);
            iExitCode  = oProcess.poll();

            if iExitCode is not 0:
                fRc = False;
        except:
            reporter.errorXcpt();
            fRc = False;
        reporter.log('Exit code [sudo]: %s (%s)' % (fRc, asArgs));
        return (fRc, str(sOutput), str(sError));
    def isHostCpuAffectedByUbuntuNewAmdBug(self, oTestDrv):
        """
        Checks if the host OS is affected by older ubuntu installers being very
        picky about which families of AMD CPUs it would run on.

        The installer checks for family 15, later 16, later 20, and in 11.10
        they remove the family check for AMD CPUs.
        """
        if not oTestDrv.isHostCpuAmd():
            return False;
        try:
            (uMaxExt, _, _, _) = oTestDrv.oVBox.host.getProcessorCPUIDLeaf(0, 0x80000000, 0);
            (uFamilyModel, _, _, _) = oTestDrv.oVBox.host.getProcessorCPUIDLeaf(0, 0x80000001, 0);
        except:
            reporter.logXcpt();
            return False;
        if uMaxExt < 0x80000001 or uMaxExt > 0x8000ffff:
            return False;

        uFamily = (uFamilyModel >> 8) & 0xf
        if uFamily == 0xf:
            uFamily = ((uFamilyModel >> 20) & 0x7f) + 0xf;
        ## @todo Break this down into which old ubuntu release supports exactly
        ##       which AMD family, if we care.
        if uFamily <= 15:
            return False;
        reporter.log('Skipping "%s" because host CPU is a family %u AMD, which may cause trouble for the guest OS installer.'
                     % (self.sVmName, uFamily,));
        return True;
    def moveTo(self, sLocation, aoMediumAttachments):
        for oAttachment in aoMediumAttachments:
            try:
                oMedium = oAttachment.medium
                reporter.log('Move medium "%s" to "%s"' % (oMedium.name, sLocation,))
            except:
                reporter.errorXcpt('failed to get the medium from the IMediumAttachment "%s"' % (oAttachment))

            if self.oTstDrv.fpApiVer >= 5.3 and self.oTstDrv.uRevision > 124748:
                try:
                    oProgress = vboxwrappers.ProgressWrapper(oMedium.moveTo(sLocation), self.oTstDrv.oVBoxMgr, self.oTstDrv,
                                                             'move "%s"' % (oMedium.name,));
                except:
                    return reporter.errorXcpt('Medium::moveTo("%s") for medium "%s" failed' % (sLocation, oMedium.name,));
            else:
                try:
                    oProgress = vboxwrappers.ProgressWrapper(oMedium.setLocation(sLocation), self.oTstDrv.oVBoxMgr, self.oTstDrv,
                                                             'move "%s"' % (oMedium.name,));
                except:
                    return reporter.errorXcpt('Medium::setLocation("%s") for medium "%s" failed' % (sLocation, oMedium.name,));


            oProgress.wait()
            if oProgress.logResult() is False:
                return False
        return True
Exemple #10
0
    def impersonate(self, sImpersonation):
        """
        Impersonate a given device.
        """

        # Clear any previous impersonation
        self._clearImpersonation();
        self.sImpersonation = sImpersonation;

        if sImpersonation == 'Invalid':
            return False;
        elif sImpersonation == 'Test':
            return self._loadModule('g_zero');
        elif sImpersonation == 'Msd':
            # @todo: Not complete
            return self._loadModule('g_mass_storage');
        elif sImpersonation == 'Webcam':
            # @todo: Not complete
            return self._loadModule('g_webcam');
        elif sImpersonation == 'Network':
            return self._loadModule('g_ether');
        else:
            reporter.log('Invalid impersonation');

        return False;
    def testOneVmConfig(self, oVM, oTestVm):
        """
        Install guest OS and wait for result
        """

        self.logVmInfo(oVM)
        reporter.testStart('Installing %s' % (oTestVm.sVmName,))

        cMsTimeout = 40*60000;
        if not reporter.isLocal(): ## @todo need to figure a better way of handling timeouts on the testboxes ...
            cMsTimeout = 180 * 60000; # will be adjusted down.

        oSession, _ = self.startVmAndConnectToTxsViaTcp(oTestVm.sVmName, fCdWait = False, cMsTimeout = cMsTimeout);
        if oSession is not None:
            # The guest has connected to TXS, so we're done (for now anyways).
            reporter.log('Guest reported success')
            ## @todo Do save + restore.

            reporter.testDone()
            fRc = self.terminateVmBySession(oSession)
            return fRc is True

        reporter.error('Installation of %s has failed' % (oTestVm.sVmName,))
        oTestVm.detatchAndDeleteHd(self); # Save space.
        reporter.testDone()
        return False
    def installVirtualBox(self, oSession, oTxsSession):
        """
        Install VirtualBox in the guest.
        """
        fRc = False;

        if self.sTestBuild is not None:
            reporter.log('Testing build: %s' % (self.sTestBuild));
            sTestBuildFilename = os.path.basename(self.sTestBuild);

            # Construct the .pkg filename from the tar.gz name.
            oMatch = re.search(r'\d+.\d+.\d+-SunOS-r\d+', sTestBuildFilename);
            if oMatch is not None:
                sPkgFilename = 'VirtualBox-' + oMatch.group() + '.pkg';

                reporter.log('Extracted package filename: %s' % (sPkgFilename));

                fRc = self.oTestDriver.txsUploadFile(oSession, oTxsSession, self.sTestBuild, \
                                                     '${SCRATCH}/' + sTestBuildFilename, \
                                                     cMsTimeout = 120 * 1000);
                fRc = fRc and self.oTestDriver.txsUnpackFile(oSession, oTxsSession, \
                                                             '${SCRATCH}/' + sTestBuildFilename, \
                                                             '${SCRATCH}', cMsTimeout = 120 * 1000);
                fRc = fRc and self.oTestDriver.txsRunTest(oTxsSession, 'Installing package', 240 * 1000, \
                                                          '/usr/sbin/pkgadd',
                                                          ('pkgadd', '-d', '${SCRATCH}/' + sPkgFilename, \
                                                           '-n', '-a', '${SCRATCH}/autoresponse', 'SUNWvbox'));
        return fRc;
    def actionExecuteOnRunnigVM(self):
        if not self.importVBoxApi():
            return False;

        oVirtualBox = self.oVBoxMgr.getVirtualBox()
        oMachine = oVirtualBox.findMachine(self.sVMname)

        if oMachine == None:
            reporter.log("Machine '%s' is unknown" % (oMachine.name))
            return False

        if oMachine.state != self.oVBoxMgr.constants.MachineState_Running:
            reporter.log("Machine '%s' is not Running" % (oMachine.name))
            return False

        oSession = self.oVBoxMgr.mgr.getSessionObject(oVirtualBox)
        oMachine.lockMachine(oSession, self.oVBoxMgr.constants.LockType_Shared)

        self.doTest(oSession);

        oSession.unlockMachine()

        del oSession
        del oMachine
        del oVirtualBox
        return True
 def parseOption(self, asArgs, iArg):                                        # pylint: disable=R0912,R0915
     if asArgs[iArg] == '--storage-ctrls':
         iArg += 1;
         if iArg >= len(asArgs):
             raise base.InvalidOption('The "--storage-ctrls" takes a colon separated list of Storage controller types');
         self.asStorageCtrls = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--disk-formats':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--disk-formats" takes a colon separated list of disk formats');
         self.asDiskFormats = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--test-vms':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--test-vms" takes colon separated list');
         self.asTestVMs = asArgs[iArg].split(':');
         for s in self.asTestVMs:
             if s not in self.asTestVMsDef:
                 raise base.InvalidOption('The "--test-vms" value "%s" is not valid; valid values are: %s' \
                     % (s, ' '.join(self.asTestVMsDef)));
     elif asArgs[iArg] == '--skip-vms':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--skip-vms" takes colon separated list');
         self.asSkipVMs = asArgs[iArg].split(':');
         for s in self.asSkipVMs:
             if s not in self.asTestVMsDef:
                 reporter.log('warning: The "--test-vms" value "%s" does not specify any of our test VMs.' % (s));
     else:
         return vbox.TestDriver.parseOption(self, asArgs, iArg);
     return iArg + 1;
    def moveVMToLocation(self, sLocation, oVM):
        """
        Document me here, not with hashes above.
        """
        fRc = True
        try:

            ## @todo r=bird: Too much unncessary crap inside try clause.  Only oVM.moveTo needs to be here.
            ##               Though, you could make an argument for oVM.name too, perhaps.

            # move machine
            reporter.log('Moving machine "%s" to the "%s"' % (oVM.name, sLocation))
            sType = 'basic'
            oProgress = vboxwrappers.ProgressWrapper(oVM.moveTo(sLocation, sType), self.oTstDrv.oVBoxMgr, self.oTstDrv,
                                                     'moving machine "%s"' % (oVM.name,))

        except:
            return reporter.errorXcpt('Machine::moveTo("%s") for machine "%s" failed' % (sLocation, oVM.name,))

        oProgress.wait()
        if oProgress.logResult() is False:
            fRc = False
            reporter.log('Progress object returned False')
        else:
            fRc = True

        return fRc
Exemple #16
0
 def parseOption(self, asArgs, iArg):  # pylint: disable=R0912,R0915
     if asArgs[iArg] == "--test-build-dir":
         iArg += 1
         if iArg >= len(asArgs):
             raise base.InvalidOption('The "--test-build-dir" takes a path argument')
         self.sTestBuildDir = asArgs[iArg]
     elif asArgs[iArg] == "--test-vms":
         iArg += 1
         if iArg >= len(asArgs):
             raise base.InvalidOption('The "--test-vms" takes colon separated list')
         self.asTestVMs = asArgs[iArg].split(":")
         for s in self.asTestVMs:
             if s not in self.asTestVMsDef:
                 raise base.InvalidOption(
                     'The "--test-vms" value "%s" is not valid; valid values are: %s'
                     % (s, " ".join(self.asTestVMsDef))
                 )
     elif asArgs[iArg] == "--skip-vms":
         iArg += 1
         if iArg >= len(asArgs):
             raise base.InvalidOption('The "--skip-vms" takes colon separated list')
         self.asSkipVMs = asArgs[iArg].split(":")
         for s in self.asSkipVMs:
             if s not in self.asTestVMsDef:
                 reporter.log('warning: The "--test-vms" value "%s" does not specify any of our test VMs.' % (s))
     else:
         return vbox.TestDriver.parseOption(self, asArgs, iArg)
     return iArg + 1
Exemple #17
0
 def parseOption(self, asArgs, iArg):                                        # pylint: disable=R0912,R0915
     if asArgs[iArg] == '--virt-modes':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--virt-modes" takes a colon separated list of modes');
         self.asVirtModes = asArgs[iArg].split(':');
         for s in self.asVirtModes:
             if s not in self.asVirtModesDef:
                 raise base.InvalidOption('The "--virt-modes" value "%s" is not valid; valid values are: %s' \
                     % (s, ' '.join(self.asVirtModesDef)));
     elif asArgs[iArg] == '--cpu-counts':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--cpu-counts" takes a colon separated list of cpu counts');
         self.acCpus = [];
         for s in asArgs[iArg].split(':'):
             try: c = int(s);
             except: raise base.InvalidOption('The "--cpu-counts" value "%s" is not an integer' % (s,));
             if c <= 0:  raise base.InvalidOption('The "--cpu-counts" value "%s" is zero or negative' % (s,));
             self.acCpus.append(c);
     elif asArgs[iArg] == '--storage-ctrls':
         iArg += 1;
         if iArg >= len(asArgs):
             raise base.InvalidOption('The "--storage-ctrls" takes a colon separated list of Storage controller types');
         self.asStorageCtrls = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--disk-formats':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--disk-formats" takes a colon separated list of disk formats');
         self.asDiskFormats = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--disk-dirs':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--disk-dirs" takes a colon separated list of directories');
         self.asDirs = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--iscsi-targets':
         iArg += 1;
         if iArg >= len(asArgs):
             raise base.InvalidOption('The "--iscsi-targets" takes a colon separated list of iscsi targets');
         self.asIscsiTargets = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--tests':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--tests" takes a colon separated list of disk formats');
         self.asTests = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--test-vms':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--test-vms" takes colon separated list');
         self.asTestVMs = asArgs[iArg].split(':');
         for s in self.asTestVMs:
             if s not in self.asTestVMsDef:
                 raise base.InvalidOption('The "--test-vms" value "%s" is not valid; valid values are: %s' \
                     % (s, ' '.join(self.asTestVMsDef)));
     elif asArgs[iArg] == '--skip-vms':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--skip-vms" takes colon separated list');
         self.asSkipVMs = asArgs[iArg].split(':');
         for s in self.asSkipVMs:
             if s not in self.asTestVMsDef:
                 reporter.log('warning: The "--test-vms" value "%s" does not specify any of our test VMs.' % (s));
     else:
         return vbox.TestDriver.parseOption(self, asArgs, iArg);
     return iArg + 1;
 def test1Sub7(self, oVmSrc, oVmDst):
     """
     Test the password check.
     """
     reporter.testStart('Bad password')
     if    self.test1ResetVmConfig(oVmSrc, fTeleporterEnabled = False) \
       and self.test1ResetVmConfig(oVmDst, fTeleporterEnabled = True):
         # Start the target VM.
         oSessionDst, oProgressDst = self.startVmEx(
             oVmDst, fWait=False)
         if oSessionDst is not None:
             if oProgressDst.waitForOperation(iOperation=-3) == 0:
                 # Start the source VM.
                 oSessionSrc = self.startVm(oVmSrc)
                 if oSessionSrc is not None:
                     tsPasswords = (
                         'password-bad',
                         'passwor',
                         'pass',
                         'p',
                         '',
                         'Password',
                     )
                     for sPassword in tsPasswords:
                         reporter.testStart(sPassword)
                         oProgressSrc = oSessionSrc.teleport(
                             'localhost', 6502, sPassword)
                         if oProgressSrc:
                             oProgressSrc.wait()
                             reporter.log(
                                 'src: %s' % oProgressSrc.stringifyResult())
                             if oProgressSrc.isSuccess():
                                 reporter.testFailure(
                                     'IConsole::teleport succeeded with bad password "%s"'
                                     % sPassword)
                             elif oProgressSrc.getErrInfoResultCode(
                             ) != vbox.ComError.E_FAIL:
                                 reporter.testFailure('IConsole::teleport returns %s instead of E_FAIL' \
                                                      % (vbox.ComError.toString(oProgressSrc.getErrInfoResultCode()),))
                             elif oProgressSrc.getErrInfoText(
                             ) != 'Invalid password':
                                 reporter.testFailure('IConsole::teleport returns "%s" instead of "Invalid password"' \
                                                      % (oProgressSrc.getErrInfoText(),))
                             elif oProgressDst.isCompleted():
                                 reporter.testFailure('Destination completed unexpectedly after bad password "%s"' \
                                                      % sPassword)
                         else:
                             reporter.testFailure(
                                 'IConsole::teleport failed with password "%s"'
                                 % sPassword)
                         if reporter.testDone()[1] != 0:
                             break
                     self.terminateVmBySession(oSessionSrc, oProgressSrc)
             self.terminateVmBySession(oSessionDst, oProgressDst)
     else:
         reporter.testFailure('reconfig failed')
     return reporter.testDone()[1] == 0
    def _installVBox(self):
        """
        Download / copy the build files into the scratch area and install them.
        """
        reporter.testStart('Installing VirtualBox');
        reporter.log('CWD=%s' % (os.getcwd(),)); # curious

        #
        # Download the build files.
        #
        for i in range(len(self._asBuildUrls)):
            if webutils.downloadFile(self._asBuildUrls[i], self._asBuildFiles[i],
                                     self.sBuildPath, reporter.log, reporter.log) is not True:
                reporter.testDone(fSkipped = True);
                return None; # Failed to get binaries, probably deleted. Skip the test run.

        #
        # Unpack anything we know what is and append it to the build files
        # list.  This allows us to use VBoxAll*.tar.gz files.
        #
        for sFile in list(self._asBuildFiles):
            if self._maybeUnpackArchive(sFile, fNonFatal = True) is not True:
                reporter.testDone(fSkipped = True);
                return None; # Failed to unpack. Probably local error, like busy
                             # DLLs on windows, no reason for failing the build.

        #
        # Go to system specific installation code.
        #
        sHost = utils.getHostOs()
        if   sHost == 'darwin':     fRc = self._installVBoxOnDarwin();
        elif sHost == 'linux':      fRc = self._installVBoxOnLinux();
        elif sHost == 'solaris':    fRc = self._installVBoxOnSolaris();
        elif sHost == 'win':        fRc = self._installVBoxOnWindows();
        else:
            reporter.error('Unsupported host "%s".' % (sHost,));
        if fRc is False:
            reporter.testFailure('Installation error.');

        #
        # Install the extension pack.
        #
        if fRc is True  and  self._fAutoInstallPuelExtPack:
            fRc = self._installExtPack();
            if fRc is False:
                reporter.testFailure('Extension pack installation error.');

        # Some debugging...
        try:
            cMbFreeSpace = utils.getDiskUsage(self.sScratchPath);
            reporter.log('Disk usage after VBox install: %d MB available at %s' % (cMbFreeSpace, self.sScratchPath,));
        except:
            reporter.logXcpt('Unable to get disk free space. Ignored. Continuing.');

        reporter.testDone();
        return fRc;
 def __getLogFiles(self, oMachine, fPrint = False):
     asLogFilesList = set()
     sFolder = oMachine.logFolder
     for sFile in os.listdir(sFolder):
         if sFile.endswith(".log"):
             sFullPath = os.path.join(sFolder, sFile)
             asLogFilesList.add(sFullPath)
             if fPrint is True:
                 reporter.log("Log file is %s" % (sFullPath))
     return asLogFilesList
 def __getSnapshotsFiles(self, oMachine, fPrint = False):
     asSnapshotsFilesList = set()
     sFolder = oMachine.snapshotFolder
     for sFile in os.listdir(sFolder):
         if sFile.endswith(".sav") is False:
             sFullPath = os.path.join(sFolder, sFile)
             asSnapshotsFilesList.add(sFullPath)
             if fPrint is True:
                 reporter.log("Snapshot file is %s" % (sFullPath))
     return asSnapshotsFilesList
 def _waitKeyboardInterrupt(self):
     """
     Idle loop until user press CTRL+C
     """
     reporter.log('[LOCAL CATCH]: waiting for keyboard interrupt')
     while (True):
         try:
             self.sleep(1)
         except KeyboardInterrupt:
             reporter.log('[LOCAL CATCH]: keyboard interrupt occurred')
             break
    def testOneVmConfig(self, oVM, oTestVm):
        #self.logVmInfo(oVM)
        oSession, oTxsSession = self.startVmAndConnectToTxsViaTcp(oTestVm.sVmName,
                                                                    fCdWait = True,
                                                                    cMsTimeout = 60 * 1000)
        if oSession is not None and oTxsSession is not None:
            # Wait until guest reported success
            reporter.log('Guest started. Connection to TXS service established.')
            self.doTest(oSessionWrapper.o)

        return True
Exemple #24
0
    def write(self, sText):
        """iozone stdout write"""
        if isinstance(sText, array.array):
            try:
                sText = sText.tostring();
            except:
                pass;
        try:
            asLines = sText.splitlines();
            for sLine in asLines:
                sLine = sLine.strip();
                if sLine.startswith('Children') is True:
                    # Extract the value
                    idxValue = sLine.rfind('=');
                    if idxValue is -1:
                        raise Exception('IozoneStdOutWrapper: Invalid state');

                    idxValue += 1;
                    while sLine[idxValue] == ' ':
                        idxValue += 1;

                    idxValueEnd = idxValue;
                    while sLine[idxValueEnd] == '.' or sLine[idxValueEnd].isdigit():
                        idxValueEnd += 1;

                    fpValue = float(sLine[idxValue:idxValueEnd]);

                    if sLine.rfind('initial writers') is not -1:
                        self.fpInitWriter = fpValue;
                    elif sLine.rfind('rewriters') is not -1:
                        self.fpRewriter = fpValue;
                    elif sLine.rfind('re-readers') is not -1:
                        self.fpRereader = fpValue;
                    elif sLine.rfind('reverse readers') is not -1:
                        self.fpReverseReader = fpValue;
                    elif sLine.rfind('stride readers') is not -1:
                        self.fpStrideReader = fpValue;
                    elif sLine.rfind('random readers') is not -1:
                        self.fpRandomReader = fpValue;
                    elif sLine.rfind('mixed workload') is not -1:
                        self.fpMixedWorkload = fpValue;
                    elif sLine.rfind('random writers') is not -1:
                        self.fpRandomWriter = fpValue;
                    elif sLine.rfind('pwrite writers') is not -1:
                        self.fpPWrite = fpValue;
                    elif sLine.rfind('pread readers') is not -1:
                        self.fpPRead = fpValue;
                    elif sLine.rfind('readers') is not -1:
                        self.fpReader = fpValue;
                    else:
                        reporter.log('Unknown test returned %s' % sLine);
        except:
            pass;
        return None;
 def _hardenedMkDir(self, sPath):
     """
     Creates the directory specified sPath (including parents).
     """
     reporter.log('_hardenedMkDir: %s' % (sPath,));
     if utils.getHostOs() in [ 'win', 'os2' ]:
         os.makedirs(sPath, 0755);
     else:
         fRc = self._sudoExecuteSync(['/bin/mkdir', '-p', '-m', '0755', sPath]);
         if fRc is not True:
             raise Exception('Failed to create dir "%s".' % (sPath,));
     return True;
    def test1OneCfg(self, sVmName, eStorageController, sDiskFormat):
        """
        Runs the specified VM thru test #1.

        Returns a success indicator on the general test execution. This is not
        the actual test result.
        """
        oVM = self.getVmByName(sVmName);

        # @ŧodo: Implement support for different formats.
        _ = sDiskFormat;

        # Reconfigure the VM
        fRc = True;
        oSession = self.openSession(oVM);
        if oSession is not None:
            # Attach HD
            fRc = oSession.ensureControllerAttached(_ControllerTypeToName(eStorageController));
            fRc = fRc and oSession.setStorageControllerType(eStorageController, _ControllerTypeToName(eStorageController));
            fRc = fRc and oSession.saveSettings();
            fRc = oSession.close() and fRc and True; # pychecker hack.
            oSession = None;
        else:
            fRc = False;

        # Start up.
        if fRc is True:
            self.logVmInfo(oVM);
            oSession, oTxsSession = self.startVmAndConnectToTxsViaTcp(sVmName, fCdWait = False, fNatForwardingForTxs = True);
            if oSession is not None:
                self.addTask(oSession);

                # Fudge factor - Allow the guest to finish starting up.
                self.sleep(5);

                # Do a snapshot first.
                oSession.takeSnapshot('Base snapshot');

                for i in range(0, 10):
                    oSession.takeSnapshot('Snapshot ' + str(i));
                    self.test1UploadFile(oSession, oTxsSession);
                    msNow = base.timestampMilli();
                    oSnapshot = oSession.findSnapshot('Snapshot ' + str(i));
                    oSession.deleteSnapshot(oSnapshot.id, cMsTimeout = 60 * 1000);
                    msElapsed = base.timestampMilli() - msNow;
                    reporter.log('Deleting snapshot %d took %d ms' % (i, msElapsed));

                # cleanup.
                self.removeTask(oTxsSession);
                self.terminateVmBySession(oSession)
            else:
                fRc = False;
        return fRc;
 def checkLocation(self, sLocation, aoMediumAttachments, asFiles):
     fRc = True
     for oAttachment in aoMediumAttachments:
         sFilePath = os.path.join(sLocation, asFiles[oAttachment.port])
         sActualFilePath = oAttachment.medium.location
         if os.path.abspath(sFilePath) != os.path.abspath(sActualFilePath):
             reporter.log('medium location expected to be "%s" but is "%s"' % (sFilePath, sActualFilePath))
             fRc = False;
         if not os.path.exists(sFilePath):
             reporter.log('medium file does not exist at "%s"' % (sFilePath,))
             fRc = False;
     return fRc
 def onRuntimeError(self, fFatal, sErrId, sMessage):
     """ Verify the error. """
     reporter.log('onRuntimeError: fFatal=%s sErrId="%s" sMessage="%s"' % (fFatal, sErrId, sMessage))
     if sErrId != "PAEmode":
         reporter.testFailure("sErrId=%s, expected PAEmode" % (sErrId,))
     elif fFatal is not True:
         reporter.testFailure("fFatal=%s, expected True" % (fFatal,))
     else:
         self.oTstDrv.fCallbackSuccess = True
     self.oTstDrv.fCallbackFired = True
     self.oVBoxMgr.interruptWaitEvents()
     return None
    def doTest(self, oSession):
        oConsole = oSession.console
        oGuest = oConsole.guest

        sOSTypeId = oGuest.OSTypeId.lower()
        if sOSTypeId.find("win") == -1 :
            reporter.log("Only Windows guests are currently supported")
            reporter.testDone()
            return True

        oGuestSession = oGuest.createSession("Administrator", "password", "", "Audio Validation Kit")
        guestSessionWaitResult = oGuestSession.waitFor(self.oVBoxMgr.constants.GuestSessionWaitResult_Start, 2000)
        reporter.log("guestSessionWaitResult = %d" % guestSessionWaitResult)

        for duration in range(3, 6):
            reporter.testStart("Checking for duration of " + str(duration) + " seconds")
            sPathToPlayer = "D:\\win\\" + ("amd64" if (sOSTypeId.find('_64') >= 0) else "x86") + "\\ntPlayToneWaveX.exe"
            oProcess = oGuestSession.processCreate(sPathToPlayer,  ["xxx0", "--total-duration-in-secs", str(duration)], [], [], 0)
            processWaitResult = oProcess.waitFor(self.oVBoxMgr.constants.ProcessWaitForFlag_Start, 1000)
            reporter.log("Started: pid %d, waitResult %d" % (oProcess.PID, processWaitResult))

            processWaitResult = oProcess.waitFor(self.oVBoxMgr.constants.ProcessWaitForFlag_Terminate, 2 * duration * 1000)
            reporter.log("Terminated: pid %d, waitResult %d" % (oProcess.PID, processWaitResult))
            time.sleep(1) # Give audio backend sometime to save a stream to .wav file

            absFileName = self.seekLatestAudioFileName(oGuestSession, duration)

            if absFileName is None:
                reporter.testFailure("Unable to find audio file")
                continue

            reporter.log("Checking audio file '" + absFileName + "'")

            diff = self.checkGuestHostTimings(absFileName + ".timing")
            if diff is not None:
                if diff > 0.0:      # Guest sends data quicker than a host can play
                    if diff > 0.01: # 1% is probably good threshold here
                        reporter.testFailure("Guest sends audio buffers too quickly")
                else:
                    diff = -diff;   # Much worse case: guest sends data very slow, host feels starvation
                    if diff > 0.005: # 0.5% is probably good threshold here
                        reporter.testFailure("Guest sends audio buffers too slowly")

                reporter.testDone()
            else:
                reporter.testFailure("Unable to parse a file with timings")

        oGuestSession.close()

        del oGuest
        del oConsole

        return True
    def _removeUnsupportedVirtModes(self, oTestDrv):
        """
        Removes unsupported virtualization modes.
        """
        if 'hwvirt' in self.asVirtModes and not oTestDrv.hasHostHwVirt():
            reporter.log('Hardware assisted virtualization is not available on the host, skipping it.');
            self.asVirtModes.remove('hwvirt');

        if 'hwvirt-np' in self.asVirtModes and not oTestDrv.hasHostNestedPaging():
            reporter.log('Nested paging not supported by the host, skipping it.');
            self.asVirtModes.remove('hwvirt-np');
        return True;
 def showUsage(self):
     rc = vbox.TestDriver.showUsage(self)
     reporter.log('')
     reporter.log('tdStorageSnapshot1 Options:')
     reporter.log('  --storage-ctrls <type1[:type2[:...]]>')
     reporter.log('      Default: %s' % (':'.join(self.asStorageCtrls)))
     reporter.log('  --disk-formats  <type1[:type2[:...]]>')
     reporter.log('      Default: %s' % (':'.join(self.asDiskFormats)))
     reporter.log('  --test-vms      <vm1[:vm2[:...]]>')
     reporter.log(
         '      Test the specified VMs in the given order. Use this to change'
     )
     reporter.log('      the execution order or limit the choice of VMs')
     reporter.log('      Default: %s  (all)' %
                  (':'.join(self.asTestVMsDef)))
     reporter.log('  --skip-vms      <vm1[:vm2[:...]]>')
     reporter.log('      Skip the specified VMs when testing.')
     return rc
Exemple #32
0
 def showUsage(self):
     rc = vbox.TestDriver.showUsage(self)
     reporter.log('')
     reporter.log('tdAddBasic1 Options:')
     reporter.log('  --tests        <s1[:s2[:]]>')
     reporter.log('      Default: %s  (all)' % (':'.join(self.asTestsDef)))
     reporter.log('  --quick')
     reporter.log('      Same as --virt-modes hwvirt --cpu-counts 1.')
     return rc
Exemple #33
0
    def testEventQueueInterrupt(self):
        """
        Test interrupting an event queue wait.
        """
        reporter.testStart('interruptWait')

        # interrupt ourselves first and check the return value.
        for i in range(0, 10):
            try:
                rc = self.oVBoxMgr.interruptWaitEvents()
            except:
                reporter.errorXcpt()
                break
            if rc is not True:
                reporter.error(
                    'interruptWaitEvents returned "%s" expected True' % (rc, ))
                break

        if reporter.testErrorCount() == 0:
            #
            # Interrupt a waitForEvents call.
            #
            # This test ASSUMES that no other events are posted to the thread's
            # event queue once we've drained it.  Also ASSUMES the box is
            # relatively fast and not too busy because we're timing sensitive.
            #
            for i in range(0, 4):
                # Try quiesce the event queue.
                for _ in range(1, 100):
                    self.oVBoxMgr.waitForEvents(0)

                # Create a thread that will interrupt us in 2 seconds.
                try:
                    oThread = threading.Thread(
                        target=self.interruptWaitEventsThreadProc)
                    oThread.setDaemon(False)
                except:
                    reporter.errorXcpt()
                    break

                cMsTimeout = 20000
                if i == 2:
                    cMsTimeout = -1
                elif i == 3:
                    cMsTimeout = -999999

                # Do the wait.
                oThread.start()
                msNow = base.timestampMilli()
                try:
                    rc = self.oVBoxMgr.waitForEvents(cMsTimeout)
                except:
                    reporter.errorXcpt()
                else:
                    msElapsed = base.timestampMilli() - msNow

                    # Check the return code and elapsed time.
                    if not isinstance(rc, types.IntType):
                        reporter.error(
                            'waitForEvents returns non-integer type after %u ms, expected 1'
                            % (msElapsed, ))
                    elif rc != 1:
                        reporter.error(
                            'waitForEvents returned "%s" after %u ms, expected 1'
                            % (rc, msElapsed))
                    if msElapsed > 15000:
                        reporter.error(
                            'waitForEvents after %u ms, expected just above 2-3 seconds'
                            % (msElapsed, ))
                    elif msElapsed < 100:
                        reporter.error(
                            'waitForEvents after %u ms, expected more than 100 ms.'
                            % (msElapsed, ))

                oThread.join()
                oThread = None
                if reporter.testErrorCount() != 0:
                    break
                reporter.log('Iteration %u was successful...' % (i + 1, ))
        return reporter.testDone()[1] == 0
Exemple #34
0
    def _uninstallVBoxOnWindows(self, sMode):
        """
        Uninstalls VBox on Windows, all installations we find to be on the safe side...
        """
        assert sMode in [
            'install',
            'uninstall',
        ]

        import win32com.client
        # pylint: disable=import-error
        win32com.client.gencache.EnsureModule(
            '{000C1092-0000-0000-C000-000000000046}', 1033, 1, 0)
        oInstaller = win32com.client.Dispatch(
            'WindowsInstaller.Installer',
            resultCLSID='{000C1090-0000-0000-C000-000000000046}')

        # Search installed products for VirtualBox.
        asProdCodes = []
        for sProdCode in oInstaller.Products:
            try:
                sProdName = oInstaller.ProductInfo(sProdCode, "ProductName")
            except:
                reporter.logXcpt()
                continue
            #reporter.log('Info: %s=%s' % (sProdCode, sProdName));
            if  sProdName.startswith('Oracle VM VirtualBox') \
             or sProdName.startswith('Sun VirtualBox'):
                asProdCodes.append([sProdCode, sProdName])

        # Before we start uninstalling anything, just ruthlessly kill any cdb,
        # msiexec, drvinst and some rundll process we might find hanging around.
        if self._isProcessPresent('rundll32'):
            cTimes = 0
            while cTimes < 3:
                cTimes += 1
                cKilled = self._terminateProcessesByNameAndArgSubstr(
                    'rundll32', 'InstallSecurityPromptRunDllW',
                    'MSI driver installation')
                if cKilled <= 0:
                    break
                time.sleep(10)
                # Give related drvinst process a chance to clean up after we killed the verification dialog.

        if self._isProcessPresent('drvinst'):
            time.sleep(15)
            # In the hope that it goes away.
            cTimes = 0
            while cTimes < 4:
                cTimes += 1
                cKilled = self._killProcessesByName('drvinst',
                                                    'MSI driver installation',
                                                    True)
                if cKilled <= 0:
                    break
                time.sleep(10)
                # Give related MSI process a chance to clean up after we killed the driver installer.

        if self._isProcessPresent('msiexec'):
            cTimes = 0
            while cTimes < 3:
                reporter.log('found running msiexec process, waiting a bit...')
                time.sleep(20)  # In the hope that it goes away.
                if not self._isProcessPresent('msiexec'):
                    break
                cTimes += 1
            ## @todo this could also be the msiexec system service, try to detect this case!
            if cTimes >= 6:
                cKilled = self._killProcessesByName('msiexec',
                                                    'MSI driver installation')
                if cKilled > 0:
                    time.sleep(16)
                    # fudge.

        # cdb.exe sometimes stays running (from utils.getProcessInfo), blocking
        # the scratch directory. No idea why.
        if self._isProcessPresent('cdb'):
            cTimes = 0
            while cTimes < 3:
                cKilled = self._killProcessesByName(
                    'cdb', 'cdb.exe from getProcessInfo')
                if cKilled <= 0:
                    break
                time.sleep(2)
                # fudge.

        # Do the uninstalling.
        fRc = True
        sLogFile = os.path.join(self.sScratchPath, 'VBoxUninstallLog.txt')
        for sProdCode, sProdName in asProdCodes:
            reporter.log('Uninstalling %s (%s)...' % (sProdName, sProdCode))
            fRc2, iRc = self._sudoExecuteSync([
                'msiexec',
                '/uninstall',
                sProdCode,
                '/quiet',
                '/passive',
                '/norestart',
                '/L*v',
                '%s' % (sLogFile),
            ])
            if fRc2 is False:
                if iRc == 3010:  # ERROR_SUCCESS_REBOOT_REQUIRED
                    reporter.error(
                        'Uninstaller required a reboot to complete uninstallation'
                    )
                else:
                    reporter.error('Uninstaller failed, exit code: %s' %
                                   (iRc, ))
                fRc = False

        self._waitForTestManagerConnectivity(30)

        # Upload the log on failure.  Do it early if the extra cleanups below causes trouble.
        if fRc is False and os.path.isfile(sLogFile):
            reporter.addLogFile(sLogFile, 'log/uninstaller',
                                "Verbose MSI uninstallation log file")
            sLogFile = None

        # Log driver service states (should ls \Driver\VBox* and \Device\VBox*).
        fHadLeftovers = False
        asLeftovers = []
        for sService in reversed(self.kasWindowsServices):
            cTries = 0
            while True:
                fRc2, _ = self._sudoExecuteSync(['sc.exe', 'query', sService])
                if not fRc2:
                    break
                fHadLeftovers = True

                cTries += 1
                if cTries > 3:
                    asLeftovers.append(sService, )
                    break

                # Get the status output.
                try:
                    sOutput = utils.sudoProcessOutputChecked(
                        ['sc.exe', 'query', sService])
                except:
                    reporter.logXcpt()
                else:
                    if re.search(r'STATE\s+:\s*1\s*STOPPED', sOutput) is None:
                        reporter.log('Trying to stop %s...' % (sService, ))
                        fRc2, _ = self._sudoExecuteSync(
                            ['sc.exe', 'stop', sService])
                        time.sleep(1)
                        # fudge

                    reporter.log('Trying to delete %s...' % (sService, ))
                    self._sudoExecuteSync(['sc.exe', 'delete', sService])

                time.sleep(1)
                # fudge

        if asLeftovers:
            reporter.log('Warning! Leftover VBox drivers: %s' %
                         (', '.join(asLeftovers), ))
            fRc = False

        if fHadLeftovers:
            self._waitForTestManagerConnectivity(30)

        # Upload the log if we have any leftovers and didn't upload it already.
        if sLogFile is not None and (
                fRc is False or fHadLeftovers) and os.path.isfile(sLogFile):
            reporter.addLogFile(sLogFile, 'log/uninstaller',
                                "Verbose MSI uninstallation log file")

        return fRc
Exemple #35
0
 def parseOption(self, asArgs, iArg):
     if asArgs[iArg] == '--virt-modes':
         iArg += 1
         if iArg >= len(asArgs):
             raise base.InvalidOption(
                 'The "--virt-modes" takes a colon separated list of modes')
         self.asVirtModes = asArgs[iArg].split(':')
         for s in self.asVirtModes:
             if s not in self.asVirtModesDef:
                 raise base.InvalidOption('The "--virt-modes" value "%s" is not valid; valid values are: %s' \
                     % (s, ' '.join(self.asVirtModesDef)))
     elif asArgs[iArg] == '--cpu-counts':
         iArg += 1
         if iArg >= len(asArgs):
             raise base.InvalidOption(
                 'The "--cpu-counts" takes a colon separated list of cpu counts'
             )
         self.acCpus = []
         for s in asArgs[iArg].split(':'):
             try:
                 c = int(s)
             except:
                 raise base.InvalidOption(
                     'The "--cpu-counts" value "%s" is not an integer' %
                     (s, ))
             if c <= 0:
                 raise base.InvalidOption(
                     'The "--cpu-counts" value "%s" is zero or negative' %
                     (s, ))
             self.acCpus.append(c)
     elif asArgs[iArg] == '--test-vms':
         iArg += 1
         if iArg >= len(asArgs):
             raise base.InvalidOption(
                 'The "--test-vms" takes colon separated list')
         if asArgs[iArg]:
             self.asTestVMs = asArgs[iArg].split(':')
             for s in self.asTestVMs:
                 if s not in self.asTestVMsDef:
                     raise base.InvalidOption('The "--test-vms" value "%s" is not valid; valid values are: %s' \
                         % (s, ' '.join(self.asTestVMsDef)))
         else:
             self.asTestVMs = []
     elif asArgs[iArg] == '--skip-vms':
         iArg += 1
         if iArg >= len(asArgs):
             raise base.InvalidOption(
                 'The "--skip-vms" takes colon separated list')
         self.asSkipVMs = asArgs[iArg].split(':')
         for s in self.asSkipVMs:
             if s not in self.asTestVMsDef:
                 reporter.log(
                     'warning: The "--skip-vms" value "%s" does not specify any of our test VMs.'
                     % (s))
     elif asArgs[iArg] == '--tests':
         iArg += 1
         if iArg >= len(asArgs):
             raise base.InvalidOption(
                 'The "--tests" takes colon separated list')
         self.asTests = asArgs[iArg].split(':')
         for s in self.asTests:
             if s not in self.asTestsDef:
                 reporter.log(
                     'warning: The "--tests" value "%s" does not specify any of our tests.'
                     % (s))
     elif asArgs[iArg] == '--skip-tests':
         iArg += 1
         if iArg >= len(asArgs):
             raise base.InvalidOption(
                 'The "--skip-tests" takes colon separated list')
         self.asSkipVMs = asArgs[iArg].split(':')
         for s in self.asSkipTests:
             if s not in self.asTestsDef:
                 reporter.log(
                     'warning: The "--skip-tests" value "%s" does not specify any of our tests.'
                     % (s))
     elif asArgs[iArg] == '--quick':
         self.asVirtModes = [
             'hwvirt',
         ]
         self.acCpus = [
             1,
         ]
         #self.asTestVMs          = ['tst-rhel5', 'tst-win2k3ent', 'tst-sol10',];
         self.asTestVMs = [
             'tst-rhel5',
         ]
     else:
         return vbox.TestDriver.parseOption(self, asArgs, iArg)
     return iArg + 1
    def test1OneCfg(self, sVmName, eStorageController, sDiskFormat, sDiskPath1, sDiskPath2, \
                    sGuestFs, cCpus, fHwVirt, fNestedPaging):
        """
        Runs the specified VM thru test #1.

        Returns a success indicator on the general test execution. This is not
        the actual test result.
        """
        oVM = self.getVmByName(sVmName);

        # Reconfigure the VM
        fRc = True;
        oSession = self.openSession(oVM);
        if oSession is not None:
            # Attach HD
            fRc = oSession.ensureControllerAttached(_ControllerTypeToName(eStorageController));
            fRc = fRc and oSession.setStorageControllerType(eStorageController, _ControllerTypeToName(eStorageController));

            if sDiskFormat == "iSCSI":
                listNames = [];
                listValues = [];
                listValues = sDiskPath1.split('|');
                listNames.append('TargetAddress');
                listNames.append('TargetName');
                listNames.append('LUN');

                if self.fpApiVer >= 5.0:
                    oHd = oSession.oVBox.createMedium(sDiskFormat, sDiskPath1, vboxcon.AccessMode_ReadWrite, \
                                                      vboxcon.DeviceType_HardDisk);
                else:
                    oHd = oSession.oVBox.createHardDisk(sDiskFormat, sDiskPath1);
                oHd.type = vboxcon.MediumType_Normal;
                oHd.setProperties(listNames, listValues);

                # Attach it.
                if fRc is True:
                    try:
                        if oSession.fpApiVer >= 4.0:
                            oSession.o.machine.attachDevice(_ControllerTypeToName(eStorageController), \
                                                            1, 0, vboxcon.DeviceType_HardDisk, oHd);
                        else:
                            oSession.o.machine.attachDevice(_ControllerTypeToName(eStorageController), \
                                                            1, 0, vboxcon.DeviceType_HardDisk, oHd.id);
                    except:
                        reporter.errorXcpt('attachDevice("%s",%s,%s,HardDisk,"%s") failed on "%s"' \
                                           % (_ControllerTypeToName(eStorageController), 1, 0, oHd.id, oSession.sName) );
                        fRc = False;
                    else:
                        reporter.log('attached "%s" to %s' % (sDiskPath1, oSession.sName));
            else:
                fRc = fRc and oSession.createAndAttachHd(sDiskPath1, sDiskFormat, _ControllerTypeToName(eStorageController), \
                                                         cb = 10*1024*1024*1024, iPort = 1, fImmutable = False);
                fRc = fRc and oSession.createAndAttachHd(sDiskPath2, sDiskFormat, _ControllerTypeToName(eStorageController), \
                                                         cb = 10*1024*1024*1024, iPort = 2, fImmutable = False);
            fRc = fRc and oSession.enableVirtEx(fHwVirt);
            fRc = fRc and oSession.enableNestedPaging(fNestedPaging);
            fRc = fRc and oSession.setCpuCount(cCpus);
            fRc = fRc and oSession.saveSettings();
            fRc = oSession.close() and fRc and True; # pychecker hack.
            oSession = None;
        else:
            fRc = False;

        # Start up.
        if fRc is True:
            self.logVmInfo(oVM);
            oSession, oTxsSession = self.startVmAndConnectToTxsViaTcp(sVmName, fCdWait = False, fNatForwardingForTxs = True);
            if oSession is not None:
                self.addTask(oTxsSession);

                # Fudge factor - Allow the guest to finish starting up.
                self.sleep(5);

                fRc = self.test1RunTestProgs(oSession, oTxsSession, fRc, 'stress testing', sGuestFs);

                # cleanup.
                self.removeTask(oTxsSession);
                self.terminateVmBySession(oSession)

                # Remove disk
                oSession = self.openSession(oVM);
                if oSession is not None:
                    try:
                        oSession.o.machine.detachDevice(_ControllerTypeToName(eStorageController), 1, 0);
                        oSession.o.machine.detachDevice(_ControllerTypeToName(eStorageController), 2, 0);

                        # Remove storage controller if it is not an IDE controller.
                        if     eStorageController is not vboxcon.StorageControllerType_PIIX3 \
                           and eStorageController is not vboxcon.StorageControllerType_PIIX4:
                            oSession.o.machine.removeStorageController(_ControllerTypeToName(eStorageController));

                        oSession.saveSettings();
                        oSession.oVBox.deleteHdByLocation(sDiskPath1);
                        oSession.oVBox.deleteHdByLocation(sDiskPath2);
                        oSession.saveSettings();
                        oSession.close();
                        oSession = None;
                    except:
                        reporter.errorXcpt('failed to detach/delete disks %s and %s from storage controller' % \
                                           (sDiskPath1, sDiskPath2));
                else:
                    fRc = False;
            else:
                fRc = False;
        return fRc;
Exemple #37
0
 def showUsage(self):
     rc = TestDriverBase.showUsage(self)
     #             0         1         2         3         4         5         6         7         8
     #             012345678901234567890123456789012345678901234567890123456789012345678901234567890
     reporter.log('')
     reporter.log('vboxinstaller Options:')
     reporter.log('  --vbox-build    <url[,url2[,...]]>')
     reporter.log(
         '      Comma separated list of URL to file to download and install or/and'
     )
     reporter.log(
         '      unpack.  URLs without a schema are assumed to be files on the'
     )
     reporter.log('      build share and will be copied off it.')
     reporter.log('  --no-puel-extpack')
     reporter.log(
         '      Indicates that the PUEL extension pack should not be installed if found.'
     )
     reporter.log(
         '      The default is to install it if found in the vbox-build.')
     reporter.log('  --no-kernel-drivers')
     reporter.log(
         '      Indicates that the kernel drivers should not be installed on platforms where this is supported.'
     )
     reporter.log('      The default is to install them.')
     reporter.log('  --')
     reporter.log(
         '      Indicates the end of our parameters and the start of the sub'
     )
     reporter.log('      testdriver and its arguments.')
     return rc
 def showUsage(self):
     rc = vbox.TestDriver.showUsage(self);
     reporter.log('');
     reporter.log('tdStorageBenchmark1 Options:');
     reporter.log('  --virt-modes    <m1[:m2[:]]');
     reporter.log('      Default: %s' % (':'.join(self.asVirtModesDef)));
     reporter.log('  --cpu-counts    <c1[:c2[:]]');
     reporter.log('      Default: %s' % (':'.join(str(c) for c in self.acCpusDef)));
     reporter.log('  --storage-ctrls <type1[:type2[:...]]>');
     reporter.log('      Default: %s' % (':'.join(self.asStorageCtrls)));
     reporter.log('  --disk-formats  <type1[:type2[:...]]>');
     reporter.log('      Default: %s' % (':'.join(self.asDiskFormats)));
     reporter.log('  --disk-dirs     <path1[:path2[:...]]>');
     reporter.log('      Default: %s' % (':'.join(self.asDirs)));
     reporter.log('  --iscsi-targets     <target1[:target2[:...]]>');
     reporter.log('      Default: %s' % (':'.join(self.asIscsiTargets)));
     reporter.log('  --tests         <test1[:test2[:...]]>');
     reporter.log('      Default: %s' % (':'.join(self.asTests)));
     reporter.log('  --guest-fs      <fs1[:fs2[:...]]>');
     reporter.log('      Default: %s' % (':'.join(self.asGuestFs)));
     reporter.log('  --test-vms      <vm1[:vm2[:...]]>');
     reporter.log('      Test the specified VMs in the given order. Use this to change');
     reporter.log('      the execution order or limit the choice of VMs');
     reporter.log('      Default: %s  (all)' % (':'.join(self.asTestVMsDef)));
     reporter.log('  --skip-vms      <vm1[:vm2[:...]]>');
     reporter.log('      Skip the specified VMs when testing.');
     return rc;
Exemple #39
0
 def showUsage(self):
     """
     Invoked by vbox.TestDriver.
     """
     reporter.log('');
     reporter.log('Test VM selection and general config options:');
     reporter.log('  --virt-modes   <m1[:m2[:]]');
     reporter.log('      Default: %s' % (':'.join(self.asVirtModesDef)));
     reporter.log('  --skip-virt-modes <m1[:m2[:]]');
     reporter.log('      Use this to avoid hwvirt or hwvirt-np when not supported by the host');
     reporter.log('      since we cannot detect it using the main API. Use after --virt-modes.');
     reporter.log('  --cpu-counts   <c1[:c2[:]]');
     reporter.log('      Default: %s' % (':'.join(str(c) for c in self.acCpusDef)));
     reporter.log('  --test-vms     <vm1[:vm2[:...]]>');
     reporter.log('      Test the specified VMs in the given order. Use this to change');
     reporter.log('      the execution order or limit the choice of VMs');
     reporter.log('      Default: %s  (all)' % (self.getAllVmNames(),));
     reporter.log('  --skip-vms     <vm1[:vm2[:...]]>');
     reporter.log('      Skip the specified VMs when testing.');
     reporter.log('  --snapshot-restore-current');
     reporter.log('      Restores the current snapshot and resumes execution.');
     reporter.log('  --paravirt-modes   <pv1[:pv2[:]]>');
     reporter.log('      Set of paravirtualized providers (modes) to tests. Intersected with what the test VM supports.');
     reporter.log('      Default is the first PV mode the test VMs support, generally same as "legacy".');
     ## @todo Add more options for controlling individual VMs.
     return True;
Exemple #40
0
    def parseOption(self, asArgs, iArg):
        """
        Parses the set test vm set options (--test-vms and --skip-vms), modifying the set
        Invoked by the testdriver method with the same name.

        Keyword arguments:
        asArgs -- The argument vector.
        iArg   -- The index of the current argument.

        Returns iArg if the option was not recognized and the caller should handle it.
        Returns the index of the next argument when something is consumed.

        In the event of a syntax error, a InvalidOption or QuietInvalidOption
        is thrown.
        """

        if asArgs[iArg] == '--virt-modes':
            iArg += 1;
            if iArg >= len(asArgs):
                raise base.InvalidOption('The "--virt-modes" takes a colon separated list of modes');

            self.asVirtModes = asArgs[iArg].split(':');
            for s in self.asVirtModes:
                if s not in self.asVirtModesDef:
                    raise base.InvalidOption('The "--virt-modes" value "%s" is not valid; valid values are: %s' \
                        % (s, ' '.join(self.asVirtModesDef)));

        elif asArgs[iArg] == '--skip-virt-modes':
            iArg += 1;
            if iArg >= len(asArgs):
                raise base.InvalidOption('The "--skip-virt-modes" takes a colon separated list of modes');

            for s in asArgs[iArg].split(':'):
                if s not in self.asVirtModesDef:
                    raise base.InvalidOption('The "--virt-modes" value "%s" is not valid; valid values are: %s' \
                        % (s, ' '.join(self.asVirtModesDef)));
                if s in self.asVirtModes:
                    self.asVirtModes.remove(s);

        elif asArgs[iArg] == '--cpu-counts':
            iArg += 1;
            if iArg >= len(asArgs):
                raise base.InvalidOption('The "--cpu-counts" takes a colon separated list of cpu counts');

            self.acCpus = [];
            for s in asArgs[iArg].split(':'):
                try: c = int(s);
                except: raise base.InvalidOption('The "--cpu-counts" value "%s" is not an integer' % (s,));
                if c <= 0:  raise base.InvalidOption('The "--cpu-counts" value "%s" is zero or negative' % (s,));
                self.acCpus.append(c);

        elif asArgs[iArg] == '--test-vms':
            iArg += 1;
            if iArg >= len(asArgs):
                raise base.InvalidOption('The "--test-vms" takes colon separated list');

            for oTestVm in self.aoTestVms:
                oTestVm.fSkip = True;

            asTestVMs = asArgs[iArg].split(':');
            for s in asTestVMs:
                oTestVm = self.findTestVmByName(s);
                if oTestVm is None:
                    raise base.InvalidOption('The "--test-vms" value "%s" is not valid; valid values are: %s' \
                                             % (s, self.getAllVmNames(' ')));
                oTestVm.fSkip = False;

        elif asArgs[iArg] == '--skip-vms':
            iArg += 1;
            if iArg >= len(asArgs):
                raise base.InvalidOption('The "--skip-vms" takes colon separated list');

            asTestVMs = asArgs[iArg].split(':');
            for s in asTestVMs:
                oTestVm = self.findTestVmByName(s);
                if oTestVm is None:
                    reporter.log('warning: The "--test-vms" value "%s" does not specify any of our test VMs.' % (s,));
                else:
                    oTestVm.fSkip = True;

        elif asArgs[iArg] == '--snapshot-restore-current':
            for oTestVm in self.aoTestVms:
                if oTestVm.fSkip is False:
                    oTestVm.fSnapshotRestoreCurrent = True;
                    reporter.log('VM "%s" will be restored.' % (oTestVm.sVmName));

        elif asArgs[iArg] == '--paravirt-modes':
            iArg += 1
            if iArg >= len(asArgs):
                raise base.InvalidOption('The "--paravirt-modes" takes a colon separated list of modes');

            self.asParavirtModes = asArgs[iArg].split(':')
            for sPvMode in self.asParavirtModes:
                if sPvMode not in g_kasParavirtProviders:
                    raise base.InvalidOption('The "--paravirt-modes" value "%s" is not valid; valid values are: %s'
                                             % (sPvMode, ', '.join(g_kasParavirtProviders),));
            if not self.asParavirtModes:
                self.asParavirtModes = None;

            # HACK ALERT! Reset the random paravirt selection for members.
            for oTestVm in self.aoTestVms:
                oTestVm.asParavirtModesSup = oTestVm.asParavirtModesSupOrg;

        else:
            return iArg;
        return iArg + 1;
Exemple #41
0
    def actionExecute(self, oTestDrv, fnCallback): # pylint: disable=R0914
        """
        For base.TestDriver.actionExecute.  Calls the callback function for
        each of the VMs and basic configuration variations (virt-mode and cpu
        count).

        Returns True if all fnCallback calls returned True, otherwise False.

        The callback can return True, False or None. The latter is for when the
        test is skipped.  (True is for success, False is for failure.)
        """

        self._removeUnsupportedVirtModes(oTestDrv);
        cMaxCpus = oTestDrv.getHostCpuCount();

        #
        # The test loop.
        #
        fRc = True;
        for oTestVm in self.aoTestVms:
            if oTestVm.fSkip and self.fIgnoreSkippedVm:
                reporter.log2('Ignoring VM %s (fSkip = True).' % (oTestVm.sVmName,));
                continue;
            reporter.testStart(oTestVm.sVmName);
            if oTestVm.fSkip:
                reporter.testDone(fSkipped = True);
                continue;

            # Intersect the supported modes and the ones being testing.
            asVirtModesSup = [sMode for sMode in oTestVm.asVirtModesSup if sMode in self.asVirtModes];

            # Ditto for CPUs.
            acCpusSup      = [cCpus for cCpus in oTestVm.acCpusSup      if cCpus in self.acCpus];

            # Ditto for paravirtualization modes, except if not specified we got a less obvious default.
            if self.asParavirtModes is not None  and  oTestDrv.fpApiVer >= 5.0:
                asParavirtModes = [sPvMode for sPvMode in oTestVm.asParavirtModesSup if sPvMode in self.asParavirtModes];
                assert None not in asParavirtModes;
            elif oTestDrv.fpApiVer >= 5.0:
                asParavirtModes = (oTestVm.asParavirtModesSup[0],);
                assert asParavirtModes[0] is not None;
            else:
                asParavirtModes = (None,);

            for cCpus in acCpusSup:
                if cCpus == 1:
                    reporter.testStart('1 cpu');
                else:
                    reporter.testStart('%u cpus' % (cCpus));
                    if cCpus > cMaxCpus:
                        reporter.testDone(fSkipped = True);
                        continue;

                cTests = 0;
                for sVirtMode in asVirtModesSup:
                    if sVirtMode == 'raw' and cCpus > 1:
                        continue;
                    reporter.testStart('%s' % ( g_dsVirtModeDescs[sVirtMode], ) );
                    cStartTests = cTests;

                    for sParavirtMode in asParavirtModes:
                        if sParavirtMode is not None:
                            assert oTestDrv.fpApiVer >= 5.0;
                            reporter.testStart('%s' % ( sParavirtMode, ) );

                        # Reconfigure the VM.
                        try:
                            (rc2, oVM) = oTestVm.getReconfiguredVm(oTestDrv, cCpus, sVirtMode, sParavirtMode = sParavirtMode);
                        except KeyboardInterrupt:
                            raise;
                        except:
                            reporter.errorXcpt(cFrames = 9);
                            rc2 = False;
                        if rc2 is True:
                            # Do the testing.
                            try:
                                rc2 = fnCallback(oVM, oTestVm);
                            except KeyboardInterrupt:
                                raise;
                            except:
                                reporter.errorXcpt(cFrames = 9);
                                rc2 = False;
                            if rc2 is False:
                                reporter.maybeErr(reporter.testErrorCount() == 0, 'fnCallback failed');
                        elif rc2 is False:
                            reporter.log('getReconfiguredVm failed');
                        if rc2 is False:
                            fRc = False;

                        cTests = cTests + (rc2 is not None);
                        if sParavirtMode is not None:
                            reporter.testDone(fSkipped = (rc2 is None));

                    reporter.testDone(fSkipped = cTests == cStartTests);

                reporter.testDone(fSkipped = cTests == 0);

            _, cErrors = reporter.testDone();
            if cErrors > 0:
                fRc = False;
        return fRc;
Exemple #42
0
 def showUsage(self):
     rc = vbox.TestDriver.showUsage(self)
     reporter.log('')
     reporter.log('tdCpuPae1 Options:')
     reporter.log('  --virt-modes   <m1[:m2[:]]')
     reporter.log('      Default: %s' % (':'.join(self.asVirtModesDef)))
     reporter.log('  --cpu-counts   <c1[:c2[:]]')
     reporter.log('      Default: %s' %
                  (':'.join(str(c) for c in self.acCpusDef)))
     reporter.log('  --quick')
     reporter.log('      Shorthand for: --virt-modes raw --cpu-counts 1 32')
     return rc
Exemple #43
0
 def showUsage(self):
     """
     Extend usage info
     """
     rc = vbox.TestDriver.showUsage(self)
     reporter.log('  --install-iso <ISO file name>')
     reporter.log('  --cpus <# CPUs>')
     reporter.log('  --no-ioapic')
     reporter.log('  --no-nested-paging')
     reporter.log('  --pae')
     reporter.log('  --set-extradata <key>:value')
     reporter.log(
         '      Set VM extra data. This command line option might be used multiple times.'
     )
     return rc
Exemple #44
0
    def actionExecute(self):
        """
        Execute the testcase itself.
        """
        #self.logVmInfo(self.oVM)

        reporter.testStart('SHUTDOWN GUEST')

        cIter = 0
        fRc = True

        if (self.fExtraVm is True):
            oExtraSession, oExtraTxsSession = self.startVmAndConnectToTxsViaTcp(
                self.sExtraVmName,
                fCdWait=False,
                cMsTimeout=self.kcMsVmStartLimit)
            if oExtraSession is None or oExtraTxsSession is None:
                reporter.error('Unable to start extra VM.')
                if (self.fLocalCatch is True):
                    self._waitKeyboardInterrupt()
                reporter.testDone()
                return False

        while (cIter < self.cShutdownIters):

            cIter += 1

            reporter.log("Starting iteration #%d." % cIter)

            oSession, oTxsSession = self.startVmAndConnectToTxsViaTcp(
                self.sVmName, fCdWait=False, cMsTimeout=self.kcMsVmStartLimit)
            if oSession is not None and oTxsSession is not None:
                # Wait until guest reported success
                reporter.log(
                    'Guest started. Connection to TXS service established.')

                if (self.fSuspendHost is True):
                    reporter.log("Disconnect form TXS.")
                    fRc = fRc and self.txsDisconnect(oSession, oTxsSession)
                    if (fRc is not True):
                        reporter.log("Disconnect form TXS failed.")
                    else:
                        reporter.log(
                            'Put host to sleep and resume it automatically after %d seconds.'
                            % self.cSecSuspendTime)
                        fRc = fRc and self._SuspendResume(self.cSecSuspendTime)
                        if (fRc is True):
                            reporter.log("Sleep/resume success.")
                        else:
                            reporter.log("Sleep/resume failed.")
                        reporter.log("Re-connect to TXS in 10 seconds.")
                        self.sleep(10)
                        (fRc, oTxsSession) = self.txsDoConnectViaTcp(
                            oSession, 2 * 60 * 10000)
                        if (fRc is not True):
                            reporter.log("Re-connect to TXS failed.")

                if (fRc is True):
                    reporter.log('Attempt to shutdown guest.')
                    fRc = fRc and oTxsSession.syncShutdown(cMsTimeout=(4 * 60 *
                                                                       1000))
                    if (fRc is True):
                        reporter.log('Shutdown request issued successfully.')
                        self.waitOnDirectSessionClose(self.oVM,
                                                      self.kcMsVmShutdownLimit)
                        reporter.log('Shutdown %s.' %
                                     ('success' if fRc is True else 'failed'))
                    else:
                        reporter.error('Shutdown request failed.')

                    # Do not terminate failing VM in order to catch it.
                    if (fRc is not True and self.fLocalCatch is True):
                        self._waitKeyboardInterrupt()
                        break

                    fRc = fRc and self.terminateVmBySession(oSession)
                    reporter.log('VM terminated.')

            else:
                reporter.error('Guest did not start (iteration %d of %d)' %
                               (cIter, self.cShutdownIters))
                fRc = False

            # Stop if fail
            if (fRc is not True):
                break

        # Local catch at the end.
        if (self.fLocalCatch is True):
            reporter.log("Test completed. Waiting for user to press CTRL+C.")
            self._waitKeyboardInterrupt()

        if (self.fExtraVm is True):
            fRc = fRc and self.terminateVmBySession(oExtraSession)

        reporter.testDone()
        return fRc is True
 def parseOption(self, asArgs, iArg):                                        # pylint: disable=R0912,R0915
     if asArgs[iArg] == '--virt-modes':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--virt-modes" takes a colon separated list of modes');
         self.asVirtModes = asArgs[iArg].split(':');
         for s in self.asVirtModes:
             if s not in self.asVirtModesDef:
                 raise base.InvalidOption('The "--virt-modes" value "%s" is not valid; valid values are: %s' \
                     % (s, ' '.join(self.asVirtModesDef)));
     elif asArgs[iArg] == '--cpu-counts':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--cpu-counts" takes a colon separated list of cpu counts');
         self.acCpus = [];
         for s in asArgs[iArg].split(':'):
             try: c = int(s);
             except: raise base.InvalidOption('The "--cpu-counts" value "%s" is not an integer' % (s,));
             if c <= 0:  raise base.InvalidOption('The "--cpu-counts" value "%s" is zero or negative' % (s,));
             self.acCpus.append(c);
     elif asArgs[iArg] == '--storage-ctrls':
         iArg += 1;
         if iArg >= len(asArgs):
             raise base.InvalidOption('The "--storage-ctrls" takes a colon separated list of Storage controller types');
         self.asStorageCtrls = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--disk-formats':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--disk-formats" takes a colon separated list of disk formats');
         self.asDiskFormats = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--disk-dirs':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--disk-dirs" takes a colon separated list of directories');
         self.asDirs = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--iscsi-targets':
         iArg += 1;
         if iArg >= len(asArgs):
             raise base.InvalidOption('The "--iscsi-targets" takes a colon separated list of iscsi targets');
         self.asIscsiTargets = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--tests':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--tests" takes a colon separated list of disk formats');
         self.asTests = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--guest-fs':
         iArg += 1;
         if iArg >= len(asArgs):
             raise base.InvalidOption('The "--guest-fs" takes a colon separated list of filesystem identifiers');
         self.asGuestFs = asArgs[iArg].split(':');
     elif asArgs[iArg] == '--test-vms':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--test-vms" takes colon separated list');
         self.asTestVMs = asArgs[iArg].split(':');
         for s in self.asTestVMs:
             if s not in self.asTestVMsDef:
                 raise base.InvalidOption('The "--test-vms" value "%s" is not valid; valid values are: %s' \
                     % (s, ' '.join(self.asTestVMsDef)));
     elif asArgs[iArg] == '--skip-vms':
         iArg += 1;
         if iArg >= len(asArgs): raise base.InvalidOption('The "--skip-vms" takes colon separated list');
         self.asSkipVMs = asArgs[iArg].split(':');
         for s in self.asSkipVMs:
             if s not in self.asTestVMsDef:
                 reporter.log('warning: The "--test-vms" value "%s" does not specify any of our test VMs.' % (s));
     else:
         return vbox.TestDriver.parseOption(self, asArgs, iArg);
     return iArg + 1;
Exemple #46
0
    def _installVBox(self):
        """
        Download / copy the build files into the scratch area and install them.
        """
        reporter.testStart('Installing VirtualBox')
        reporter.log('CWD=%s' % (os.getcwd(), ))
        # curious

        #
        # Download the build files.
        #
        for i, sBuildUrl in enumerate(self._asBuildUrls):
            if webutils.downloadFile(sBuildUrl, self._asBuildFiles[i],
                                     self.sBuildPath, reporter.log,
                                     reporter.log) is not True:
                reporter.testDone(fSkipped=True)
                return None
                # Failed to get binaries, probably deleted. Skip the test run.

        #
        # Unpack anything we know what is and append it to the build files
        # list.  This allows us to use VBoxAll*.tar.gz files.
        #
        for sFile in list(
                self._asBuildFiles
        ):  # Note! We copy the list as _maybeUnpackArchive updates it.
            if self._maybeUnpackArchive(sFile, fNonFatal=True) is not True:
                reporter.testDone(fSkipped=True)
                return None
                # Failed to unpack. Probably local error, like busy
                # DLLs on windows, no reason for failing the build.
        self._fUnpackedBuildFiles = True

        #
        # Go to system specific installation code.
        #
        sHost = utils.getHostOs()
        if sHost == 'darwin': fRc = self._installVBoxOnDarwin()
        elif sHost == 'linux': fRc = self._installVBoxOnLinux()
        elif sHost == 'solaris': fRc = self._installVBoxOnSolaris()
        elif sHost == 'win': fRc = self._installVBoxOnWindows()
        else:
            reporter.error('Unsupported host "%s".' % (sHost, ))
        if fRc is False:
            reporter.testFailure('Installation error.')
        elif fRc is not True:
            reporter.log(
                'Seems installation was skipped. Old version lurking behind? Not the fault of this build/test run!'
            )

        #
        # Install the extension pack.
        #
        if fRc is True and self._fAutoInstallPuelExtPack:
            fRc = self._installExtPack()
            if fRc is False:
                reporter.testFailure('Extension pack installation error.')

        # Some debugging...
        try:
            cMbFreeSpace = utils.getDiskUsage(self.sScratchPath)
            reporter.log(
                'Disk usage after VBox install: %d MB available at %s' % (
                    cMbFreeSpace,
                    self.sScratchPath,
                ))
        except:
            reporter.logXcpt(
                'Unable to get disk free space. Ignored. Continuing.')

        reporter.testDone(fRc is None)
        return fRc
Exemple #47
0
    def test1Sub6(self, oVmSrc, oVmDst):
        """
        Misconfigure the target VM and check that teleportation fails with the
        same status and message on both ends.
        xTracker: #4813
        """
        reporter.testStart('Misconfiguration & error message')
        if    self.test1ResetVmConfig(oVmSrc, fTeleporterEnabled = False) \
          and self.test1ResetVmConfig(oVmDst, fTeleporterEnabled = True):
            # Give the source a bit more RAM.
            oSession = self.openSession(oVmSrc)
            if oSession is not None:
                try:
                    cbMB = oVmSrc.memorySize + 4
                except:
                    cbMB = 1
                    fRc = False
                fRc = oSession.setRamSize(cbMB)
                if not oSession.saveSettings(): fRc = False
                if not oSession.close(): fRc = False
                oSession = None
            else:
                fRc = False
            if fRc:
                # Start the target VM.
                oSessionDst, oProgressDst = self.startVmEx(oVmDst, fWait=False)
                if oSessionDst is not None:
                    if oProgressDst.waitForOperation(iOperation=-3) == 0:
                        # Start the source VM.
                        oSessionSrc = self.startVm(oVmSrc)
                        if oSessionSrc is not None:
                            # Try teleport.
                            oProgressSrc = oSessionSrc.teleport(
                                'localhost', 6502, 'password')
                            if oProgressSrc:
                                oProgressSrc.wait()
                                oProgressDst.wait()

                                reporter.log('src: %s' %
                                             oProgressSrc.stringifyResult())
                                reporter.log('dst: %s' %
                                             oProgressDst.stringifyResult())

                                # Make sure it failed.
                                if oProgressSrc.isSuccess(
                                ) and oProgressDst.isSuccess():
                                    reporter.testFailure(
                                        'The teleporation did not fail as expected'
                                    )

                                # Compare the results.
                                if oProgressSrc.getResult(
                                ) != oProgressDst.getResult():
                                    reporter.testFailure('Result differs - src=%s dst=%s' \
                                                         % (vbox.ComError.toString(oProgressSrc.getResult()),\
                                                            vbox.ComError.toString(oProgressDst.getResult())))
                                elif oProgressSrc.getErrInfoResultCode(
                                ) != oProgressDst.getErrInfoResultCode():
                                    reporter.testFailure('ErrorInfo::resultCode differs - src=%s dst=%s' \
                                                         % (vbox.ComError.toString(oProgressSrc.getErrInfoResultCode()),\
                                                            vbox.ComError.toString(oProgressDst.getErrInfoResultCode())))
                                elif oProgressSrc.getErrInfoText(
                                ) != oProgressDst.getErrInfoText():
                                    reporter.testFailure('ErrorInfo::text differs - src="%s" dst="%s"' \
                                                         % (oProgressSrc.getErrInfoText(), oProgressDst.getErrInfoText()))

                            self.terminateVmBySession(oSessionSrc,
                                                      oProgressSrc)
                    self.terminateVmBySession(oSessionDst, oProgressDst)
                    self.test1ResetVmConfig(oVmSrc, fTeleporterEnabled=False)
                    self.test1ResetVmConfig(oVmDst, fTeleporterEnabled=True)
            else:
                reporter.testFailure('reconfig #2 failed')
        else:
            reporter.testFailure('reconfig #1 failed')
        return reporter.testDone()[1] == 0
Exemple #48
0
    def showUsage(self):
        """
        Extend usage info
        """
        rc = vbox.TestDriver.showUsage(self)
        reporter.log('  --boot-hdd <HDD image file name>')

        reporter.log('  --cpus <# CPUs>')
        reporter.log('  --no-ioapic')
        reporter.log('  --no-nested-paging')
        reporter.log('  --pae')
        reporter.log('  --suspend-host')
        reporter.log('  --suspend-time <sec>')
        reporter.log('  --shutdown-iters <# iters>')
        reporter.log('  --extra-vm')
        reporter.log('  --local-catch')
        return rc
Exemple #49
0
    def _killAllVBoxProcesses(self):
        """
        Kills all virtual box related processes we find in the system.
        """
        sHostOs = utils.getHostOs()
        asDebuggers = [
            'cdb',
            'windbg',
        ] if sHostOs == 'windows' else [
            'gdb', 'gdb-i386-apple-darwin', 'lldb'
        ]

        for iIteration in range(22):
            # Gather processes to kill.
            aoTodo = []
            aoDebuggers = []
            for oProcess in utils.processListAll():
                sBase = oProcess.getBaseImageNameNoExeSuff()
                if sBase is None:
                    continue
                sBase = sBase.lower()
                if sBase in [
                        'vboxsvc',
                        'vboxsds',
                        'virtualbox',
                        'virtualboxvm',
                        'vboxheadless',
                        'vboxmanage',
                        'vboxsdl',
                        'vboxwebsrv',
                        'vboxautostart',
                        'vboxballoonctrl',
                        'vboxbfe',
                        'vboxextpackhelperapp',
                        'vboxnetdhcp',
                        'vboxnetnat',
                        'vboxnetadpctl',
                        'vboxtestogl',
                        'vboxtunctl',
                        'vboxvmmpreload',
                        'vboxxpcomipcd',
                ]:
                    aoTodo.append(oProcess)
                if sBase.startswith('virtualbox-') and sBase.endswith(
                        '-multiarch.exe'):
                    aoTodo.append(oProcess)
                if sBase in asDebuggers:
                    aoDebuggers.append(oProcess)
                    if iIteration in [0, 21]:
                        reporter.log('Warning: debugger running: %s (%s %s)' %
                                     (oProcess.iPid, sBase, oProcess.asArgs))
            if not aoTodo:
                return True

            # Are any of the debugger processes hooked up to a VBox process?
            if sHostOs == 'windows':
                # On demand debugging windows: windbg -p <decimal-pid> -e <decimal-event> -g
                for oDebugger in aoDebuggers:
                    for oProcess in aoTodo:
                        # The whole command line is asArgs[0] here. Fix if that changes.
                        if oDebugger.asArgs and oDebugger.asArgs[0].find(
                                '-p %s ' % (oProcess.iPid, )) >= 0:
                            aoTodo.append(oDebugger)
                            break
            else:
                for oDebugger in aoDebuggers:
                    for oProcess in aoTodo:
                        # Simplistic approach: Just check for argument equaling our pid.
                        if oDebugger.asArgs and (
                                '%s' % oProcess.iPid) in oDebugger.asArgs:
                            aoTodo.append(oDebugger)
                            break

            # Kill.
            for oProcess in aoTodo:
                reporter.log('Loop #%d - Killing %s (%s, uid=%s)' % (
                    iIteration,
                    oProcess.iPid,
                    oProcess.sImage
                    if oProcess.sName is None else oProcess.sName,
                    oProcess.iUid,
                ))
                if    not utils.processKill(oProcess.iPid) \
                  and sHostOs != 'windows' \
                  and utils.processExists(oProcess.iPid):
                    # Many of the vbox processes are initially set-uid-to-root and associated debuggers are running
                    # via sudo, so we might not be able to kill them unless we sudo and use /bin/kill.
                    try:
                        utils.sudoProcessCall(
                            ['/bin/kill', '-9',
                             '%s' % (oProcess.iPid, )])
                    except:
                        reporter.logXcpt()

            # Check if they're all dead like they should be.
            time.sleep(0.1)
            for oProcess in aoTodo:
                if utils.processExists(oProcess.iPid):
                    time.sleep(2)
                    break

        return False
    def showUsage(self):
        """
        Extend usage info
        """
        rc = vbox.TestDriver.showUsage(self)
        reporter.log('')
        reporter.log('tdGuestOsInstTest1 options:')
        reporter.log('  --ioapic, --no-ioapic')
        reporter.log('      Enable or disable the I/O apic.')
        reporter.log('      Default: --ioapic')
        reporter.log('  --pae, --no-pae')
        reporter.log('      Enable or disable PAE support for 32-bit guests.')
        reporter.log('      Default: Guest dependent.')
        reporter.log('  --ram-adjust <MBs>')
        reporter.log(
            '      Adjust the VM ram size by the given delta.  Both negative and positive'
        )
        reporter.log('      values are accepted.')
        reporter.log('  --set-extradata <key>:value')
        reporter.log(
            '      Set VM extra data. This command line option might be used multiple times.'
        )
        reporter.log('obsolete:')
        reporter.log('  --nested-paging, --no-nested-paging')
        reporter.log('  --raw-mode')
        reporter.log('  --cpus <# CPUs>')
        reporter.log('  --install-iso <ISO file name>')

        return rc
Exemple #51
0
 def showUsage(self):
     rc = vbox.TestDriver.showUsage(self)
     reporter.log('')
     reporter.log('tdTeleportLocal1 Options:')
     reporter.log('  --virt-modes   <m1[:m2[:]]')
     reporter.log('      Default: %s' % (':'.join(self.asVirtModesDef)))
     reporter.log('  --cpu-counts   <c1[:c2[:]]')
     reporter.log('      Default: %s' %
                  (':'.join(str(c) for c in self.acCpusDef)))
     reporter.log('  --test-vms     <vm1[:vm2[:...]]>')
     reporter.log(
         '      Test the specified VMs in the given order. Use this to change'
     )
     reporter.log('      the execution order or limit the choice of VMs')
     reporter.log('      Default: %s  (all)' %
                  (':'.join(self.asTestVMsDef)))
     reporter.log('  --skip-vms     <vm1[:vm2[:...]]>')
     reporter.log('      Skip the specified VMs when testing.')
     reporter.log('  --tests        <test1[:test2[:...]]>')
     reporter.log('      Run the specified tests.')
     reporter.log('      Default: %s  (all)' % (':'.join(self.asTestsDef)))
     reporter.log('  --skip-tests   <test1[:test2[:...]]>')
     reporter.log('      Skip the specified VMs when testing.')
     reporter.log('  --quick')
     reporter.log('      Shorthand for: --virt-modes hwvirt --cpu-counts 1')
     reporter.log(
         '                     --test-vms tst-rhel5:tst-win2k3ent:tst-sol10'
     )
     return rc
    def getReconfiguredVm(self,
                          oTestDrv,
                          cCpus,
                          sVirtMode,
                          sParavirtMode=None):
        #
        # Do the standard reconfig in the base class first, it'll figure out
        # if we can run the VM as requested.
        #
        (fRc,
         oVM) = vboxtestvms.TestVm.getReconfiguredVm(self, oTestDrv, cCpus,
                                                     sVirtMode, sParavirtMode)

        #
        # Make sure there is no HD from the previous run attached nor taking
        # up storage on the host.
        #
        if fRc is True:
            fRc = self.detatchAndDeleteHd(oTestDrv)

        #
        # Check for ubuntu installer vs. AMD host CPU.
        #
        if fRc is True and (self.fInstVmFlags & self.kfUbuntuNewAmdBug):
            if self.isHostCpuAffectedByUbuntuNewAmdBug(oTestDrv):
                return (None, None)
                # (skip)

        #
        # Make adjustments to the default config, and adding a fresh HD.
        #
        if fRc is True:
            oSession = oTestDrv.openSession(oVM)
            if oSession is not None:
                if self.sHddControllerType == self.ksSataController:
                    fRc = fRc and oSession.setStorageControllerType(
                        vboxcon.StorageControllerType_IntelAhci,
                        self.sHddControllerType)
                    fRc = fRc and oSession.setStorageControllerPortCount(
                        self.sHddControllerType, 1)

                try:
                    sHddPath = os.path.join(
                        os.path.dirname(oVM.settingsFilePath),
                        '%s-%s-%s.vdi' % (
                            self.sVmName,
                            sVirtMode,
                            cCpus,
                        ))
                except:
                    reporter.errorXcpt()
                    sHddPath = None
                    fRc = False

                fRc = fRc and oSession.createAndAttachHd(
                    sHddPath,
                    cb=self.cGbHdd * 1024 * 1024 * 1024,
                    sController=self.sHddControllerType,
                    iPort=0,
                    fImmutable=False)

                # Set proper boot order
                fRc = fRc and oSession.setBootOrder(
                    1, vboxcon.DeviceType_HardDisk)
                fRc = fRc and oSession.setBootOrder(2, vboxcon.DeviceType_DVD)

                # Adjust memory if requested.
                if self.iOptRamAdjust != 0:
                    fRc = fRc and oSession.setRamSize(
                        oSession.o.machine.memorySize + self.iOptRamAdjust)

                # Set extra data
                for sExtraData in self.asExtraData:
                    try:
                        sKey, sValue = sExtraData.split(':')
                    except ValueError:
                        raise base.InvalidOption(
                            'Invalid extradata specified: %s' % sExtraData)
                    reporter.log('Set extradata: %s => %s' % (sKey, sValue))
                    fRc = fRc and oSession.setExtraData(sKey, sValue)

                # Other variations?

                # Save the settings.
                fRc = fRc and oSession.saveSettings()
                fRc = oSession.close() and fRc
            else:
                fRc = False
            if fRc is not True:
                oVM = None

        # Done.
        return (fRc, oVM)
Exemple #53
0
    def actionConfig(self):
        """
        Configure pre-conditions.
        """

        if not self.importVBoxApi():
            return False

        assert self.sIso is not None
        if self.sIso not in self.kaoVmParams:
            reporter.log('Error: unknown ISO image specified: %s' % self.sIso)
            return False

        # Get VM params specific to ISO image
        cBytesHdd, sKind, sController = self.kaoVmParams[self.sIso]

        # Create VM itself
        eNic0AttachType = vboxcon.NetworkAttachmentType_NAT
        self.sIso = os.path.join(self.sIsoPathBase, self.sIso)
        assert os.path.isfile(self.sIso)

        self.sFloppy = os.path.join(self.sIsoPathBase,
                                    os.path.splitext(self.sIso)[0] + '.img')

        oVM = self.createTestVM(self.sVmName,
                                1,
                                sKind=sKind,
                                sDvdImage=self.sIso,
                                cCpus=self.cCpus,
                                sFloppy=self.sFloppy,
                                eNic0AttachType=eNic0AttachType)
        assert oVM is not None

        oSession = self.openSession(oVM)

        # Create HDD
        sHddPath = os.path.join(self.sScratchPath, self.sHddName)
        fRc = True
        if sController == self.ksSataController:
            fRc = oSession.setStorageControllerType(
                vboxcon.StorageControllerType_IntelAhci, sController)

        fRc = fRc and oSession.createAndAttachHd(sHddPath,
                                                 cb=cBytesHdd,
                                                 sController=sController,
                                                 iPort=0,
                                                 fImmutable=False)
        if sController == self.ksSataController:
            fRc = fRc and oSession.setStorageControllerPortCount(
                sController, 1)

        # Set proper boot order
        fRc = fRc and oSession.setBootOrder(1, vboxcon.DeviceType_HardDisk)
        fRc = fRc and oSession.setBootOrder(2, vboxcon.DeviceType_Floppy)

        # Enable HW virt
        fRc = fRc and oSession.enableVirtEx(True)

        # Enable I/O APIC
        fRc = fRc and oSession.enableIoApic(self.fEnableIOAPIC)

        # Enable Nested Paging
        fRc = fRc and oSession.enableNestedPaging(self.fEnableNestedPaging)

        # Enable PAE
        fRc = fRc and oSession.enablePae(self.fEnablePAE)

        # Remote desktop
        oSession.setupVrdp(True)

        # Set extra data
        if self.asExtraData != []:
            for sExtraData in self.asExtraData:
                try:
                    sKey, sValue = sExtraData.split(':')
                except ValueError:
                    raise base.InvalidOption(
                        'Invalid extradata specified: %s' % sExtraData)
                reporter.log('Set extradata: %s => %s' % (sKey, sValue))
                fRc = fRc and oSession.setExtraData(sKey, sValue)

        fRc = fRc and oSession.saveSettings()
        fRc = oSession.close()
        assert fRc is True

        return vbox.TestDriver.actionConfig(self)