VirtualBox

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

Last change on this file since 95094 was 95094, checked in by vboxsync, 3 years ago

Validation Kit/tdAutostart1: Fixed function typo.

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