VirtualBox

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

Last change on this file since 84559 was 84559, checked in by vboxsync, 5 years ago

Main: bugref:9341: Added the VM deletion after testing.

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