VirtualBox

source: vbox/trunk/src/VBox/ValidationKit/tests/autostart/tdAutostart1.py@ 87114

Last change on this file since 87114 was 87114, checked in by vboxsync, 4 years ago

Main: bugref:9341: Fixed pylint issues

  • Property svn:eol-style set to LF
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 69.4 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3"""
4Autostart testcase using.
5"""
6#from pykickstart.commands import repo
7__copyright__ = \
8"""
9Copyright (C) 2013-2020 Oracle Corporation
10This file is part of VirtualBox Open Source Edition (OSE), as
11available from http://www.virtualbox.org. This file is free software;
12you can redistribute it and/or modify it under the terms of the GNU
13General Public License (GPL) as published by the Free Software
14Foundation, in version 2 as it comes in the "COPYING" file of the
15VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17The contents of this file may alternatively be used under the terms
18of the Common Development and Distribution License Version 1.0
19(CDDL) only, as it comes in the "COPYING.CDDL" file of the
20VirtualBox OSE distribution, in which case the provisions of the
21CDDL are applicable instead of those of the GPL.
22You may elect to license modified versions of this file under the
23terms and conditions of either the GPL or the CDDL or both.
24"""
25__version__ = "$Id: tdAutostart1.py 87114 2020-12-22 16:17:19Z vboxsync $"
26# Standard Python imports.
27import os;
28import sys;
29import re;
30# Only the main script needs to modify the path.
31try: __file__
32except: __file__ = sys.argv[0];
33g_ksValidationKitDir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))));
34sys.path.append(g_ksValidationKitDir);
35# Validation Kit imports.
36from testdriver import reporter;
37from testdriver import base;
38from testdriver import vbox;
39from testdriver import vboxcon;
40from testdriver import vboxtestvms;
41from testdriver import vboxwrappers;
42class VBoxManageStdOutWrapper(object):
43 """ Parser for VBoxManage list runningvms """
44 def __init__(self):
45 self.sVmRunning = '';
46 def __del__(self):
47 self.close();
48 def close(self):
49 """file.close"""
50 return;
51 def read(self, cb):
52 """file.read"""
53 _ = cb;
54 return "";
55 def write(self, sText):
56 """VBoxManage stdout write"""
57 if sText is None:
58 return None;
59 try: sText = str(sText); # pylint: disable=redefined-variable-type
60 except: pass;
61 asLines = sText.splitlines();
62 for sLine in asLines:
63 sLine = sLine.strip();
64 reporter.log('Logging: ' + sLine);
65 # Extract the value
66 idxVmNameStart = sLine.find('"');
67 if idxVmNameStart == -1:
68 raise Exception('VBoxManageStdOutWrapper: Invalid output');
69 idxVmNameStart += 1;
70 idxVmNameEnd = idxVmNameStart;
71 while sLine[idxVmNameEnd] != '"':
72 idxVmNameEnd += 1;
73 self.sVmRunning = sLine[idxVmNameStart:idxVmNameEnd];
74 reporter.log('Logging: ' + self.sVmRunning);
75 return None;
76class tdAutostartOs(vboxtestvms.BaseTestVm):
77 """
78 Base autostart helper class to provide common methods.
79 """
80 # pylint: disable=too-many-arguments
81 def __init__(self, oSet, oTstDrv, sVmName, sKind, sHdd, eNic0Type = None, cMbRam = None, \
82 cCpus = 1, fPae = None, sGuestAdditionsIso = None):
83 vboxtestvms.BaseTestVm.__init__(self, sVmName, oSet = oSet, sKind = sKind);
84 self.oTstDrv = oTstDrv;
85 self.sHdd = sHdd;
86 self.eNic0Type = eNic0Type;
87 self.cMbRam = cMbRam;
88 self.cCpus = cCpus;
89 self.fPae = fPae;
90 self.sGuestAdditionsIso = sGuestAdditionsIso;
91 self._asTestBuildDirs = [];
92 self.sTestBuild = None;
93 self.sVBoxInstaller = "";
94 self.asVirtModesSup = ['hwvirt-np',];
95 self.asParavirtModesSup = ['default',];
96 @property
97 def asTestBuildDirs(self):
98 return self._asTestBuildDirs;
99 @asTestBuildDirs.setter
100 def asTestBuildDirs(self, value):
101 self._asTestBuildDirs = value;
102 self.sTestBuild = self._findFile(self.sVBoxInstaller, value);
103 if not self.sTestBuild:
104 raise base.GenError("VirtualBox install package not found");
105 def _findFile(self, sRegExp, asTestBuildDirs):
106 """
107 Returns a filepath based on the given regex and paths to look into
108 or None if no matching file is found.
109 """
110 oRegExp = re.compile(sRegExp);
111 for sTestBuildDir in asTestBuildDirs:
112 try:
113 #return most recent file if there are several ones matching the pattern
114 asFiles = [s for s in os.listdir(sTestBuildDir)
115 if os.path.isfile(os.path.join(sTestBuildDir, s))];
116 asFiles = (s for s in asFiles
117 if oRegExp.match(os.path.basename(s))
118 and os.path.exists(sTestBuildDir + '/' + s));
119 asFiles = sorted(asFiles, reverse = True,
120 key = lambda s, sTstBuildDir = sTestBuildDir: os.path.getmtime(os.path.join(sTstBuildDir, s)));
121 if asFiles:
122 return sTestBuildDir + '/' + asFiles[0];
123 except:
124 pass;
125 reporter.error('Failed to find a file matching "%s" in %s.' % (sRegExp, ','.join(asTestBuildDirs)));
126 return None;
127 def _createAutostartCfg(self, sDefaultPolicy = 'allow', asUserAllow = (), asUserDeny = ()):
128 """
129 Creates a autostart config for VirtualBox
130 """
131 sVBoxCfg = 'default_policy=' + sDefaultPolicy + '\n';
132 for sUserAllow in asUserAllow:
133 sVBoxCfg = sVBoxCfg + sUserAllow + ' = {\n allow = true\n }\n';
134 for sUserDeny in asUserDeny:
135 sVBoxCfg = sVBoxCfg + sUserDeny + ' = {\n allow = false\n }\n';
136 return sVBoxCfg;
137 def _waitAdditionsIsRunning(self, oGuest, fWaitTrayControl):
138 """
139 Check is the additions running
140 """
141 cAttempt = 0;
142 fRc = False;
143 while cAttempt < 30:
144 fRc = oGuest.additionsRunLevel in [vboxcon.AdditionsRunLevelType_Userland,
145 vboxcon.AdditionsRunLevelType_Desktop];
146 if fRc:
147 eServiceStatus, _ = oGuest.getFacilityStatus(vboxcon.AdditionsFacilityType_VBoxService);
148 fRc = eServiceStatus == vboxcon.AdditionsFacilityStatus_Active;
149 if fRc and not fWaitTrayControl:
150 break;
151 if fRc:
152 eServiceStatus, _ = oGuest.getFacilityStatus(vboxcon.AdditionsFacilityType_VBoxTrayClient);
153 fRc = eServiceStatus == vboxcon.AdditionsFacilityStatus_Active;
154 if fRc:
155 break;
156 self.oTstDrv.sleep(10);
157 cAttempt += 1;
158 return fRc;
159 def createSession(self, oSession, sName, sUser, sPassword, cMsTimeout = 10 * 1000, fIsError = True):
160 """
161 Creates (opens) a guest session.
162 Returns (True, IGuestSession) on success or (False, None) on failure.
163 """
164 oGuest = oSession.o.console.guest;
165 if sName is None:
166 sName = "<untitled>";
167 reporter.log('Creating session "%s" ...' % (sName,));
168 try:
169 oGuestSession = oGuest.createSession(sUser, sPassword, '', sName);
170 except:
171 # Just log, don't assume an error here (will be done in the main loop then).
172 reporter.maybeErrXcpt(fIsError, 'Creating a guest session "%s" failed; sUser="%s", pw="%s"'
173 % (sName, sUser, sPassword));
174 return (False, None);
175 reporter.log('Waiting for session "%s" to start within %dms...' % (sName, cMsTimeout));
176 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start, ];
177 try:
178 waitResult = oGuestSession.waitForArray(aeWaitFor, cMsTimeout);
179 #
180 # Be nice to Guest Additions < 4.3: They don't support session handling and
181 # therefore return WaitFlagNotSupported.
182 #
183 if waitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
184 # Just log, don't assume an error here (will be done in the main loop then).
185 reporter.maybeErr(fIsError, 'Session did not start successfully, returned wait result: %d' % (waitResult,));
186 return (False, None);
187 reporter.log('Session "%s" successfully started' % (sName,));
188 except:
189 # Just log, don't assume an error here (will be done in the main loop then).
190 reporter.maybeErrXcpt(fIsError, 'Waiting for guest session "%s" (usr=%s;pw=%s) to start failed:'
191 % (sName, sUser, sPassword,));
192 return (False, None);
193 return (True, oGuestSession);
194 def closeSession(self, oGuestSession, fIsError = True):
195 """
196 Closes the guest session.
197 """
198 if oGuestSession is not None:
199 try:
200 sName = oGuestSession.name;
201 except:
202 return reporter.errorXcpt();
203 reporter.log('Closing session "%s" ...' % (sName,));
204 try:
205 oGuestSession.close();
206 oGuestSession = None;
207 except:
208 # Just log, don't assume an error here (will be done in the main loop then).
209 reporter.maybeErrXcpt(fIsError, 'Closing guest session "%s" failed:' % (sName,));
210 return False;
211 return True;
212 def guestProcessExecute(self, oGuestSession, sTestName, cMsTimeout, sExecName, asArgs = (),
213 fGetStdOut = True, fIsError = True):
214 """
215 Helper function to execute a program on a guest, specified in the current test.
216 Returns (True, ProcessStatus, ProcessExitCode, ProcessStdOutBuffer) on success or (False, 0, 0, None) on failure.
217 """
218 _ = sTestName;
219 fRc = True; # Be optimistic.
220 reporter.log2('Using session user=%s, name=%s, timeout=%d'
221 % (oGuestSession.user, oGuestSession.name, oGuestSession.timeout,));
222 #
223 # Start the process:
224 #
225 reporter.log2('Executing sCmd=%s, timeoutMS=%d, asArgs=%s'
226 % (sExecName, cMsTimeout, asArgs, ));
227 fTaskFlags = [];
228 if fGetStdOut:
229 fTaskFlags = [vboxcon.ProcessCreateFlag_WaitForStdOut,
230 vboxcon.ProcessCreateFlag_WaitForStdErr];
231 try:
232 oProcess = oGuestSession.processCreate(sExecName,
233 asArgs if self.oTstDrv.fpApiVer >= 5.0 else asArgs[1:],
234 [], fTaskFlags, cMsTimeout);
235 except:
236 reporter.maybeErrXcpt(fIsError, 'asArgs=%s' % (asArgs,));
237 return (False, 0, 0, None);
238 if oProcess is None:
239 return (reporter.error('oProcess is None! (%s)' % (asArgs,)), 0, 0, None);
240 #time.sleep(5); # try this if you want to see races here.
241 # Wait for the process to start properly:
242 reporter.log2('Process start requested, waiting for start (%dms) ...' % (cMsTimeout,));
243 iPid = -1;
244 aeWaitFor = [ vboxcon.ProcessWaitForFlag_Start, ];
245 aBuf = None;
246 try:
247 eWaitResult = oProcess.waitForArray(aeWaitFor, cMsTimeout);
248 except:
249 reporter.maybeErrXcpt(fIsError, 'waitforArray failed for asArgs=%s' % (asArgs,));
250 fRc = False;
251 else:
252 try:
253 eStatus = oProcess.status;
254 iPid = oProcess.PID;
255 except:
256 fRc = reporter.errorXcpt('asArgs=%s' % (asArgs,));
257 else:
258 reporter.log2('Wait result returned: %d, current process status is: %d' % (eWaitResult, eStatus,));
259 #
260 # Wait for the process to run to completion if necessary.
261 #
262 # Note! The above eWaitResult return value can be ignored as it will
263 # (mostly) reflect the process status anyway.
264 #
265 if eStatus == vboxcon.ProcessStatus_Started:
266 # What to wait for:
267 aeWaitFor = [ vboxcon.ProcessWaitForFlag_Terminate,
268 vboxcon.ProcessWaitForFlag_StdOut,
269 vboxcon.ProcessWaitForFlag_StdErr];
270 reporter.log2('Process (PID %d) started, waiting for termination (%dms), aeWaitFor=%s ...'
271 % (iPid, cMsTimeout, aeWaitFor));
272 acbFdOut = [0,0,0];
273 while True:
274 try:
275 eWaitResult = oProcess.waitForArray(aeWaitFor, cMsTimeout);
276 except KeyboardInterrupt: # Not sure how helpful this is, but whatever.
277 reporter.error('Process (PID %d) execution interrupted' % (iPid,));
278 try: oProcess.close();
279 except: pass;
280 break;
281 except:
282 fRc = reporter.errorXcpt('asArgs=%s' % (asArgs,));
283 break;
284 reporter.log2('Wait returned: %d' % (eWaitResult,));
285 # Process output:
286 for eFdResult, iFd, sFdNm in [ (vboxcon.ProcessWaitResult_StdOut, 1, 'stdout'),
287 (vboxcon.ProcessWaitResult_StdErr, 2, 'stderr'), ]:
288 if eWaitResult in (eFdResult, vboxcon.ProcessWaitResult_WaitFlagNotSupported):
289 reporter.log2('Reading %s ...' % (sFdNm,));
290 try:
291 abBuf = oProcess.read(iFd, 64 * 1024, cMsTimeout);
292 except KeyboardInterrupt: # Not sure how helpful this is, but whatever.
293 reporter.error('Process (PID %d) execution interrupted' % (iPid,));
294 try: oProcess.close();
295 except: pass;
296 except:
297 pass; ## @todo test for timeouts and fail on anything else!
298 else:
299 if abBuf:
300 reporter.log2('Process (PID %d) got %d bytes of %s data' % (iPid, len(abBuf), sFdNm,));
301 acbFdOut[iFd] += len(abBuf);
302 ## @todo Figure out how to uniform + append!
303 sBuf = '';
304 if sys.version_info >= (2, 7) and isinstance(abBuf, memoryview):
305 abBuf = abBuf.tobytes();
306 sBuf = abBuf.decode("utf-8");
307 else:
308 sBuf = str(abBuf);
309 if aBuf:
310 aBuf += sBuf;
311 else:
312 aBuf = sBuf;
313 ## Process input (todo):
314 #if eWaitResult in (vboxcon.ProcessWaitResult_StdIn, vboxcon.ProcessWaitResult_WaitFlagNotSupported):
315 # reporter.log2('Process (PID %d) needs stdin data' % (iPid,));
316 # Termination or error?
317 if eWaitResult in (vboxcon.ProcessWaitResult_Terminate,
318 vboxcon.ProcessWaitResult_Error,
319 vboxcon.ProcessWaitResult_Timeout,):
320 try: eStatus = oProcess.status;
321 except: fRc = reporter.errorXcpt('asArgs=%s' % (asArgs,));
322 reporter.log2('Process (PID %d) reported terminate/error/timeout: %d, status: %d'
323 % (iPid, eWaitResult, eStatus,));
324 break;
325 # End of the wait loop.
326 _, cbStdOut, cbStdErr = acbFdOut;
327 try: eStatus = oProcess.status;
328 except: fRc = reporter.errorXcpt('asArgs=%s' % (asArgs,));
329 reporter.log2('Final process status (PID %d) is: %d' % (iPid, eStatus));
330 reporter.log2('Process (PID %d) %d stdout, %d stderr' % (iPid, cbStdOut, cbStdErr));
331 #
332 # Get the final status and exit code of the process.
333 #
334 try:
335 uExitStatus = oProcess.status;
336 iExitCode = oProcess.exitCode;
337 except:
338 fRc = reporter.errorXcpt('asArgs=%s' % (asArgs,));
339 reporter.log2('Process (PID %d) has exit code: %d; status: %d ' % (iPid, iExitCode, uExitStatus));
340 return (fRc, uExitStatus, iExitCode, aBuf);
341 def uploadString(self, oGuestSession, sSrcString, sDst):
342 """
343 Upload the string into guest.
344 """
345 fRc = True;
346 try:
347 oFile = oGuestSession.fileOpenEx(sDst, vboxcon.FileAccessMode_ReadWrite, vboxcon.FileOpenAction_CreateOrReplace,
348 vboxcon.FileSharingMode_All, 0, []);
349 except:
350 fRc = reporter.errorXcpt('Upload string failed. Could not create and open the file %s' % sDst);
351 else:
352 try:
353 oFile.write(bytearray(sSrcString), 60*1000);
354 except:
355 fRc = reporter.errorXcpt('Upload string failed. Could not write the string into the file %s' % sDst);
356 try:
357 oFile.close();
358 except:
359 fRc = reporter.errorXcpt('Upload string failed. Could not close the file %s' % sDst);
360 return fRc;
361 def uploadFile(self, oGuestSession, sSrc, sDst):
362 """
363 Upload the string into guest.
364 """
365 fRc = True;
366 try:
367 if self.oTstDrv.fpApiVer >= 5.0:
368 oCurProgress = oGuestSession.fileCopyToGuest(sSrc, sDst, [0]);
369 else:
370 oCurProgress = oGuestSession.copyTo(sSrc, sDst, [0]);
371 except:
372 reporter.maybeErrXcpt(True, 'Upload file exception for sSrc="%s":'
373 % (self.sGuestAdditionsIso,));
374 fRc = False;
375 else:
376 if oCurProgress is not None:
377 oWrapperProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv, "uploadFile");
378 oWrapperProgress.wait();
379 if not oWrapperProgress.isSuccess():
380 oWrapperProgress.logResult(fIgnoreErrors = False);
381 fRc = False;
382 else:
383 fRc = reporter.error('No progress object returned');
384 return fRc;
385 def downloadFile(self, oGuestSession, sSrc, sDst, fIgnoreErrors = False):
386 """
387 Get a file (sSrc) from the guest storing it on the host (sDst).
388 """
389 fRc = True;
390 try:
391 if self.oTstDrv.fpApiVer >= 5.0:
392 oCurProgress = oGuestSession.fileCopyFromGuest(sSrc, sDst, [0]);
393 else:
394 oCurProgress = oGuestSession.copyFrom(sSrc, sDst, [0]);
395 except:
396 if not fIgnoreErrors:
397 reporter.errorXcpt('Download file exception for sSrc="%s":' % (sSrc,));
398 else:
399 reporter.log('warning: Download file exception for sSrc="%s":' % (sSrc,));
400 fRc = False;
401 else:
402 if oCurProgress is not None:
403 oWrapperProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr,
404 self.oTstDrv, "downloadFile");
405 oWrapperProgress.wait();
406 if not oWrapperProgress.isSuccess():
407 oWrapperProgress.logResult(fIgnoreErrors);
408 fRc = False;
409 else:
410 if not fIgnoreErrors:
411 reporter.error('No progress object returned');
412 else:
413 reporter.log('warning: No progress object returned');
414 fRc = False;
415 return fRc;
416 def downloadFiles(self, oGuestSession, asFiles, fIgnoreErrors = False):
417 """
418 Convenience function to get files from the guest and stores it
419 into the scratch directory for later (manual) review.
420 Returns True on success.
421 Returns False on failure, logged.
422 """
423 fRc = True;
424 for sGstFile in asFiles:
425 ## @todo r=bird: You need to use the guest specific path functions here.
426 ## Best would be to add basenameEx to common/pathutils.py. See how joinEx
427 ## is used by BaseTestVm::pathJoin and such.
428 sTmpFile = os.path.join(self.oTstDrv.sScratchPath, 'tmp-' + os.path.basename(sGstFile));
429 reporter.log2('Downloading file "%s" to "%s" ...' % (sGstFile, sTmpFile));
430 # First try to remove (unlink) an existing temporary file, as we don't truncate the file.
431 try: os.unlink(sTmpFile);
432 except: pass;
433 ## @todo Check for already existing files on the host and create a new
434 # name for the current file to download.
435 fRc = self.downloadFile(oGuestSession, sGstFile, sTmpFile, fIgnoreErrors);
436 if fRc:
437 reporter.addLogFile(sTmpFile, 'misc/other', 'guest - ' + sGstFile);
438 else:
439 if fIgnoreErrors is not True:
440 reporter.error('error downloading file "%s" to "%s"' % (sGstFile, sTmpFile));
441 return fRc;
442 reporter.log('warning: file "%s" was not downloaded, ignoring.' % (sGstFile,));
443 return True;
444 def _checkVmIsReady(self, oGuestSession):
445 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Start a guest process',
446 30 * 1000, '/sbin/ifconfig',
447 ['ifconfig',],
448 False, False);
449 return fRc;
450 def waitVmIsReady(self, oSession, fWaitTrayControl):
451 """
452 Waits the VM is ready after start or reboot.
453 Returns result (true or false) and guest session obtained
454 """
455 _ = fWaitTrayControl;
456 # Give the VM a time to reboot
457 self.oTstDrv.sleep(30);
458 # Waiting the VM is ready.
459 # To do it, one will try to open the guest session and start the guest process in loop
460 if not self._waitAdditionsIsRunning(oSession.o.console.guest, False):
461 return (False, None);
462 cAttempt = 0;
463 oGuestSession = None;
464 fRc = False;
465 while cAttempt < 30:
466 fRc, oGuestSession = self.createSession(oSession, 'Session for user: vbox',
467 'vbox', 'password', 10 * 1000, False);
468 if fRc:
469 fRc = self._checkVmIsReady(oGuestSession);
470 if fRc:
471 break;
472 self.closeSession(oGuestSession, False);
473 self.oTstDrv.sleep(10);
474 cAttempt += 1;
475 return (fRc, oGuestSession);
476 def _rebootVM(self, oGuestSession):
477 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Reboot the VM',
478 30 * 1000, '/usr/bin/sudo',
479 ['sudo', 'reboot'],
480 False, True);
481 if not fRc:
482 reporter.error('Calling the reboot utility failed');
483 return fRc;
484 def rebootVMAndCheckReady(self, oSession, oGuestSession):
485 """
486 Reboot the VM and wait the VM is ready.
487 Returns result and guest session obtained after reboot
488 """
489 reporter.testStart('Reboot VM and wait for readiness');
490 fRc = self._rebootVM(oGuestSession);
491 fRc = self.closeSession(oGuestSession, True) and fRc and True; # pychecker hack.
492 if fRc:
493 (fRc, oGuestSession) = self.waitVmIsReady(oSession, False);
494 if not fRc:
495 reporter.error('VM is not ready after reboot');
496 reporter.testDone();
497 return (fRc, oGuestSession);
498 def _powerDownVM(self, oGuestSession):
499 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Power down the VM',
500 30 * 1000, '/usr/bin/sudo',
501 ['sudo', 'poweroff'],
502 False, True);
503 if not fRc:
504 reporter.error('Calling the poweroff utility failed');
505 return fRc;
506 def powerDownVM(self, oGuestSession):
507 """
508 Power down the VM by calling guest process without wating
509 the VM is really powered off. Also, closes the guest session.
510 It helps the terminateBySession to stop the VM without aborting.
511 """
512 if oGuestSession is None:
513 return False;
514 reporter.testStart('Power down the VM');
515 fRc = self._powerDownVM(oGuestSession);
516 fRc = self.closeSession(oGuestSession, True) and fRc and True; # pychecker hack.
517 if not fRc:
518 reporter.error('Power down the VM failed');
519 reporter.testDone();
520 return fRc;
521 def installAdditions(self, oSession, oGuestSession, oVM):
522 """
523 Installs the Windows guest additions using the test execution service.
524 """
525 _ = oSession;
526 _ = oGuestSession;
527 _ = oVM;
528 reporter.error('Not implemented');
529 return False;
530 def installVirtualBox(self, oGuestSession):
531 """
532 Install VirtualBox in the guest.
533 """
534 _ = oGuestSession;
535 reporter.error('Not implemented');
536 return False;
537 def configureAutostart(self, oGuestSession, sDefaultPolicy = 'allow', asUserAllow = (), asUserDeny = ()):
538 """
539 Configures the autostart feature in the guest.
540 """
541 _ = oGuestSession;
542 _ = sDefaultPolicy;
543 _ = asUserAllow;
544 _ = asUserDeny;
545 reporter.error('Not implemented');
546 return False;
547 def createUser(self, oGuestSession, sUser):
548 """
549 Create a new user with the given name
550 """
551 _ = oGuestSession;
552 _ = sUser;
553 reporter.error('Not implemented');
554 return False;
555 def checkForRunningVM(self, oSession, oGuestSession, sUser, sVmName):
556 """
557 Check for VM running in the guest after autostart.
558 Due to the sUser is created whithout password,
559 all calls will be perfomed using 'sudo -u sUser'
560 """
561 _ = oSession;
562 _ = oGuestSession;
563 _ = sUser;
564 _ = sVmName;
565 reporter.error('Not implemented');
566 return False;
567 def getResourceSet(self):
568 asRet = [];
569 if not os.path.isabs(self.sHdd):
570 asRet.append(self.sHdd);
571 return asRet;
572 def _createVmDoIt(self, oTestDrv, eNic0AttachType, sDvdImage):
573 """
574 Creates the VM.
575 Returns Wrapped VM object on success, None on failure.
576 """
577 _ = eNic0AttachType;
578 _ = sDvdImage;
579 return oTestDrv.createTestVM(self.sVmName, self.iGroup, self.sHdd, sKind = self.sKind, \
580 fIoApic = True, eNic0AttachType = vboxcon.NetworkAttachmentType_NAT, \
581 eNic0Type = self.eNic0Type, cMbRam = self.cMbRam, \
582 sHddControllerType = "SATA Controller", fPae = self.fPae, \
583 cCpus = self.cCpus, sDvdImage = self.sGuestAdditionsIso);
584 def _createVmPost(self, oTestDrv, oVM, eNic0AttachType, sDvdImage):
585 _ = eNic0AttachType;
586 _ = sDvdImage;
587 fRc = True;
588 oSession = oTestDrv.openSession(oVM);
589 if oSession is not None:
590 fRc = fRc and oSession.enableVirtEx(True);
591 fRc = fRc and oSession.enableNestedPaging(True);
592 fRc = fRc and oSession.enableNestedHwVirt(True);
593 # disable 3D until the error is fixed.
594 fRc = fRc and oSession.setAccelerate3DEnabled(False);
595 fRc = fRc and oSession.setVRamSize(256);
596 fRc = fRc and oSession.setVideoControllerType(vboxcon.GraphicsControllerType_VBoxSVGA);
597 fRc = fRc and oSession.enableUsbOhci(True);
598 fRc = fRc and oSession.enableUsbHid(True);
599 fRc = fRc and oSession.saveSettings();
600 fRc = oSession.close() and fRc and True; # pychecker hack.
601 oSession = None;
602 else:
603 fRc = False;
604 return oVM if fRc else None;
605 def getReconfiguredVm(self, oTestDrv, cCpus, sVirtMode, sParavirtMode = None):
606 #
607 # Current test uses precofigured VMs. This override disables any changes in the machine.
608 #
609 _ = cCpus;
610 _ = sVirtMode;
611 _ = sParavirtMode;
612 oVM = oTestDrv.getVmByName(self.sVmName);
613 if oVM is None:
614 return (False, None);
615 return (True, oVM);
616class tdAutostartOsLinux(tdAutostartOs):
617 """
618 Autostart support methods for Linux guests.
619 """
620 # pylint: disable=too-many-arguments
621 def __init__(self, oSet, oTstDrv, sVmName, sKind, sHdd, eNic0Type = None, cMbRam = None, \
622 cCpus = 1, fPae = None, sGuestAdditionsIso = None):
623 tdAutostartOs.__init__(self, oSet, oTstDrv, sVmName, sKind, sHdd, eNic0Type, cMbRam, \
624 cCpus, fPae, sGuestAdditionsIso);
625 self.sVBoxInstaller = '^VirtualBox-.*\\.run$';
626 return;
627 def installAdditions(self, oSession, oGuestSession, oVM):
628 """
629 Install guest additions in the guest.
630 """
631 reporter.testStart('Install Guest Additions');
632 fRc = False;
633 # Install Kernel headers, which are required for actually installing the Linux Additions.
634 if oVM.OSTypeId.startswith('Debian') \
635 or oVM.OSTypeId.startswith('Ubuntu'):
636 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Installing Kernel headers',
637 5 * 60 *1000, '/usr/bin/apt-get',
638 ['/usr/bin/apt-get', 'install', '-y',
639 'linux-headers-generic'],
640 False, True);
641 if not fRc:
642 reporter.error('Error installing Kernel headers');
643 else:
644 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Installing Guest Additions depdendencies',
645 5 * 60 *1000, '/usr/bin/apt-get',
646 ['/usr/bin/apt-get', 'install', '-y', 'build-essential',
647 'perl'], False, True);
648 if not fRc:
649 reporter.error('Error installing additional installer dependencies');
650 elif oVM.OSTypeId.startswith('OL') \
651 or oVM.OSTypeId.startswith('Oracle') \
652 or oVM.OSTypeId.startswith('RHEL') \
653 or oVM.OSTypeId.startswith('Redhat') \
654 or oVM.OSTypeId.startswith('Cent'):
655 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Installing Kernel headers',
656 5 * 60 *1000, '/usr/bin/yum',
657 ['/usr/bin/yum', '-y', 'install', 'kernel-headers'],
658 False, True);
659 if not fRc:
660 reporter.error('Error installing Kernel headers');
661 else:
662 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Installing Guest Additions depdendencies',
663 5 * 60 *1000, '/usr/bin/yum',
664 ['/usr/bin/yum', '-y', 'install', 'make', 'automake', 'gcc',
665 'kernel-devel', 'dkms', 'bzip2', 'perl'], False, True);
666 if not fRc:
667 reporter.error('Error installing additional installer dependencies');
668 else:
669 reporter.error('Installing Linux Additions for the "%s" is not supported yet' % oVM.OSTypeId);
670 fRc = False;
671 if fRc:
672 #
673 # The actual install.
674 # Also tell the installer to produce the appropriate log files.
675 #
676 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Installing guest additions',
677 10 * 60 *1000, '/usr/bin/sudo',
678 ['/usr/bin/sudo', '/bin/sh',
679 '/media/cdrom/VBoxLinuxAdditions.run'],
680 False, True);
681 if fRc:
682 # Due to the GA updates as separate process the above function returns before
683 # the actual installation finished. So just wait until the GA installed
684 fRc = self.closeSession(oGuestSession);
685 if fRc:
686 (fRc, oGuestSession) = self.waitVmIsReady(oSession, False);
687 # Download log files.
688 # Ignore errors as all files above might not be present for whatever reason.
689 #
690 if fRc:
691 asLogFile = [];
692 asLogFile.append('/var/log/vboxadd-install.log');
693 self.downloadFiles(oGuestSession, asLogFile, fIgnoreErrors = True);
694 else:
695 reporter.error('Installing guest additions failed: Error occured during vbox installer execution')
696 if fRc:
697 (fRc, oGuestSession) = self.rebootVMAndCheckReady(oSession, oGuestSession);
698 if not fRc:
699 reporter.error('Reboot after installing GuestAdditions failed');
700 reporter.testDone();
701 return (fRc, oGuestSession);
702 def installVirtualBox(self, oGuestSession):
703 """
704 Install VirtualBox in the guest.
705 """
706 if self.sTestBuild is None:
707 return False;
708 reporter.testStart('Install Virtualbox into the guest VM');
709 reporter.log("Virtualbox install file: %s" % os.path.basename(self.sTestBuild));
710 fRc = self.uploadFile(oGuestSession, self.sTestBuild,
711 '/tmp/' + os.path.basename(self.sTestBuild));
712 if not fRc:
713 reporter.error('Upload the vbox installer into guest VM failed');
714 else:
715 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession,
716 'Allowing execution for the vbox installer',
717 30 * 1000, '/usr/bin/sudo',
718 ['/usr/bin/sudo', '/bin/chmod', '755',
719 '/tmp/' + os.path.basename(self.sTestBuild)],
720 False, True);
721 if not fRc:
722 reporter.error('Allowing execution for the vbox installer failed');
723 if fRc:
724 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Installing VBox',
725 240 * 1000, '/usr/bin/sudo',
726 ['/usr/bin/sudo',
727 '/tmp/' + os.path.basename(self.sTestBuild),],
728 False, True);
729 if not fRc:
730 reporter.error('Installing VBox failed');
731 reporter.testDone();
732 return fRc;
733 def configureAutostart(self, oGuestSession, sDefaultPolicy = 'allow', asUserAllow = (), asUserDeny = ()):
734 """
735 Configures the autostart feature in the guest.
736 """
737 reporter.testStart('Configure autostart');
738 # Create autostart database directory writeable for everyone
739 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Creating autostart database',
740 30 * 1000, '/usr/bin/sudo',
741 ['/usr/bin/sudo', '/bin/mkdir', '-m', '1777', '/etc/vbox/autostart.d'],
742 False, True);
743 if not fRc:
744 reporter.error('Creating autostart database failed');
745 # Create /etc/default/virtualbox
746 if fRc:
747 sVBoxCfg = 'VBOXAUTOSTART_CONFIG=/etc/vbox/autostart.cfg\n' \
748 + 'VBOXAUTOSTART_DB=/etc/vbox/autostart.d\n';
749 fRc = self.uploadString(oGuestSession, sVBoxCfg, '/tmp/virtualbox');
750 if not fRc:
751 reporter.error('Upload to /tmp/virtualbox failed');
752 if fRc:
753 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Moving to destination',
754 30 * 1000, '/usr/bin/sudo',
755 ['/usr/bin/sudo', '/bin/mv', '/tmp/virtualbox',
756 '/etc/default/virtualbox'],
757 False, True);
758 if not fRc:
759 reporter.error('Moving the /tmp/virtualbox to destination failed');
760 if fRc:
761 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Setting permissions',
762 30 * 1000, '/usr/bin/sudo',
763 ['/usr/bin/sudo', '/bin/chmod', '644',
764 '/etc/default/virtualbox'],
765 False, True);
766 if not fRc:
767 reporter.error('Setting permissions for the virtualbox failed');
768 if fRc:
769 sVBoxCfg = self._createAutostartCfg(sDefaultPolicy, asUserAllow, asUserDeny);
770 fRc = self.uploadString(oGuestSession, sVBoxCfg, '/tmp/autostart.cfg');
771 if not fRc:
772 reporter.error('Upload to /tmp/autostart.cfg failed');
773 if fRc:
774 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Moving to destination',
775 30 * 1000, '/usr/bin/sudo',
776 ['/usr/bin/sudo', '/bin/mv', '/tmp/autostart.cfg',
777 '/etc/vbox/autostart.cfg'],
778 False, True);
779 if not fRc:
780 reporter.error('Moving the /tmp/autostart.cfg to destination failed');
781 if fRc:
782 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Setting permissions',
783 30 * 1000, '/usr/bin/sudo',
784 ['/usr/bin/sudo', '/bin/chmod', '644',
785 '/etc/vbox/autostart.cfg'],
786 False, True);
787 if not fRc:
788 reporter.error('Setting permissions for the autostart.cfg failed');
789 reporter.testDone();
790 return fRc;
791 def createUser(self, oGuestSession, sUser):
792 """
793 Create a new user with the given name
794 """
795 reporter.testStart('Create user %s' % sUser);
796 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Creating new user',
797 30 * 1000, '/usr/bin/sudo',
798 ['/usr/bin/sudo', '/usr/sbin/useradd', '-m', '-U',
799 sUser], False, True);
800 if not fRc:
801 reporter.error('Create user %s failed' % sUser);
802 reporter.testDone();
803 return fRc;
804 # pylint: enable=too-many-arguments
805 def createTestVM(self, oSession, oGuestSession, sUser, sVmName):
806 """
807 Create a test VM in the guest and enable autostart.
808 Due to the sUser is created whithout password,
809 all calls will be perfomed using 'sudo -u sUser'
810 """
811 _ = oSession;
812 reporter.testStart('Create test VM for user %s' % sUser);
813 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Configuring autostart database',
814 30 * 1000, '/usr/bin/sudo',
815 ['/usr/bin/sudo', '-u', sUser, '-H', '/opt/VirtualBox/VBoxManage',
816 'setproperty', 'autostartdbpath', '/etc/vbox/autostart.d'],
817 False, True);
818 if not fRc:
819 reporter.error('Configuring autostart database failed');
820 else:
821 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Create VM ' + sVmName,
822 30 * 1000, '/usr/bin/sudo',
823 ['/usr/bin/sudo', '-u', sUser, '-H',
824 '/opt/VirtualBox/VBoxManage', 'createvm',
825 '--name', sVmName, '--register'], False, True);
826 if not fRc:
827 reporter.error('Create VM %s failed' % sVmName);
828 if fRc:
829 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Enabling autostart for test VM',
830 30 * 1000, '/usr/bin/sudo',
831 ['/usr/bin/sudo', '-u', sUser, '-H',
832 '/opt/VirtualBox/VBoxManage', 'modifyvm',
833 sVmName, '--autostart-enabled', 'on'], False, True);
834 if not fRc:
835 reporter.error('Enabling autostart for %s failed' % sVmName);
836 reporter.testDone();
837 return fRc;
838 def checkForRunningVM(self, oSession, oGuestSession, sUser, sVmName):
839 """
840 Check for VM running in the guest after autostart.
841 Due to the sUser is created whithout password,
842 all calls will be perfomed using 'sudo -u sUser'
843 """
844 self.oTstDrv.sleep(30);
845 _ = oSession;
846 reporter.testStart('Check the VM %s is running for user %s' % (sVmName, sUser));
847 (fRc, _, _, aBuf) = self.guestProcessExecute(oGuestSession, 'Check for running VM',
848 30 * 1000, '/usr/bin/sudo',
849 ['/usr/bin/sudo', '-u', sUser, '-H',
850 '/opt/VirtualBox/VBoxManage',
851 'list', 'runningvms'], True, True);
852 if not fRc:
853 reporter.error('Checking the VM %s is running for user %s failed' % (sVmName, sUser));
854 else:
855 bufWrapper = VBoxManageStdOutWrapper();
856 bufWrapper.write(aBuf);
857 fRc = bufWrapper.sVmRunning == sVmName;
858 reporter.testDone();
859 return fRc;
860class tdAutostartOsDarwin(tdAutostartOs):
861 """
862 Autostart support methods for Darwin guests.
863 """
864 # pylint: disable=too-many-arguments
865 def __init__(self, oSet, oTstDrv, sVmName, sKind, sHdd, eNic0Type = None, cMbRam = None, \
866 cCpus = 1, fPae = None, sGuestAdditionsIso = None):
867 tdAutostartOs.__init__(self, oSet, oTstDrv, sVmName, sKind, sHdd, eNic0Type, cMbRam, \
868 cCpus, fPae, sGuestAdditionsIso);
869 raise base.GenError('Testing the autostart functionality for Darwin is not implemented');
870class tdAutostartOsSolaris(tdAutostartOs):
871 """
872 Autostart support methods for Solaris guests.
873 """
874 # pylint: disable=too-many-arguments
875 def __init__(self, oSet, oTstDrv, sVmName, sKind, sHdd, eNic0Type = None, cMbRam = None, \
876 cCpus = 1, fPae = None, sGuestAdditionsIso = None):
877 tdAutostartOs.__init__(self, oSet, oTstDrv, sVmName, sKind, sHdd, eNic0Type, cMbRam, \
878 cCpus, fPae, sGuestAdditionsIso);
879 raise base.GenError('Testing the autostart functionality for Solaris is not implemented');
880class tdAutostartOsWin(tdAutostartOs):
881 """
882 Autostart support methods for Windows guests.
883 """
884 # pylint: disable=too-many-arguments
885 def __init__(self, oSet, oTstDrv, sVmName, sKind, sHdd, eNic0Type = None, cMbRam = None, \
886 cCpus = 1, fPae = None, sGuestAdditionsIso = None):
887 tdAutostartOs.__init__(self, oSet, oTstDrv, sVmName, sKind, sHdd, eNic0Type, cMbRam, \
888 cCpus, fPae, sGuestAdditionsIso);
889 self.sVBoxInstaller = '^VirtualBox-.*\\.(exe|msi)$';
890 return;
891 def _checkVmIsReady(self, oGuestSession):
892 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Start a guest process',
893 30 * 1000, 'C:\\Windows\\System32\\ipconfig.exe',
894 ['C:\\Windows\\System32\\ipconfig.exe',],
895 False, False);
896 return fRc;
897 def _rebootVM(self, oGuestSession):
898 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Reboot the VM',
899 30 * 1000, 'C:\\Windows\\System32\\shutdown.exe',
900 ['C:\\Windows\\System32\\shutdown.exe', '/f',
901 '/r', '/t', '0'],
902 False, True);
903 if not fRc:
904 reporter.error('Calling the shutdown utility failed');
905 return fRc;
906 def _powerDownVM(self, oGuestSession):
907 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Power down the VM',
908 30 * 1000, 'C:\\Windows\\System32\\shutdown.exe',
909 ['C:\\Windows\\System32\\shutdown.exe', '/f',
910 '/s', '/t', '0'],
911 False, True);
912 if not fRc:
913 reporter.error('Calling the shutdown utility failed');
914 return fRc;
915 def installAdditions(self, oSession, oGuestSession, oVM):
916 """
917 Installs the Windows guest additions using the test execution service.
918 """
919 _ = oVM;
920 reporter.testStart('Install Guest Additions');
921 asLogFiles = [];
922 fRc = self.closeSession(oGuestSession, True); # pychecker hack.
923 try:
924 oCurProgress = oSession.o.console.guest.updateGuestAdditions(self.sGuestAdditionsIso, ['/l',], None);
925 except:
926 reporter.maybeErrXcpt(True, 'Updating Guest Additions exception for sSrc="%s":'
927 % (self.sGuestAdditionsIso,));
928 fRc = False;
929 else:
930 if oCurProgress is not None:
931 oWrapperProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr,
932 self.oTstDrv, "installAdditions");
933 oWrapperProgress.wait(cMsTimeout = 10 * 60 * 1000);
934 if not oWrapperProgress.isSuccess():
935 oWrapperProgress.logResult(fIgnoreErrors = False);
936 fRc = False;
937 else:
938 fRc = reporter.error('No progress object returned');
939 #---------------------------------------
940 #
941 ##
942 ## Install the public signing key.
943 ##
944 #
945 #self.oTstDrv.sleep(60 * 2);
946 #
947 #if oVM.OSTypeId not in ('WindowsNT4', 'Windows2000', 'WindowsXP', 'Windows2003'):
948 # (fRc, _, _, _) = \
949 # self.guestProcessExecute(oGuestSession, 'Installing SHA1 certificate',
950 # 60 * 1000, 'D:\\cert\\VBoxCertUtil.exe',
951 # ['D:\\cert\\VBoxCertUtil.exe', 'add-trusted-publisher',
952 # 'D:\\cert\\vbox-sha1.cer'],
953 # False, True);
954 # if not fRc:
955 # reporter.error('Error installing SHA1 certificate');
956 # else:
957 # (fRc, _, _, _) = \
958 # self.guestProcessExecute(oGuestSession, 'Installing SHA1 certificate',
959 # 60 * 1000, 'D:\\cert\\VBoxCertUtil.exe',
960 # ['D:\\cert\\VBoxCertUtil.exe', 'add-trusted-publisher',
961 # 'D:\\cert\\vbox-sha256.cer'],
962 # False, True);
963 # if not fRc:
964 # reporter.error('Error installing SHA256 certificate');
965 #
966 #(fRc, _, _, _) = \
967 # self.guestProcessExecute(oGuestSession, 'Installing GA',
968 # 60 * 1000, 'D:\\VBoxWindowsAdditions.exe',
969 # ['D:\\VBoxWindowsAdditions.exe', '/S', '/l',
970 # '/no_vboxservice_exit'],
971 # False, True);
972 #
973 #if fRc:
974 # # Due to the GA updates as separate process the above function returns before
975 # # the actual installation finished. So just wait until the GA installed
976 # fRc = self.closeSession(oGuestSession, True);
977 # if fRc:
978 # (fRc, oGuestSession) = self.waitVmIsReady(oSession, False, False);
979 #---------------------------------------
980 # Store the result and try download logs anyway.
981 fGaRc = fRc;
982 fRc, oGuestSession = self.createSession(oSession, 'Session for user: vbox',
983 'vbox', 'password', 10 * 1000, True);
984 if fRc is True:
985 (fRc, oGuestSession) = self.rebootVMAndCheckReady(oSession, oGuestSession);
986 if fRc is True:
987 # Add the Windows Guest Additions installer files to the files we want to download
988 # from the guest.
989 sGuestAddsDir = 'C:/Program Files/Oracle/VirtualBox Guest Additions/';
990 asLogFiles.append(sGuestAddsDir + 'install.log');
991 # Note: There won't be a install_ui.log because of the silent installation.
992 asLogFiles.append(sGuestAddsDir + 'install_drivers.log');
993 # Download log files.
994 # Ignore errors as all files above might not be present (or in different locations)
995 # on different Windows guests.
996 #
997 self.downloadFiles(oGuestSession, asLogFiles, fIgnoreErrors = True);
998 else:
999 reporter.error('Reboot after installing GuestAdditions failed');
1000 else:
1001 reporter.error('Create session for user vbox after GA updating failed');
1002 reporter.testDone();
1003 return (fRc and fGaRc, oGuestSession);
1004 def installVirtualBox(self, oGuestSession):
1005 """
1006 Install VirtualBox in the guest.
1007 """
1008 if self.sTestBuild is None:
1009 return False;
1010 reporter.testStart('Install Virtualbox into the guest VM');
1011 reporter.log("Virtualbox install file: %s" % os.path.basename(self.sTestBuild));
1012 # Used windows image already contains the C:\Temp
1013 fRc = self.uploadFile(oGuestSession, self.sTestBuild,
1014 'C:\\Temp\\' + os.path.basename(self.sTestBuild));
1015 if not fRc:
1016 reporter.error('Upload the installing into guest VM failed');
1017 else:
1018 if self.sTestBuild.endswith('.msi'):
1019 sLogFile = 'C:/Temp/VBoxInstallLog.txt';
1020 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Installing VBox',
1021 600 * 1000, 'C:\\Windows\\System32\\msiexec.exe',
1022 ['msiexec', '/quiet', '/norestart', '/i',
1023 'C:\\Temp\\' + os.path.basename(self.sTestBuild),
1024 '/lv', sLogFile],
1025 False, True);
1026 if not fRc:
1027 reporter.error('Installing the VBox from msi installer failed');
1028 else:
1029 sLogFile = 'C:/Temp/Virtualbox/VBoxInstallLog.txt';
1030 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Installing VBox',
1031 600 * 1000, 'C:\\Temp\\' + os.path.basename(self.sTestBuild),
1032 ['C:\\Temp\\' + os.path.basename(self.sTestBuild), '-vvvv',
1033 '--silent', '--logging',
1034 '--msiparams', 'REBOOT=ReallySuppress'],
1035 False, True);
1036 if not fRc:
1037 reporter.error('Installing the VBox failed');
1038 else:
1039 (_, _, _, aBuf) = self.guestProcessExecute(oGuestSession, 'Check installation',
1040 240 * 1000, 'C:\\Windows\\System32\\cmd.exe',
1041 ['c:\\Windows\\System32\\cmd.exe', '/c',
1042 'dir', 'C:\\Program Files\\Oracle\\VirtualBox\\*.*'],
1043 True, True);
1044 reporter.log('Content of VirtualBxox folder:');
1045 reporter.log(str(aBuf));
1046 asLogFiles = [sLogFile,];
1047 self.downloadFiles(oGuestSession, asLogFiles, fIgnoreErrors = True);
1048 reporter.testDone();
1049 return fRc;
1050 def configureAutostart(self, oGuestSession, sDefaultPolicy = 'allow', asUserAllow = (), asUserDeny = ()):
1051 """
1052 Configures the autostart feature in the guest.
1053 """
1054 reporter.testStart('Configure autostart');
1055 # Create autostart database directory writeable for everyone
1056 (fRc, _, _, _) = \
1057 self.guestProcessExecute(oGuestSession, 'Setting the autostart environment variable',
1058 30 * 1000, 'C:\\Windows\\System32\\reg.exe',
1059 ['reg', 'add',
1060 'HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment',
1061 '/v', 'VBOXAUTOSTART_CONFIG', '/d',
1062 'C:\\ProgramData\\autostart.cfg', '/f'],
1063 False, True);
1064 if fRc:
1065 sVBoxCfg = self._createAutostartCfg(sDefaultPolicy, asUserAllow, asUserDeny);
1066 fRc = self.uploadString(oGuestSession, sVBoxCfg, 'C:\\ProgramData\\autostart.cfg');
1067 if not fRc:
1068 reporter.error('Upload the autostart.cfg failed');
1069 else:
1070 reporter.error('Setting the autostart environment variable failed');
1071 reporter.testDone();
1072 return fRc;
1073 def createTestVM(self, oSession, oGuestSession, sUser, sVmName):
1074 """
1075 Create a test VM in the guest and enable autostart.
1076 """
1077 _ = oGuestSession;
1078 reporter.testStart('Create test VM for user %s' % sUser);
1079 fRc, oGuestSession = self.createSession(oSession, 'Session for user: %s' % (sUser,),
1080 sUser, 'password', 10 * 1000, True);
1081 if not fRc:
1082 reporter.error('Create session for user %s failed' % sUser);
1083 else:
1084 (fRc, _, _, _) = \
1085 self.guestProcessExecute(oGuestSession, 'Create VM ' + sVmName,
1086 30 * 1000, 'C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe',
1087 ['C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe', 'createvm',
1088 '--name', sVmName, '--register'], False, True);
1089 if not fRc:
1090 reporter.error('Create VM %s for user %s failed' % (sVmName, sUser));
1091 else:
1092 (fRc, _, _, _) = \
1093 self.guestProcessExecute(oGuestSession, 'Enabling autostart for test VM',
1094 30 * 1000, 'C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe',
1095 ['C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe',
1096 'modifyvm', sVmName, '--autostart-enabled', 'on'], False, True);
1097 if not fRc:
1098 reporter.error('Enabling autostart for VM %s for user %s failed' % (sVmName, sUser));
1099 if fRc:
1100 fRc = self.uploadString(oGuestSession, 'password', 'C:\\ProgramData\\password.cfg');
1101 if not fRc:
1102 reporter.error('Upload the password.cfg failed');
1103 if fRc:
1104 (fRc, _, _, _) = \
1105 self.guestProcessExecute(oGuestSession, 'Install autostart service for the user',
1106 30 * 1000, 'C:\\Program Files\\Oracle\\VirtualBox\\VBoxAutostartSvc.exe',
1107 ['C:\\Program Files\\Oracle\\VirtualBox\\VBoxAutostartSvc.exe',
1108 'install', '--user=' + sUser,
1109 '--password-file=C:\\ProgramData\\password.cfg'],
1110 False, True);
1111 if not fRc:
1112 reporter.error('Install autostart service for user %s failed' % sUser);
1113 fRc1 = self.closeSession(oGuestSession, True);
1114 if not fRc1:
1115 reporter.error('Closing session for user %s failed' % sUser);
1116 fRc = fRc1 and fRc and True; # pychecker hack.
1117 reporter.testDone();
1118 return fRc;
1119 def checkForRunningVM(self, oSession, oGuestSession, sUser, sVmName):
1120 """
1121 Check for VM running in the guest after autostart.
1122 """
1123 self.oTstDrv.sleep(30);
1124 _ = oGuestSession;
1125 reporter.testStart('Check the VM %s is running for user %s' % (sVmName, sUser));
1126 fRc, oGuestSession = self.createSession(oSession, 'Session for user: %s' % (sUser,),
1127 sUser, 'password', 10 * 1000, True);
1128 if not fRc:
1129 reporter.error('Create session for user %s failed' % sUser);
1130 else:
1131 (fRc, _, _, aBuf) = self.guestProcessExecute(oGuestSession, 'Check for running VM',
1132 60 * 1000, 'C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe',
1133 [ 'C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe',
1134 'list', 'runningvms' ], True, True);
1135 if not fRc:
1136 reporter.error('Checking the VM %s is running for user %s failed' % (sVmName, sUser));
1137 else:
1138 bufWrapper = VBoxManageStdOutWrapper();
1139 bufWrapper.write(aBuf);
1140 fRc = bufWrapper.sVmRunning == sVmName;
1141 fRc1 = self.closeSession(oGuestSession, True);
1142 if not fRc1:
1143 reporter.error('Closing session for user %s failed' % sUser);
1144 fRc = fRc1 and fRc and True; # pychecker hack.
1145 reporter.testDone();
1146 return fRc;
1147 def createUser(self, oGuestSession, sUser):
1148 """
1149 Create a new user with the given name
1150 """
1151 reporter.testStart('Create user %s' % sUser);
1152 # Create user
1153 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Creating user %s to run a VM' % sUser,
1154 30 * 1000, 'C:\\Windows\\System32\\net.exe',
1155 ['net', 'user', sUser, 'password', '/add' ], False, True);
1156 if not fRc:
1157 reporter.error('Creating user %s to run a VM failed' % sUser);
1158 # Add the user to Administrators group
1159 else:
1160 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession, 'Adding the user %s to Administrators group' % sUser,
1161 30 * 1000, 'C:\\Windows\\System32\\net.exe',
1162 ['net', 'localgroup', 'Administrators', sUser, '/add' ], False, True);
1163 if not fRc:
1164 reporter.error('Adding the user %s to Administrators group failed' % sUser);
1165 #Allow the user to logon as service
1166 if fRc:
1167 sSecPolicyEditor = """
1168$sUser = '%s'
1169$oUser = New-Object System.Security.Principal.NTAccount("$sUser")
1170$oSID = $oUser.Translate([System.Security.Principal.SecurityIdentifier])
1171$sExportFile = 'C:\\Temp\\cfg.inf'
1172$sSecDb = 'C:\\Temp\\secedt.sdb'
1173$sImportFile = 'C:\\Temp\\newcfg.inf'
1174secedit /export /cfg $sExportFile
1175$sCurrServiceLogonRight = Get-Content -Path $sExportFile |
1176 Where-Object {$_ -Match 'SeServiceLogonRight'}
1177$asFileContent = @'
1178[Unicode]
1179Unicode=yes
1180[System Access]
1181[Event Audit]
1182[Registry Values]
1183[Version]
1184signature="$CHICAGO$"
1185Revision=1
1186[Profile Description]
1187Description=GrantLogOnAsAService security template
1188[Privilege Rights]
1189{0}*{1}
1190'@ -f $(
1191 if($sCurrServiceLogonRight){"$sCurrServiceLogonRight,"}
1192 else{'SeServiceLogonRight = '}
1193 ), $oSid.Value
1194Set-Content -Path $sImportFile -Value $asFileContent
1195secedit /import /db $sSecDb /cfg $sImportFile
1196secedit /configure /db $sSecDb
1197Remove-Item -Path $sExportFile
1198Remove-Item -Path $sSecDb
1199Remove-Item -Path $sImportFile
1200 """ % (sUser,);
1201 fRc = self.uploadString(oGuestSession, sSecPolicyEditor, 'C:\\Temp\\adjustsec.ps1');
1202 if not fRc:
1203 reporter.error('Upload the adjustsec.ps1 failed');
1204 if fRc:
1205 (fRc, _, _, _) = self.guestProcessExecute(oGuestSession,
1206 'Setting the "Logon as service" policy to the user %s' % sUser,
1207 300 * 1000, 'C:\\Windows\\System32\\cmd.exe',
1208 ['cmd.exe', '/c', "type C:\\Temp\\adjustsec.ps1 | powershell -"],
1209 False, True);
1210 if not fRc:
1211 reporter.error('Setting the "Logon as service" policy to the user %s failed' % sUser);
1212 try:
1213 oGuestSession.fsObjRemove('C:\\Temp\\adjustsec.ps1');
1214 except:
1215 fRc = reporter.errorXcpt('Removing policy script failed');
1216 reporter.testDone();
1217 return fRc;
1218class tdAutostart(vbox.TestDriver): # pylint: disable=too-many-instance-attributes
1219 """
1220 Autostart testcase.
1221 """
1222 ksOsLinux = 'tst-linux'
1223 ksOsWindows = 'tst-win'
1224 ksOsDarwin = 'tst-darwin'
1225 ksOsSolaris = 'tst-solaris'
1226 ksOsFreeBSD = 'tst-freebsd'
1227 def __init__(self):
1228 vbox.TestDriver.__init__(self);
1229 self.asRsrcs = None;
1230 self.asTestVMsDef = [self.ksOsWindows, self.ksOsLinux]; #[self.ksOsLinux, self.ksOsWindows];
1231 self.asTestVMs = self.asTestVMsDef;
1232 self.asSkipVMs = [];
1233 ## @todo r=bird: The --test-build-dirs option as primary way to get the installation files to test
1234 ## is not an acceptable test practice as we don't know wtf you're testing. See defect for more.
1235 self.asTestBuildDirs = None; #'D:/AlexD/TestBox/TestAdditionalFiles';
1236 self.sGuestAdditionsIso = None; #'D:/AlexD/TestBox/TestAdditionalFiles/VBoxGuestAdditions_6.1.2.iso';
1237 oSet = vboxtestvms.TestVmSet(self.oTestVmManager, acCpus = [2], fIgnoreSkippedVm = True);
1238 # pylint: disable=line-too-long
1239 oSet.aoTestVms.extend([
1240 tdAutostartOsWin(oSet, self, self.ksOsWindows, 'Windows7_64', \
1241 '6.0/windows7piglit/windows7piglit.vdi', eNic0Type = None, cMbRam = 2048, \
1242 cCpus = 2, fPae = True, sGuestAdditionsIso = self.getGuestAdditionsIso()),
1243 tdAutostartOsLinux(oSet, self, self.ksOsLinux, 'Ubuntu_64', \
1244 '6.0/ub1804piglit/ub1804piglit.vdi', eNic0Type = None, \
1245 cMbRam = 2048, cCpus = 2, fPae = None, sGuestAdditionsIso = self.getGuestAdditionsIso())
1246 ]);
1247 # pylint: enable=line-too-long
1248 self.oTestVmSet = oSet;
1249 #
1250 # Overridden methods.
1251 #
1252 def showUsage(self):
1253 rc = vbox.TestDriver.showUsage(self);
1254 reporter.log('');
1255 reporter.log('tdAutostart Options:');
1256 reporter.log(' --test-build-dirs <path1[,path2[,...]]>');
1257 reporter.log(' The list of directories with VirtualBox distros. The option is mandatory');
1258 reporter.log(' without any default value. The test raises an exception if the');
1259 reporter.log(' option is not specified. At least, one directory should be pointed.');
1260 return rc;
1261 def parseOption(self, asArgs, iArg): # pylint: disable=too-many-branches,too-many-statements
1262 if asArgs[iArg] == '--test-build-dirs':
1263 iArg += 1;
1264 if iArg >= len(asArgs): raise base.InvalidOption('The "--test-build-dirs" takes a paths argument');
1265 self.asTestBuildDirs = asArgs[iArg].split(',');
1266 for oTestVm in self.oTestVmSet.aoTestVms:
1267 oTestVm.asTestBuildDirs = self.asTestBuildDirs;
1268 else:
1269 return vbox.TestDriver.parseOption(self, asArgs, iArg);
1270 return iArg + 1;
1271 def completeOptions(self):
1272 # Remove skipped VMs from the test list.
1273 if self.asTestBuildDirs is None:
1274 raise base.InvalidOption('--test-build-dirs is not specified')
1275 for sVM in self.asSkipVMs:
1276 try: self.asTestVMs.remove(sVM);
1277 except: pass;
1278 return vbox.TestDriver.completeOptions(self);
1279 def actionConfig(self):
1280 if not self.importVBoxApi(): # So we can use the constant below.
1281 return False;
1282 return self.oTestVmSet.actionConfig(self);
1283 def actionExecute(self):
1284 """
1285 Execute the testcase.
1286 """
1287 return self.oTestVmSet.actionExecute(self, self.testAutostartOneVfg)
1288 #
1289 # Test execution helpers.
1290 #
1291 def testAutostartOneVfg(self, oVM, oTestVm):
1292 # Reconfigure the VM
1293 fRc = True;
1294 self.logVmInfo(oVM);
1295 oSession = self.startVmByName(oTestVm.sVmName);
1296 if oSession is not None:
1297 sTestUserAllow = 'test1';
1298 sTestUserDeny = 'test2';
1299 sTestVmName = 'TestVM';
1300 #wait the VM is ready after starting
1301 (fRc, oGuestSession) = oTestVm.waitVmIsReady(oSession, True);
1302 #install fresh guest additions
1303 if fRc:
1304 (fRc, oGuestSession) = oTestVm.installAdditions(oSession, oGuestSession, oVM);
1305 # Create two new users
1306 fRc = fRc and oTestVm.createUser(oGuestSession, sTestUserAllow);
1307 fRc = fRc and oTestVm.createUser(oGuestSession, sTestUserDeny);
1308 if fRc is True:
1309 # Install VBox first
1310 fRc = oTestVm.installVirtualBox(oGuestSession);
1311 if fRc is True:
1312 fRc = oTestVm.configureAutostart(oGuestSession, 'allow', (sTestUserAllow,), (sTestUserDeny,));
1313 if fRc is True:
1314 # Create a VM with autostart enabled in the guest for both users
1315 fRc = oTestVm.createTestVM(oSession, oGuestSession, sTestUserAllow, sTestVmName);
1316 fRc = fRc and oTestVm.createTestVM(oSession, oGuestSession, sTestUserDeny, sTestVmName);
1317 if fRc is True:
1318 # Reboot the guest
1319 (fRc, oGuestSession) = oTestVm.rebootVMAndCheckReady(oSession, oGuestSession);
1320 if fRc is True:
1321 # Fudge factor - Allow the guest VMs to finish starting up.
1322 self.sleep(60);
1323 fRc = oTestVm.checkForRunningVM(oSession, oGuestSession, sTestUserAllow, sTestVmName);
1324 if fRc is True:
1325 fRc = oTestVm.checkForRunningVM(oSession, oGuestSession, sTestUserDeny, sTestVmName);
1326 if fRc is True:
1327 reporter.error('Test VM is running inside the guest for denied user');
1328 fRc = not fRc;
1329 else:
1330 reporter.error('Test VM is not running inside the guest for allowed user');
1331 else:
1332 reporter.error('Rebooting the guest failed');
1333 else:
1334 reporter.error('Creating test VM failed');
1335 else:
1336 reporter.error('Configuring autostart in the guest failed');
1337 else:
1338 reporter.error('Installing VirtualBox in the guest failed');
1339 else:
1340 reporter.error('Creating test users failed');
1341 if oGuestSession is not None:
1342 try: oTestVm.powerDownVM(oGuestSession);
1343 except: pass;
1344 try: self.terminateVmBySession(oSession);
1345 except: pass;
1346 fRc = oSession.close() and fRc and True; # pychecker hack.
1347 oSession = None;
1348 else:
1349 fRc = False;
1350 return fRc;
1351if __name__ == '__main__':
1352 sys.exit(tdAutostart().main(sys.argv));
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette