VirtualBox

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

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

Main: bugref:9341: Testcase is restricted to test only the host-like OS by default.

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