VirtualBox

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

Last change on this file since 97673 was 97673, checked in by vboxsync, 2 years ago

Validation Kit: Fixed lots of warnings, based on pylint 2.12.2.

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