VirtualBox

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

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

Main: bugref:9341: Testcase: fixed invalid matching string in the script

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

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