VirtualBox

source: vbox/trunk/src/VBox/ValidationKit/testdriver/vbox.py@ 94596

最後變更 在這個檔案從94596是 94596,由 vboxsync 提交於 3 年 前

ValidationKit/testdriver/vbox.py: Split long commented out python command to make pylint happy.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 197.2 KB
 
1# -*- coding: utf-8 -*-
2# $Id: vbox.py 94596 2022-04-13 21:41:11Z vboxsync $
3# pylint: disable=too-many-lines
4
5"""
6VirtualBox Specific base testdriver.
7"""
8
9__copyright__ = \
10"""
11Copyright (C) 2010-2022 Oracle Corporation
12
13This file is part of VirtualBox Open Source Edition (OSE), as
14available from http://www.alldomusa.eu.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__ = "$Revision: 94596 $"
31
32# pylint: disable=unnecessary-semicolon
33
34# Standard Python imports.
35import datetime
36import os
37import platform
38import re;
39import sys
40import threading
41import time
42import traceback
43
44# Figure out where the validation kit lives and make sure it's in the path.
45try: __file__
46except: __file__ = sys.argv[0];
47g_ksValidationKitDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)));
48if g_ksValidationKitDir not in sys.path:
49 sys.path.append(g_ksValidationKitDir);
50
51# Validation Kit imports.
52from common import utils;
53from testdriver import base;
54from testdriver import btresolver;
55from testdriver import reporter;
56from testdriver import vboxcon;
57from testdriver import vboxtestvms;
58
59# Python 3 hacks:
60if sys.version_info[0] >= 3:
61 xrange = range; # pylint: disable=redefined-builtin,invalid-name
62 long = int; # pylint: disable=redefined-builtin,invalid-name
63
64#
65# Exception and Error Unification Hacks.
66# Note! This is pretty gross stuff. Be warned!
67# TODO: Find better ways of doing these things, preferrably in vboxapi.
68#
69
70ComException = None; # pylint: disable=invalid-name
71__fnComExceptionGetAttr__ = None; # pylint: disable=invalid-name
72
73def __MyDefaultGetAttr(oSelf, sName):
74 """ __getattribute__/__getattr__ default fake."""
75 try:
76 oAttr = oSelf.__dict__[sName];
77 except:
78 oAttr = dir(oSelf)[sName];
79 return oAttr;
80
81def __MyComExceptionGetAttr(oSelf, sName):
82 """ ComException.__getattr__ wrapper - both XPCOM and COM. """
83 try:
84 oAttr = __fnComExceptionGetAttr__(oSelf, sName);
85 except AttributeError:
86 if platform.system() == 'Windows':
87 if sName == 'errno':
88 oAttr = __fnComExceptionGetAttr__(oSelf, 'hresult');
89 elif sName == 'msg':
90 oAttr = __fnComExceptionGetAttr__(oSelf, 'strerror');
91 else:
92 raise;
93 else:
94 if sName == 'hresult':
95 oAttr = __fnComExceptionGetAttr__(oSelf, 'errno');
96 elif sName == 'strerror':
97 oAttr = __fnComExceptionGetAttr__(oSelf, 'msg');
98 elif sName == 'excepinfo':
99 oAttr = None;
100 elif sName == 'argerror':
101 oAttr = None;
102 else:
103 raise;
104 #print '__MyComExceptionGetAttr(,%s) -> "%s"' % (sName, oAttr);
105 return oAttr;
106
107def __deployExceptionHacks__(oNativeComExceptionClass):
108 """
109 Deploys the exception and error hacks that helps unifying COM and XPCOM
110 exceptions and errors.
111 """
112 global ComException # pylint: disable=invalid-name
113 global __fnComExceptionGetAttr__ # pylint: disable=invalid-name
114
115 # Hook up our attribute getter for the exception class (ASSUMES new-style).
116 if __fnComExceptionGetAttr__ is None:
117 try:
118 __fnComExceptionGetAttr__ = getattr(oNativeComExceptionClass, '__getattr__');
119 except:
120 try:
121 __fnComExceptionGetAttr__ = getattr(oNativeComExceptionClass, '__getattribute__');
122 except:
123 __fnComExceptionGetAttr__ = __MyDefaultGetAttr;
124 setattr(oNativeComExceptionClass, '__getattr__', __MyComExceptionGetAttr)
125
126 # Make the modified classes accessible (are there better ways to do this?)
127 ComException = oNativeComExceptionClass
128 return None;
129
130
131
132#
133# Utility functions.
134#
135
136def isIpAddrValid(sIpAddr):
137 """
138 Checks if a IPv4 address looks valid. This will return false for
139 localhost and similar.
140 Returns True / False.
141 """
142 if sIpAddr is None: return False;
143 if len(sIpAddr.split('.')) != 4: return False;
144 if sIpAddr.endswith('.0'): return False;
145 if sIpAddr.endswith('.255'): return False;
146 if sIpAddr.startswith('127.'): return False;
147 if sIpAddr.startswith('169.254.'): return False;
148 if sIpAddr.startswith('192.0.2.'): return False;
149 if sIpAddr.startswith('224.0.0.'): return False;
150 return True;
151
152def stringifyErrorInfo(oErrInfo):
153 """
154 Stringifies the error information in a IVirtualBoxErrorInfo object.
155
156 Returns string with error info.
157 """
158 try:
159 rc = oErrInfo.resultCode;
160 sText = oErrInfo.text;
161 sIid = oErrInfo.interfaceID;
162 sComponent = oErrInfo.component;
163 except:
164 sRet = 'bad error object (%s)?' % (oErrInfo,);
165 traceback.print_exc();
166 else:
167 sRet = 'rc=%s text="%s" IID=%s component=%s' % (ComError.toString(rc), sText, sIid, sComponent);
168 return sRet;
169
170def reportError(oErr, sText):
171 """
172 Report a VirtualBox error on oErr. oErr can be IVirtualBoxErrorInfo
173 or IProgress. Anything else is ignored.
174
175 Returns the same a reporter.error().
176 """
177 try:
178 oErrObj = oErr.errorInfo; # IProgress.
179 except:
180 oErrObj = oErr;
181 reporter.error(sText);
182 return reporter.error(stringifyErrorInfo(oErrObj));
183
184def formatComOrXpComException(oType, oXcpt):
185 """
186 Callback installed with the reporter to better format COM exceptions.
187 Similar to format_exception_only, only it returns None if not interested.
188 """
189 _ = oType;
190 oVBoxMgr = vboxcon.goHackModuleClass.oVBoxMgr;
191 if oVBoxMgr is None:
192 return None;
193 if not oVBoxMgr.xcptIsOurXcptKind(oXcpt): # pylint: disable=not-callable
194 return None;
195
196 if platform.system() == 'Windows':
197 hrc = oXcpt.hresult;
198 if hrc == ComError.DISP_E_EXCEPTION and oXcpt.excepinfo is not None and len(oXcpt.excepinfo) > 5:
199 hrc = oXcpt.excepinfo[5];
200 sWhere = oXcpt.excepinfo[1];
201 sMsg = oXcpt.excepinfo[2];
202 else:
203 sWhere = None;
204 sMsg = oXcpt.strerror;
205 else:
206 hrc = oXcpt.errno;
207 sWhere = None;
208 sMsg = oXcpt.msg;
209
210 sHrc = oVBoxMgr.xcptToString(hrc); # pylint: disable=not-callable
211 if sHrc.find('(') < 0:
212 sHrc = '%s (%#x)' % (sHrc, hrc & 0xffffffff,);
213
214 asRet = ['COM-Xcpt: %s' % (sHrc,)];
215 if sMsg and sWhere:
216 asRet.append('--------- %s: %s' % (sWhere, sMsg,));
217 elif sMsg:
218 asRet.append('--------- %s' % (sMsg,));
219 return asRet;
220 #if sMsg and sWhere:
221 # return ['COM-Xcpt: %s - %s: %s' % (sHrc, sWhere, sMsg,)];
222 #if sMsg:
223 # return ['COM-Xcpt: %s - %s' % (sHrc, sMsg,)];
224 #return ['COM-Xcpt: %s' % (sHrc,)];
225
226#
227# Classes
228#
229
230class ComError(object):
231 """
232 Unified COM and XPCOM status code repository.
233 This works more like a module than a class since it's replacing a module.
234 """
235
236 # The VBOX_E_XXX bits:
237 __VBOX_E_BASE = -2135228416;
238 VBOX_E_OBJECT_NOT_FOUND = __VBOX_E_BASE + 1;
239 VBOX_E_INVALID_VM_STATE = __VBOX_E_BASE + 2;
240 VBOX_E_VM_ERROR = __VBOX_E_BASE + 3;
241 VBOX_E_FILE_ERROR = __VBOX_E_BASE + 4;
242 VBOX_E_IPRT_ERROR = __VBOX_E_BASE + 5;
243 VBOX_E_PDM_ERROR = __VBOX_E_BASE + 6;
244 VBOX_E_INVALID_OBJECT_STATE = __VBOX_E_BASE + 7;
245 VBOX_E_HOST_ERROR = __VBOX_E_BASE + 8;
246 VBOX_E_NOT_SUPPORTED = __VBOX_E_BASE + 9;
247 VBOX_E_XML_ERROR = __VBOX_E_BASE + 10;
248 VBOX_E_INVALID_SESSION_STATE = __VBOX_E_BASE + 11;
249 VBOX_E_OBJECT_IN_USE = __VBOX_E_BASE + 12;
250 VBOX_E_DONT_CALL_AGAIN = __VBOX_E_BASE + 13;
251
252 # Reverse lookup table.
253 dDecimalToConst = {}; # pylint: disable=invalid-name
254
255 def __init__(self):
256 raise base.GenError('No instances, please');
257
258 @staticmethod
259 def copyErrors(oNativeComErrorClass):
260 """
261 Copy all error codes from oNativeComErrorClass to this class and
262 install compatability mappings.
263 """
264
265 # First, add the VBOX_E_XXX constants to dDecimalToConst.
266 for sAttr in dir(ComError):
267 if sAttr.startswith('VBOX_E'):
268 oAttr = getattr(ComError, sAttr);
269 ComError.dDecimalToConst[oAttr] = sAttr;
270
271 # Copy all error codes from oNativeComErrorClass to this class.
272 for sAttr in dir(oNativeComErrorClass):
273 if sAttr[0].isupper():
274 oAttr = getattr(oNativeComErrorClass, sAttr);
275 setattr(ComError, sAttr, oAttr);
276 if isinstance(oAttr, int):
277 ComError.dDecimalToConst[oAttr] = sAttr;
278
279 # Install mappings to the other platform.
280 if platform.system() == 'Windows':
281 ComError.NS_OK = ComError.S_OK;
282 ComError.NS_ERROR_FAILURE = ComError.E_FAIL;
283 ComError.NS_ERROR_ABORT = ComError.E_ABORT;
284 ComError.NS_ERROR_NULL_POINTER = ComError.E_POINTER;
285 ComError.NS_ERROR_NO_INTERFACE = ComError.E_NOINTERFACE;
286 ComError.NS_ERROR_INVALID_ARG = ComError.E_INVALIDARG;
287 ComError.NS_ERROR_OUT_OF_MEMORY = ComError.E_OUTOFMEMORY;
288 ComError.NS_ERROR_NOT_IMPLEMENTED = ComError.E_NOTIMPL;
289 ComError.NS_ERROR_UNEXPECTED = ComError.E_UNEXPECTED;
290 else:
291 ComError.E_ACCESSDENIED = -2147024891; # see VBox/com/defs.h
292 ComError.S_OK = ComError.NS_OK;
293 ComError.E_FAIL = ComError.NS_ERROR_FAILURE;
294 ComError.E_ABORT = ComError.NS_ERROR_ABORT;
295 ComError.E_POINTER = ComError.NS_ERROR_NULL_POINTER;
296 ComError.E_NOINTERFACE = ComError.NS_ERROR_NO_INTERFACE;
297 ComError.E_INVALIDARG = ComError.NS_ERROR_INVALID_ARG;
298 ComError.E_OUTOFMEMORY = ComError.NS_ERROR_OUT_OF_MEMORY;
299 ComError.E_NOTIMPL = ComError.NS_ERROR_NOT_IMPLEMENTED;
300 ComError.E_UNEXPECTED = ComError.NS_ERROR_UNEXPECTED;
301 ComError.DISP_E_EXCEPTION = -2147352567; # For COM compatability only.
302 return True;
303
304 @staticmethod
305 def getXcptResult(oXcpt):
306 """
307 Gets the result code for an exception.
308 Returns COM status code (or E_UNEXPECTED).
309 """
310 if platform.system() == 'Windows':
311 # The DISP_E_EXCEPTION + excptinfo fun needs checking up, only
312 # empirical info on it so far.
313 try:
314 hrXcpt = oXcpt.hresult;
315 except AttributeError:
316 hrXcpt = ComError.E_UNEXPECTED;
317 if hrXcpt == ComError.DISP_E_EXCEPTION and oXcpt.excepinfo is not None:
318 hrXcpt = oXcpt.excepinfo[5];
319 else:
320 try:
321 hrXcpt = oXcpt.errno;
322 except AttributeError:
323 hrXcpt = ComError.E_UNEXPECTED;
324 return hrXcpt;
325
326 @staticmethod
327 def equal(oXcpt, hr):
328 """
329 Checks if the ComException e is not equal to the COM status code hr.
330 This takes DISP_E_EXCEPTION & excepinfo into account.
331
332 This method can be used with any Exception derivate, however it will
333 only return True for classes similar to the two ComException variants.
334 """
335 if platform.system() == 'Windows':
336 # The DISP_E_EXCEPTION + excptinfo fun needs checking up, only
337 # empirical info on it so far.
338 try:
339 hrXcpt = oXcpt.hresult;
340 except AttributeError:
341 return False;
342 if hrXcpt == ComError.DISP_E_EXCEPTION and oXcpt.excepinfo is not None:
343 hrXcpt = oXcpt.excepinfo[5];
344 else:
345 try:
346 hrXcpt = oXcpt.errno;
347 except AttributeError:
348 return False;
349 return hrXcpt == hr;
350
351 @staticmethod
352 def notEqual(oXcpt, hr):
353 """
354 Checks if the ComException e is not equal to the COM status code hr.
355 See equal() for more details.
356 """
357 return not ComError.equal(oXcpt, hr)
358
359 @staticmethod
360 def toString(hr):
361 """
362 Converts the specified COM status code to a string.
363 """
364 try:
365 sStr = ComError.dDecimalToConst[int(hr)];
366 except KeyError:
367 hrLong = long(hr);
368 sStr = '%#x (%d)' % (hrLong, hrLong);
369 return sStr;
370
371
372class Build(object): # pylint: disable=too-few-public-methods
373 """
374 A VirtualBox build.
375
376 Note! After dropping the installation of VBox from this code and instead
377 realizing that with the vboxinstall.py wrapper driver, this class is
378 of much less importance and contains unnecessary bits and pieces.
379 """
380
381 def __init__(self, oDriver, strInstallPath):
382 """
383 Construct a build object from a build file name and/or install path.
384 """
385 # Initialize all members first.
386 self.oDriver = oDriver;
387 self.sInstallPath = strInstallPath;
388 self.sSdkPath = None;
389 self.sSrcRoot = None;
390 self.sKind = None;
391 self.sDesignation = None;
392 self.sType = None;
393 self.sOs = None;
394 self.sArch = None;
395 self.sGuestAdditionsIso = None;
396
397 # Figure out the values as best we can.
398 if strInstallPath is None:
399 #
400 # Both parameters are None, which means we're falling back on a
401 # build in the development tree.
402 #
403 self.sKind = "development";
404
405 if self.sType is None:
406 self.sType = os.environ.get("KBUILD_TYPE", "release");
407 if self.sOs is None:
408 self.sOs = os.environ.get("KBUILD_TARGET", oDriver.sHost);
409 if self.sArch is None:
410 self.sArch = os.environ.get("KBUILD_TARGET_ARCH", oDriver.sHostArch);
411
412 sOut = os.path.join('out', self.sOs + '.' + self.sArch, self.sType);
413 sSearch = os.environ.get('VBOX_TD_DEV_TREE', os.path.dirname(__file__)); # Env.var. for older trees or testboxscript.
414 sCandidat = None;
415 for i in range(0, 10): # pylint: disable=unused-variable
416 sBldDir = os.path.join(sSearch, sOut);
417 if os.path.isdir(sBldDir):
418 sCandidat = os.path.join(sBldDir, 'bin', 'VBoxSVC' + base.exeSuff());
419 if os.path.isfile(sCandidat):
420 self.sSdkPath = os.path.join(sBldDir, 'bin/sdk');
421 break;
422 sCandidat = os.path.join(sBldDir, 'dist/VirtualBox.app/Contents/MacOS/VBoxSVC');
423 if os.path.isfile(sCandidat):
424 self.sSdkPath = os.path.join(sBldDir, 'dist/sdk');
425 break;
426 sSearch = os.path.abspath(os.path.join(sSearch, '..'));
427 if sCandidat is None or not os.path.isfile(sCandidat):
428 raise base.GenError();
429 self.sInstallPath = os.path.abspath(os.path.dirname(sCandidat));
430 self.sSrcRoot = os.path.abspath(sSearch);
431
432 self.sDesignation = os.environ.get('TEST_BUILD_DESIGNATION', None);
433 if self.sDesignation is None:
434 try:
435 oFile = utils.openNoInherit(os.path.join(self.sSrcRoot, sOut, 'revision.kmk'), 'r');
436 except:
437 pass;
438 else:
439 s = oFile.readline();
440 oFile.close();
441 oMatch = re.search("VBOX_SVN_REV=(\\d+)", s);
442 if oMatch is not None:
443 self.sDesignation = oMatch.group(1);
444
445 if self.sDesignation is None:
446 self.sDesignation = 'XXXXX'
447 else:
448 #
449 # We've been pointed to an existing installation, this could be
450 # in the out dir of a svn checkout, untarred VBoxAll or a real
451 # installation directory.
452 #
453 self.sKind = "preinstalled";
454 self.sType = "release";
455 self.sOs = oDriver.sHost;
456 self.sArch = oDriver.sHostArch;
457 self.sInstallPath = os.path.abspath(strInstallPath);
458 self.sSdkPath = os.path.join(self.sInstallPath, 'sdk');
459 self.sSrcRoot = None;
460 self.sDesignation = os.environ.get('TEST_BUILD_DESIGNATION', 'XXXXX');
461 ## @todo Much more work is required here.
462
463 # Try Determine the build type.
464 sVBoxManage = os.path.join(self.sInstallPath, 'VBoxManage' + base.exeSuff());
465 if os.path.isfile(sVBoxManage):
466 try:
467 (iExit, sStdOut, _) = utils.processOutputUnchecked([sVBoxManage, '--dump-build-type']);
468 sStdOut = sStdOut.strip();
469 if iExit == 0 and sStdOut in ('release', 'debug', 'strict', 'dbgopt', 'asan'):
470 self.sType = sStdOut;
471 reporter.log('Build: Detected build type: %s' % (self.sType));
472 else:
473 reporter.log('Build: --dump-build-type -> iExit=%u sStdOut=%s' % (iExit, sStdOut,));
474 except:
475 reporter.logXcpt('Build: Running "%s --dump-build-type" failed!' % (sVBoxManage,));
476 else:
477 reporter.log3('Build: sVBoxManage=%s not found' % (sVBoxManage,));
478
479 # Do some checks.
480 sVMMR0 = os.path.join(self.sInstallPath, 'VMMR0.r0');
481 if not os.path.isfile(sVMMR0) and utils.getHostOs() == 'solaris': # solaris is special.
482 sVMMR0 = os.path.join(self.sInstallPath, 'amd64' if utils.getHostArch() == 'amd64' else 'i386', 'VMMR0.r0');
483 if not os.path.isfile(sVMMR0):
484 raise base.GenError('%s is missing' % (sVMMR0,));
485
486 # Guest additions location is different on windows for some _stupid_ reason.
487 if self.sOs == 'win' and self.sKind != 'development':
488 self.sGuestAdditionsIso = '%s/VBoxGuestAdditions.iso' % (self.sInstallPath,);
489 elif self.sOs == 'darwin':
490 self.sGuestAdditionsIso = '%s/VBoxGuestAdditions.iso' % (self.sInstallPath,);
491 elif self.sOs == 'solaris':
492 self.sGuestAdditionsIso = '%s/VBoxGuestAdditions.iso' % (self.sInstallPath,);
493 else:
494 self.sGuestAdditionsIso = '%s/additions/VBoxGuestAdditions.iso' % (self.sInstallPath,);
495
496 # __init__ end;
497
498 def isDevBuild(self):
499 """ Returns True if it's development build (kind), otherwise False. """
500 return self.sKind == 'development';
501
502
503class EventHandlerBase(object):
504 """
505 Base class for both Console and VirtualBox event handlers.
506 """
507
508 def __init__(self, dArgs, fpApiVer, sName = None):
509 self.oVBoxMgr = dArgs['oVBoxMgr'];
510 self.oEventSrc = dArgs['oEventSrc']; # Console/VirtualBox for < 3.3
511 self.oListener = dArgs['oListener'];
512 self.fPassive = self.oListener is not None;
513 self.sName = sName
514 self.fShutdown = False;
515 self.oThread = None;
516 self.fpApiVer = fpApiVer;
517 self.dEventNo2Name = {};
518 for sKey, iValue in self.oVBoxMgr.constants.all_values('VBoxEventType').items():
519 self.dEventNo2Name[iValue] = sKey;
520
521 def threadForPassiveMode(self):
522 """
523 The thread procedure for the event processing thread.
524 """
525 assert self.fPassive is not None;
526 while not self.fShutdown:
527 try:
528 oEvt = self.oEventSrc.getEvent(self.oListener, 500);
529 except:
530 if not self.oVBoxMgr.xcptIsDeadInterface(): reporter.logXcpt();
531 else: reporter.log('threadForPassiveMode/%s: interface croaked (ignored)' % (self.sName,));
532 break;
533 if oEvt:
534 self.handleEvent(oEvt);
535 if not self.fShutdown:
536 try:
537 self.oEventSrc.eventProcessed(self.oListener, oEvt);
538 except:
539 reporter.logXcpt();
540 break;
541 self.unregister(fWaitForThread = False);
542 return None;
543
544 def startThreadForPassiveMode(self):
545 """
546 Called when working in passive mode.
547 """
548 self.oThread = threading.Thread(target = self.threadForPassiveMode, \
549 args=(), name=('PAS-%s' % (self.sName,)));
550 self.oThread.setDaemon(True)
551 self.oThread.start();
552 return None;
553
554 def unregister(self, fWaitForThread = True):
555 """
556 Unregister the event handler.
557 """
558 fRc = False;
559 if not self.fShutdown:
560 self.fShutdown = True;
561
562 if self.oEventSrc is not None:
563 if self.fpApiVer < 3.3:
564 try:
565 self.oEventSrc.unregisterCallback(self.oListener);
566 fRc = True;
567 except:
568 reporter.errorXcpt('unregisterCallback failed on %s' % (self.oListener,));
569 else:
570 try:
571 self.oEventSrc.unregisterListener(self.oListener);
572 fRc = True;
573 except:
574 if self.oVBoxMgr.xcptIsDeadInterface():
575 reporter.log('unregisterListener failed on %s because of dead interface (%s)'
576 % (self.oListener, self.oVBoxMgr.xcptToString(),));
577 else:
578 reporter.errorXcpt('unregisterListener failed on %s' % (self.oListener,));
579
580 if self.oThread is not None \
581 and self.oThread != threading.current_thread():
582 self.oThread.join();
583 self.oThread = None;
584
585 _ = fWaitForThread;
586 return fRc;
587
588 def handleEvent(self, oEvt):
589 """
590 Compatibility wrapper that child classes implement.
591 """
592 _ = oEvt;
593 return None;
594
595 @staticmethod
596 def registerDerivedEventHandler(oVBoxMgr, fpApiVer, oSubClass, dArgsCopy, # pylint: disable=too-many-arguments
597 oSrcParent, sSrcParentNm, sICallbackNm,
598 fMustSucceed = True, sLogSuffix = '', aenmEvents = None):
599 """
600 Registers the callback / event listener.
601 """
602 dArgsCopy['oVBoxMgr'] = oVBoxMgr;
603 dArgsCopy['oListener'] = None;
604 if fpApiVer < 3.3:
605 dArgsCopy['oEventSrc'] = oSrcParent;
606 try:
607 oRet = oVBoxMgr.createCallback(sICallbackNm, oSubClass, dArgsCopy);
608 except:
609 reporter.errorXcpt('%s::registerCallback(%s) failed%s' % (sSrcParentNm, oRet, sLogSuffix));
610 else:
611 try:
612 oSrcParent.registerCallback(oRet);
613 return oRet;
614 except Exception as oXcpt:
615 if fMustSucceed or ComError.notEqual(oXcpt, ComError.E_UNEXPECTED):
616 reporter.errorXcpt('%s::registerCallback(%s)%s' % (sSrcParentNm, oRet, sLogSuffix));
617 else:
618 #
619 # Scalable event handling introduced in VBox 4.0.
620 #
621 fPassive = sys.platform == 'win32'; # or webservices.
622
623 if not aenmEvents:
624 aenmEvents = (vboxcon.VBoxEventType_Any,);
625
626 try:
627 oEventSrc = oSrcParent.eventSource;
628 dArgsCopy['oEventSrc'] = oEventSrc;
629 if not fPassive:
630 oListener = oRet = oVBoxMgr.createListener(oSubClass, dArgsCopy);
631 else:
632 oListener = oEventSrc.createListener();
633 dArgsCopy['oListener'] = oListener;
634 oRet = oSubClass(dArgsCopy);
635 except:
636 reporter.errorXcpt('%s::eventSource.createListener(%s) failed%s' % (sSrcParentNm, oListener, sLogSuffix));
637 else:
638 try:
639 oEventSrc.registerListener(oListener, aenmEvents, not fPassive);
640 except Exception as oXcpt:
641 if fMustSucceed or ComError.notEqual(oXcpt, ComError.E_UNEXPECTED):
642 reporter.errorXcpt('%s::eventSource.registerListener(%s) failed%s'
643 % (sSrcParentNm, oListener, sLogSuffix));
644 else:
645 if not fPassive:
646 if sys.platform == 'win32':
647 from win32com.server.util import unwrap # pylint: disable=import-error
648 oRet = unwrap(oRet);
649 oRet.oListener = oListener;
650 else:
651 oRet.startThreadForPassiveMode();
652 return oRet;
653 return None;
654
655
656
657
658class ConsoleEventHandlerBase(EventHandlerBase):
659 """
660 Base class for handling IConsole events.
661
662 The class has IConsoleCallback (<=3.2) compatible callback methods which
663 the user can override as needed.
664
665 Note! This class must not inherit from object or we'll get type errors in VBoxPython.
666 """
667 def __init__(self, dArgs, sName = None):
668 self.oSession = dArgs['oSession'];
669 self.oConsole = dArgs['oConsole'];
670 if sName is None:
671 sName = self.oSession.sName;
672 EventHandlerBase.__init__(self, dArgs, self.oSession.fpApiVer, sName);
673
674
675 # pylint: disable=missing-docstring,too-many-arguments,unused-argument
676 def onMousePointerShapeChange(self, fVisible, fAlpha, xHot, yHot, cx, cy, abShape):
677 reporter.log2('onMousePointerShapeChange/%s' % (self.sName));
678 def onMouseCapabilityChange(self, fSupportsAbsolute, *aArgs): # Extra argument was added in 3.2.
679 reporter.log2('onMouseCapabilityChange/%s' % (self.sName));
680 def onKeyboardLedsChange(self, fNumLock, fCapsLock, fScrollLock):
681 reporter.log2('onKeyboardLedsChange/%s' % (self.sName));
682 def onStateChange(self, eState):
683 reporter.log2('onStateChange/%s' % (self.sName));
684 def onAdditionsStateChange(self):
685 reporter.log2('onAdditionsStateChange/%s' % (self.sName));
686 def onNetworkAdapterChange(self, oNic):
687 reporter.log2('onNetworkAdapterChange/%s' % (self.sName));
688 def onSerialPortChange(self, oPort):
689 reporter.log2('onSerialPortChange/%s' % (self.sName));
690 def onParallelPortChange(self, oPort):
691 reporter.log2('onParallelPortChange/%s' % (self.sName));
692 def onStorageControllerChange(self):
693 reporter.log2('onStorageControllerChange/%s' % (self.sName));
694 def onMediumChange(self, attachment):
695 reporter.log2('onMediumChange/%s' % (self.sName));
696 def onCPUChange(self, iCpu, fAdd):
697 reporter.log2('onCPUChange/%s' % (self.sName));
698 def onVRDPServerChange(self):
699 reporter.log2('onVRDPServerChange/%s' % (self.sName));
700 def onRemoteDisplayInfoChange(self):
701 reporter.log2('onRemoteDisplayInfoChange/%s' % (self.sName));
702 def onUSBControllerChange(self):
703 reporter.log2('onUSBControllerChange/%s' % (self.sName));
704 def onUSBDeviceStateChange(self, oDevice, fAttached, oError):
705 reporter.log2('onUSBDeviceStateChange/%s' % (self.sName));
706 def onSharedFolderChange(self, fGlobal):
707 reporter.log2('onSharedFolderChange/%s' % (self.sName));
708 def onRuntimeError(self, fFatal, sErrId, sMessage):
709 reporter.log2('onRuntimeError/%s' % (self.sName));
710 def onCanShowWindow(self):
711 reporter.log2('onCanShowWindow/%s' % (self.sName));
712 return True
713 def onShowWindow(self):
714 reporter.log2('onShowWindow/%s' % (self.sName));
715 return None;
716 # pylint: enable=missing-docstring,too-many-arguments,unused-argument
717
718 def handleEvent(self, oEvt):
719 """
720 Compatibility wrapper.
721 """
722 try:
723 oEvtBase = self.oVBoxMgr.queryInterface(oEvt, 'IEvent');
724 eType = oEvtBase.type;
725 except:
726 reporter.logXcpt();
727 return None;
728 if eType == vboxcon.VBoxEventType_OnRuntimeError:
729 try:
730 oEvtIt = self.oVBoxMgr.queryInterface(oEvtBase, 'IRuntimeErrorEvent');
731 return self.onRuntimeError(oEvtIt.fatal, oEvtIt.id, oEvtIt.message)
732 except:
733 reporter.logXcpt();
734 ## @todo implement the other events.
735 try:
736 if eType not in (vboxcon.VBoxEventType_OnMousePointerShapeChanged,
737 vboxcon.VBoxEventType_OnCursorPositionChanged):
738 if eType in self.dEventNo2Name:
739 reporter.log2('%s(%s)/%s' % (self.dEventNo2Name[eType], str(eType), self.sName));
740 else:
741 reporter.log2('%s/%s' % (str(eType), self.sName));
742 except AttributeError: # Handle older VBox versions which don't have a specific event.
743 pass;
744 return None;
745
746
747class VirtualBoxEventHandlerBase(EventHandlerBase):
748 """
749 Base class for handling IVirtualBox events.
750
751 The class has IConsoleCallback (<=3.2) compatible callback methods which
752 the user can override as needed.
753
754 Note! This class must not inherit from object or we'll get type errors in VBoxPython.
755 """
756 def __init__(self, dArgs, sName = "emanon"):
757 self.oVBoxMgr = dArgs['oVBoxMgr'];
758 self.oVBox = dArgs['oVBox'];
759 EventHandlerBase.__init__(self, dArgs, self.oVBox.fpApiVer, sName);
760
761 # pylint: disable=missing-docstring,unused-argument
762 def onMachineStateChange(self, sMachineId, eState):
763 pass;
764 def onMachineDataChange(self, sMachineId):
765 pass;
766 def onExtraDataCanChange(self, sMachineId, sKey, sValue):
767 # The COM bridge does tuples differently. Not very funny if you ask me... ;-)
768 if self.oVBoxMgr.type == 'MSCOM':
769 return '', 0, True;
770 return True, ''
771 def onExtraDataChange(self, sMachineId, sKey, sValue):
772 pass;
773 def onMediumRegistered(self, sMediumId, eMediumType, fRegistered):
774 pass;
775 def onMachineRegistered(self, sMachineId, fRegistered):
776 pass;
777 def onSessionStateChange(self, sMachineId, eState):
778 pass;
779 def onSnapshotTaken(self, sMachineId, sSnapshotId):
780 pass;
781 def onSnapshotDiscarded(self, sMachineId, sSnapshotId):
782 pass;
783 def onSnapshotChange(self, sMachineId, sSnapshotId):
784 pass;
785 def onGuestPropertyChange(self, sMachineId, sName, sValue, sFlags, fWasDeleted):
786 pass;
787 # pylint: enable=missing-docstring,unused-argument
788
789 def handleEvent(self, oEvt):
790 """
791 Compatibility wrapper.
792 """
793 try:
794 oEvtBase = self.oVBoxMgr.queryInterface(oEvt, 'IEvent');
795 eType = oEvtBase.type;
796 except:
797 reporter.logXcpt();
798 return None;
799 if eType == vboxcon.VBoxEventType_OnMachineStateChanged:
800 try:
801 oEvtIt = self.oVBoxMgr.queryInterface(oEvtBase, 'IMachineStateChangedEvent');
802 return self.onMachineStateChange(oEvtIt.machineId, oEvtIt.state)
803 except:
804 reporter.logXcpt();
805 elif eType == vboxcon.VBoxEventType_OnGuestPropertyChanged:
806 try:
807 oEvtIt = self.oVBoxMgr.queryInterface(oEvtBase, 'IGuestPropertyChangedEvent');
808 return self.onGuestPropertyChange(oEvtIt.machineId, oEvtIt.name, oEvtIt.value, oEvtIt.flags, oEvtIt.fWasDeleted);
809 except:
810 reporter.logXcpt();
811 ## @todo implement the other events.
812 if eType in self.dEventNo2Name:
813 reporter.log2('%s(%s)/%s' % (self.dEventNo2Name[eType], str(eType), self.sName));
814 else:
815 reporter.log2('%s/%s' % (str(eType), self.sName));
816 return None;
817
818
819class SessionConsoleEventHandler(ConsoleEventHandlerBase):
820 """
821 For catching machine state changes and waking up the task machinery at that point.
822 """
823 def __init__(self, dArgs):
824 ConsoleEventHandlerBase.__init__(self, dArgs);
825
826 def onMachineStateChange(self, sMachineId, eState): # pylint: disable=unused-argument
827 """ Just interrupt the wait loop here so it can check again. """
828 _ = sMachineId; _ = eState;
829 self.oVBoxMgr.interruptWaitEvents();
830
831 def onRuntimeError(self, fFatal, sErrId, sMessage):
832 reporter.log('onRuntimeError/%s: fFatal=%d sErrId=%s sMessage=%s' % (self.sName, fFatal, sErrId, sMessage));
833 oSession = self.oSession;
834 if oSession is not None: # paranoia
835 if sErrId == 'HostMemoryLow':
836 oSession.signalHostMemoryLow();
837 if sys.platform == 'win32':
838 from testdriver import winbase;
839 winbase.logMemoryStats();
840 oSession.signalTask();
841 self.oVBoxMgr.interruptWaitEvents();
842
843
844
845class TestDriver(base.TestDriver): # pylint: disable=too-many-instance-attributes
846 """
847 This is the VirtualBox test driver.
848 """
849
850 def __init__(self):
851 base.TestDriver.__init__(self);
852 self.fImportedVBoxApi = False;
853 self.fpApiVer = 3.2;
854 self.uRevision = 0;
855 self.uApiRevision = 0;
856 self.oBuild = None;
857 self.oVBoxMgr = None;
858 self.oVBox = None;
859 self.aoRemoteSessions = [];
860 self.aoVMs = []; ## @todo not sure if this list will be of any use.
861 self.oTestVmManager = vboxtestvms.TestVmManager(self.sResourcePath);
862 self.oTestVmSet = vboxtestvms.TestVmSet();
863 self.sSessionTypeDef = 'headless';
864 self.sSessionType = self.sSessionTypeDef;
865 self.fEnableVrdp = True;
866 self.uVrdpBasePortDef = 6000;
867 self.uVrdpBasePort = self.uVrdpBasePortDef;
868 self.sDefBridgedNic = None;
869 self.fUseDefaultSvc = False;
870 self.sLogSelfGroups = '';
871 self.sLogSelfFlags = 'time';
872 self.sLogSelfDest = '';
873 self.sLogSessionGroups = '';
874 self.sLogSessionFlags = 'time';
875 self.sLogSessionDest = '';
876 self.sLogSvcGroups = '';
877 self.sLogSvcFlags = 'time';
878 self.sLogSvcDest = '';
879 self.sSelfLogFile = None;
880 self.sVBoxSvcLogFile = None;
881 self.oVBoxSvcProcess = None;
882 self.sVBoxSvcPidFile = None;
883 self.fVBoxSvcInDebugger = False;
884 self.fVBoxSvcWaitForDebugger = False;
885 self.sVBoxValidationKit = None;
886 self.sVBoxValidationKitIso = None;
887 self.sVBoxBootSectors = None;
888 self.fAlwaysUploadLogs = False;
889 self.fAlwaysUploadScreenshots = False;
890 self.fEnableDebugger = True;
891
892 # Drop LD_PRELOAD and enable memory leak detection in LSAN_OPTIONS from vboxinstall.py
893 # before doing build detection. This is a little crude and inflexible...
894 if 'LD_PRELOAD' in os.environ:
895 del os.environ['LD_PRELOAD'];
896 if 'LSAN_OPTIONS' in os.environ:
897 asLSanOptions = os.environ['LSAN_OPTIONS'].split(':');
898 try: asLSanOptions.remove('detect_leaks=0');
899 except: pass;
900 if asLSanOptions: os.environ['LSAN_OPTIONS'] = ':'.join(asLSanOptions);
901 else: del os.environ['LSAN_OPTIONS'];
902
903 # Quietly detect build and validation kit.
904 self._detectBuild(False);
905 self._detectValidationKit(False);
906
907 # Make sure all debug logs goes to the scratch area unless
908 # specified otherwise (more of this later on).
909 if 'VBOX_LOG_DEST' not in os.environ:
910 os.environ['VBOX_LOG_DEST'] = 'nodeny dir=%s' % (self.sScratchPath);
911
912
913 def _detectBuild(self, fQuiet = False):
914 """
915 This is used internally to try figure a locally installed build when
916 running tests manually.
917 """
918 if self.oBuild is not None:
919 return True;
920
921 # Try dev build first since that's where I'll be using it first...
922 if True is True: # pylint: disable=comparison-with-itself
923 try:
924 self.oBuild = Build(self, None);
925 reporter.log('VBox %s build at %s (%s).'
926 % (self.oBuild.sType, self.oBuild.sInstallPath, self.oBuild.sDesignation,));
927 return True;
928 except base.GenError:
929 pass;
930
931 # Try default installation locations.
932 if self.sHost == 'win':
933 sProgFiles = os.environ.get('ProgramFiles', 'C:\\Program Files');
934 asLocs = [
935 os.path.join(sProgFiles, 'Oracle', 'VirtualBox'),
936 os.path.join(sProgFiles, 'OracleVM', 'VirtualBox'),
937 os.path.join(sProgFiles, 'Sun', 'VirtualBox'),
938 ];
939 elif self.sHost == 'solaris':
940 asLocs = [ '/opt/VirtualBox-3.2', '/opt/VirtualBox-3.1', '/opt/VirtualBox-3.0', '/opt/VirtualBox' ];
941 elif self.sHost == 'darwin':
942 asLocs = [ '/Applications/VirtualBox.app/Contents/MacOS' ];
943 elif self.sHost == 'linux':
944 asLocs = [ '/opt/VirtualBox-3.2', '/opt/VirtualBox-3.1', '/opt/VirtualBox-3.0', '/opt/VirtualBox' ];
945 else:
946 asLocs = [ '/opt/VirtualBox' ];
947 if 'VBOX_INSTALL_PATH' in os.environ:
948 asLocs.insert(0, os.environ['VBOX_INSTALL_PATH']);
949
950 for sLoc in asLocs:
951 try:
952 self.oBuild = Build(self, sLoc);
953 reporter.log('VBox %s build at %s (%s).'
954 % (self.oBuild.sType, self.oBuild.sInstallPath, self.oBuild.sDesignation,));
955 return True;
956 except base.GenError:
957 pass;
958
959 if not fQuiet:
960 reporter.error('failed to find VirtualBox installation');
961 return False;
962
963 def _detectValidationKit(self, fQuiet = False):
964 """
965 This is used internally by the constructor to try locate an unzipped
966 VBox Validation Kit somewhere in the immediate proximity.
967 """
968 if self.sVBoxValidationKit is not None:
969 return True;
970
971 #
972 # Normally it's found where we're running from, which is the same as
973 # the script directly on the testboxes.
974 #
975 asCandidates = [self.sScriptPath, ];
976 if g_ksValidationKitDir not in asCandidates:
977 asCandidates.append(g_ksValidationKitDir);
978 if os.getcwd() not in asCandidates:
979 asCandidates.append(os.getcwd());
980 if self.oBuild is not None and self.oBuild.sInstallPath not in asCandidates:
981 asCandidates.append(self.oBuild.sInstallPath);
982
983 #
984 # When working out of the tree, we'll search the current directory
985 # as well as parent dirs.
986 #
987 for sDir in list(asCandidates):
988 for i in range(10):
989 sDir = os.path.dirname(sDir);
990 if sDir not in asCandidates:
991 asCandidates.append(sDir);
992
993 #
994 # Do the searching.
995 #
996 sCandidate = None;
997 for i, _ in enumerate(asCandidates):
998 sCandidate = asCandidates[i];
999 if os.path.isfile(os.path.join(sCandidate, 'VBoxValidationKit.iso')):
1000 break;
1001 sCandidate = os.path.join(sCandidate, 'validationkit');
1002 if os.path.isfile(os.path.join(sCandidate, 'VBoxValidationKit.iso')):
1003 break;
1004 sCandidate = None;
1005
1006 fRc = sCandidate is not None;
1007 if fRc is False:
1008 if not fQuiet:
1009 reporter.error('failed to find VBox Validation Kit installation (candidates: %s)' % (asCandidates,));
1010 sCandidate = os.path.join(self.sScriptPath, 'validationkit'); # Don't leave the values as None.
1011
1012 #
1013 # Set the member values.
1014 #
1015 self.sVBoxValidationKit = sCandidate;
1016 self.sVBoxValidationKitIso = os.path.join(sCandidate, 'VBoxValidationKit.iso');
1017 self.sVBoxBootSectors = os.path.join(sCandidate, 'bootsectors');
1018 return fRc;
1019
1020 def _makeEnvironmentChanges(self):
1021 """
1022 Make the necessary VBox related environment changes.
1023 Children not importing the VBox API should call this.
1024 """
1025 # Make sure we've got our own VirtualBox config and VBoxSVC (on XPCOM at least).
1026 if not self.fUseDefaultSvc:
1027 os.environ['VBOX_USER_HOME'] = os.path.join(self.sScratchPath, 'VBoxUserHome');
1028 sUser = os.environ.get('USERNAME', os.environ.get('USER', os.environ.get('LOGNAME', 'unknown')));
1029 os.environ['VBOX_IPC_SOCKETID'] = sUser + '-VBoxTest';
1030 return True;
1031
1032 @staticmethod
1033 def makeApiRevision(uMajor, uMinor, uBuild, uApiRevision):
1034 """ Calculates an API revision number. """
1035 return (long(uMajor) << 56) | (long(uMinor) << 48) | (long(uBuild) << 40) | uApiRevision;
1036
1037 def importVBoxApi(self):
1038 """
1039 Import the 'vboxapi' module from the VirtualBox build we're using and
1040 instantiate the two basic objects.
1041
1042 This will try detect an development or installed build if no build has
1043 been associated with the driver yet.
1044 """
1045 if self.fImportedVBoxApi:
1046 return True;
1047
1048 self._makeEnvironmentChanges();
1049
1050 # Do the detecting.
1051 self._detectBuild();
1052 if self.oBuild is None:
1053 return False;
1054
1055 # Avoid crashing when loading the 32-bit module (or whatever it is that goes bang).
1056 if self.oBuild.sArch == 'x86' \
1057 and self.sHost == 'darwin' \
1058 and platform.architecture()[0] == '64bit' \
1059 and self.oBuild.sKind == 'development' \
1060 and os.getenv('VERSIONER_PYTHON_PREFER_32_BIT') != 'yes':
1061 reporter.log("WARNING: 64-bit python on darwin, 32-bit VBox development build => crash");
1062 reporter.log("WARNING: bash-3.2$ /usr/bin/python2.5 ./testdriver");
1063 reporter.log("WARNING: or");
1064 reporter.log("WARNING: bash-3.2$ VERSIONER_PYTHON_PREFER_32_BIT=yes ./testdriver");
1065 return False;
1066
1067 # Start VBoxSVC and load the vboxapi bits.
1068 if self._startVBoxSVC() is True:
1069 assert(self.oVBoxSvcProcess is not None);
1070
1071 sSavedSysPath = sys.path;
1072 self._setupVBoxApi();
1073 sys.path = sSavedSysPath;
1074
1075 # Adjust the default machine folder.
1076 if self.fImportedVBoxApi and not self.fUseDefaultSvc and self.fpApiVer >= 4.0:
1077 sNewFolder = os.path.join(self.sScratchPath, 'VBoxUserHome', 'Machines');
1078 try:
1079 self.oVBox.systemProperties.defaultMachineFolder = sNewFolder;
1080 except:
1081 self.fImportedVBoxApi = False;
1082 self.oVBoxMgr = None;
1083 self.oVBox = None;
1084 reporter.logXcpt("defaultMachineFolder exception (sNewFolder=%s)" % (sNewFolder,));
1085
1086 # Kill VBoxSVC on failure.
1087 if self.oVBoxMgr is None:
1088 self._stopVBoxSVC();
1089 else:
1090 assert(self.oVBoxSvcProcess is None);
1091 return self.fImportedVBoxApi;
1092
1093 def _startVBoxSVC(self): # pylint: disable=too-many-statements
1094 """ Starts VBoxSVC. """
1095 assert(self.oVBoxSvcProcess is None);
1096
1097 # Setup vbox logging for VBoxSVC now and start it manually. This way
1098 # we can control both logging and shutdown.
1099 self.sVBoxSvcLogFile = '%s/VBoxSVC-debug.log' % (self.sScratchPath,);
1100 try: os.remove(self.sVBoxSvcLogFile);
1101 except: pass;
1102 os.environ['VBOX_LOG'] = self.sLogSvcGroups;
1103 os.environ['VBOX_LOG_FLAGS'] = '%s append' % (self.sLogSvcFlags,); # Append becuse of VBoxXPCOMIPCD.
1104 if self.sLogSvcDest:
1105 os.environ['VBOX_LOG_DEST'] = 'nodeny ' + self.sLogSvcDest;
1106 else:
1107 os.environ['VBOX_LOG_DEST'] = 'nodeny file=%s' % (self.sVBoxSvcLogFile,);
1108 os.environ['VBOXSVC_RELEASE_LOG_FLAGS'] = 'time append';
1109
1110 # Always leave a pid file behind so we can kill it during cleanup-before.
1111 self.sVBoxSvcPidFile = '%s/VBoxSVC.pid' % (self.sScratchPath,);
1112 fWritePidFile = True;
1113
1114 cMsFudge = 1;
1115 sVBoxSVC = '%s/VBoxSVC' % (self.oBuild.sInstallPath,); ## @todo .exe and stuff.
1116 if self.fVBoxSvcInDebugger:
1117 if self.sHost in ('darwin', 'freebsd', 'linux', 'solaris', ):
1118 # Start VBoxSVC in gdb in a new terminal.
1119 #sTerm = '/usr/bin/gnome-terminal'; - doesn't work, some fork+exec stuff confusing us.
1120 sTerm = '/usr/bin/xterm';
1121 if not os.path.isfile(sTerm): sTerm = '/usr/X11/bin/xterm';
1122 if not os.path.isfile(sTerm): sTerm = '/usr/X11R6/bin/xterm';
1123 if not os.path.isfile(sTerm): sTerm = '/usr/bin/xterm';
1124 if not os.path.isfile(sTerm): sTerm = 'xterm';
1125 sGdb = '/usr/bin/gdb';
1126 if not os.path.isfile(sGdb): sGdb = '/usr/local/bin/gdb';
1127 if not os.path.isfile(sGdb): sGdb = '/usr/sfw/bin/gdb';
1128 if not os.path.isfile(sGdb): sGdb = 'gdb';
1129 sGdbCmdLine = '%s --args %s --pidfile %s' % (sGdb, sVBoxSVC, self.sVBoxSvcPidFile);
1130 # Cool tweak to run performance analysis instead of gdb:
1131 #sGdb = '/usr/bin/valgrind';
1132 #sGdbCmdLine = '%s --tool=callgrind --collect-atstart=no -- %s --pidfile %s' \
1133 # % (sGdb, sVBoxSVC, self.sVBoxSvcPidFile);
1134 reporter.log('term="%s" gdb="%s"' % (sTerm, sGdbCmdLine));
1135 os.environ['SHELL'] = self.sOrgShell; # Non-working shell may cause gdb and/or the term problems.
1136 ## @todo -e is deprecated; use "-- <args>".
1137 self.oVBoxSvcProcess = base.Process.spawnp(sTerm, sTerm, '-e', sGdbCmdLine);
1138 os.environ['SHELL'] = self.sOurShell;
1139 if self.oVBoxSvcProcess is not None:
1140 reporter.log('Press enter or return after starting VBoxSVC in the debugger...');
1141 sys.stdin.read(1);
1142 fWritePidFile = False;
1143
1144 elif self.sHost == 'win':
1145 sWinDbg = 'c:\\Program Files\\Debugging Tools for Windows\\windbg.exe';
1146 if not os.path.isfile(sWinDbg): sWinDbg = 'c:\\Program Files\\Debugging Tools for Windows (x64)\\windbg.exe';
1147 if not os.path.isfile(sWinDbg): sWinDbg = 'c:\\Programme\\Debugging Tools for Windows\\windbg.exe'; # Localization rulez! pylint: disable=line-too-long
1148 if not os.path.isfile(sWinDbg): sWinDbg = 'c:\\Programme\\Debugging Tools for Windows (x64)\\windbg.exe';
1149 if not os.path.isfile(sWinDbg): sWinDbg = 'windbg'; # WinDbg must be in the path; better than nothing.
1150 # Assume that everything WinDbg needs is defined using the environment variables.
1151 # See WinDbg help for more information.
1152 reporter.log('windbg="%s"' % (sWinDbg));
1153 self.oVBoxSvcProcess = base.Process.spawn(sWinDbg, sWinDbg, sVBoxSVC + base.exeSuff());
1154 if self.oVBoxSvcProcess is not None:
1155 reporter.log('Press enter or return after starting VBoxSVC in the debugger...');
1156 sys.stdin.read(1);
1157 fWritePidFile = False;
1158 ## @todo add a pipe interface similar to xpcom if feasible, i.e. if
1159 # we can get actual handle values for pipes in python.
1160
1161 else:
1162 reporter.error('Port me!');
1163 else: # Run without a debugger attached.
1164 if self.sHost in ('darwin', 'freebsd', 'linux', 'solaris', ):
1165 #
1166 # XPCOM - We can use a pipe to let VBoxSVC notify us when it's ready.
1167 #
1168 iPipeR, iPipeW = os.pipe();
1169 if hasattr(os, 'set_inheritable'):
1170 os.set_inheritable(iPipeW, True); # pylint: disable=no-member
1171 os.environ['NSPR_INHERIT_FDS'] = 'vboxsvc:startup-pipe:5:0x%x' % (iPipeW,);
1172 reporter.log2("NSPR_INHERIT_FDS=%s" % (os.environ['NSPR_INHERIT_FDS']));
1173
1174 self.oVBoxSvcProcess = base.Process.spawn(sVBoxSVC, sVBoxSVC, '--auto-shutdown'); # SIGUSR1 requirement.
1175 try: # Try make sure we get the SIGINT and not VBoxSVC.
1176 os.setpgid(self.oVBoxSvcProcess.getPid(), 0); # pylint: disable=no-member
1177 os.setpgid(0, 0); # pylint: disable=no-member
1178 except:
1179 reporter.logXcpt();
1180
1181 os.close(iPipeW);
1182 try:
1183 sResponse = os.read(iPipeR, 32);
1184 except:
1185 reporter.logXcpt();
1186 sResponse = None;
1187 os.close(iPipeR);
1188
1189 if hasattr(sResponse, 'decode'):
1190 sResponse = sResponse.decode('utf-8', 'ignore');
1191
1192 if sResponse is None or sResponse.strip() != 'READY':
1193 reporter.error('VBoxSVC failed starting up... (sResponse=%s)' % (sResponse,));
1194 if not self.oVBoxSvcProcess.wait(5000):
1195 self.oVBoxSvcProcess.terminate();
1196 self.oVBoxSvcProcess.wait(5000);
1197 self.oVBoxSvcProcess = None;
1198
1199 elif self.sHost == 'win':
1200 #
1201 # Windows - Just fudge it for now.
1202 #
1203 cMsFudge = 2000;
1204 self.oVBoxSvcProcess = base.Process.spawn(sVBoxSVC, sVBoxSVC);
1205
1206 else:
1207 reporter.error('Port me!');
1208
1209 #
1210 # Enable automatic crash reporting if we succeeded.
1211 #
1212 if self.oVBoxSvcProcess is not None:
1213 self.oVBoxSvcProcess.enableCrashReporting('crash/report/svc', 'crash/dump/svc');
1214
1215 #
1216 # Wait for debugger to attach.
1217 #
1218 if self.oVBoxSvcProcess is not None and self.fVBoxSvcWaitForDebugger:
1219 reporter.log('Press any key after attaching to VBoxSVC (pid %s) with a debugger...'
1220 % (self.oVBoxSvcProcess.getPid(),));
1221 sys.stdin.read(1);
1222
1223 #
1224 # Fudge and pid file.
1225 #
1226 if self.oVBoxSvcProcess is not None and not self.oVBoxSvcProcess.wait(cMsFudge):
1227 if fWritePidFile:
1228 iPid = self.oVBoxSvcProcess.getPid();
1229 try:
1230 oFile = utils.openNoInherit(self.sVBoxSvcPidFile, "w+");
1231 oFile.write('%s' % (iPid,));
1232 oFile.close();
1233 except:
1234 reporter.logXcpt('sPidFile=%s' % (self.sVBoxSvcPidFile,));
1235 reporter.log('VBoxSVC PID=%u' % (iPid,));
1236
1237 #
1238 # Finally add the task so we'll notice when it dies in a relatively timely manner.
1239 #
1240 self.addTask(self.oVBoxSvcProcess);
1241 else:
1242 self.oVBoxSvcProcess = None;
1243 try: os.remove(self.sVBoxSvcPidFile);
1244 except: pass;
1245
1246 return self.oVBoxSvcProcess is not None;
1247
1248
1249 def _killVBoxSVCByPidFile(self, sPidFile):
1250 """ Kill a VBoxSVC given the pid from it's pid file. """
1251
1252 # Read the pid file.
1253 if not os.path.isfile(sPidFile):
1254 return False;
1255 try:
1256 oFile = utils.openNoInherit(sPidFile, "r");
1257 sPid = oFile.readline().strip();
1258 oFile.close();
1259 except:
1260 reporter.logXcpt('sPidfile=%s' % (sPidFile,));
1261 return False;
1262
1263 # Convert the pid to an integer and validate the range a little bit.
1264 try:
1265 iPid = long(sPid);
1266 except:
1267 reporter.logXcpt('sPidfile=%s sPid="%s"' % (sPidFile, sPid));
1268 return False;
1269 if iPid <= 0:
1270 reporter.log('negative pid - sPidfile=%s sPid="%s" iPid=%d' % (sPidFile, sPid, iPid));
1271 return False;
1272
1273 # Take care checking that it's VBoxSVC we're about to inhume.
1274 if base.processCheckPidAndName(iPid, "VBoxSVC") is not True:
1275 reporter.log('Ignoring stale VBoxSVC pid file (pid=%s)' % (iPid,));
1276 return False;
1277
1278 # Loop thru our different ways of getting VBoxSVC to terminate.
1279 for aHow in [ [ base.sendUserSignal1, 5000, 'Dropping VBoxSVC a SIGUSR1 hint...'], \
1280 [ base.processInterrupt, 5000, 'Dropping VBoxSVC a SIGINT hint...'], \
1281 [ base.processTerminate, 7500, 'VBoxSVC is still around, killing it...'] ]:
1282 reporter.log(aHow[2]);
1283 if aHow[0](iPid) is True:
1284 msStart = base.timestampMilli();
1285 while base.timestampMilli() - msStart < 5000 \
1286 and base.processExists(iPid):
1287 time.sleep(0.2);
1288
1289 fRc = not base.processExists(iPid);
1290 if fRc is True:
1291 break;
1292 if fRc:
1293 reporter.log('Successfully killed VBoxSVC (pid=%s)' % (iPid,));
1294 else:
1295 reporter.log('Failed to kill VBoxSVC (pid=%s)' % (iPid,));
1296 return fRc;
1297
1298 def _stopVBoxSVC(self):
1299 """
1300 Stops VBoxSVC. Try the polite way first.
1301 """
1302
1303 if self.oVBoxSvcProcess:
1304 self.removeTask(self.oVBoxSvcProcess);
1305 self.oVBoxSvcProcess.enableCrashReporting(None, None); # Disables it.
1306
1307 fRc = False;
1308 if self.oVBoxSvcProcess is not None \
1309 and not self.fVBoxSvcInDebugger:
1310 # by process object.
1311 if self.oVBoxSvcProcess.isRunning():
1312 reporter.log('Dropping VBoxSVC a SIGUSR1 hint...');
1313 if not self.oVBoxSvcProcess.sendUserSignal1() \
1314 or not self.oVBoxSvcProcess.wait(5000):
1315 reporter.log('Dropping VBoxSVC a SIGINT hint...');
1316 if not self.oVBoxSvcProcess.interrupt() \
1317 or not self.oVBoxSvcProcess.wait(5000):
1318 reporter.log('VBoxSVC is still around, killing it...');
1319 self.oVBoxSvcProcess.terminate();
1320 self.oVBoxSvcProcess.wait(7500);
1321 else:
1322 reporter.log('VBoxSVC is no longer running...');
1323
1324 if not self.oVBoxSvcProcess.isRunning():
1325 iExit = self.oVBoxSvcProcess.getExitCode();
1326 if iExit != 0 or not self.oVBoxSvcProcess.isNormalExit():
1327 reporter.error("VBoxSVC exited with status %d (%#x)" % (iExit, self.oVBoxSvcProcess.uExitCode));
1328 self.oVBoxSvcProcess = None;
1329 else:
1330 # by pid file.
1331 self._killVBoxSVCByPidFile('%s/VBoxSVC.pid' % (self.sScratchPath,));
1332 return fRc;
1333
1334 def _setupVBoxApi(self):
1335 """
1336 Import and set up the vboxapi.
1337 The caller saves and restores sys.path.
1338 """
1339
1340 # Setup vbox logging for self (the test driver).
1341 self.sSelfLogFile = '%s/VBoxTestDriver.log' % (self.sScratchPath,);
1342 try: os.remove(self.sSelfLogFile);
1343 except: pass;
1344 os.environ['VBOX_LOG'] = self.sLogSelfGroups;
1345 os.environ['VBOX_LOG_FLAGS'] = '%s append' % (self.sLogSelfFlags, );
1346 if self.sLogSelfDest:
1347 os.environ['VBOX_LOG_DEST'] = 'nodeny ' + self.sLogSelfDest;
1348 else:
1349 os.environ['VBOX_LOG_DEST'] = 'nodeny file=%s' % (self.sSelfLogFile,);
1350 os.environ['VBOX_RELEASE_LOG_FLAGS'] = 'time append';
1351
1352 # Hack the sys.path + environment so the vboxapi can be found.
1353 sys.path.insert(0, self.oBuild.sInstallPath);
1354 if self.oBuild.sSdkPath is not None:
1355 sys.path.insert(0, os.path.join(self.oBuild.sSdkPath, 'installer'))
1356 sys.path.insert(1, os.path.join(self.oBuild.sSdkPath, 'install')); # stupid stupid windows installer!
1357 sys.path.insert(2, os.path.join(self.oBuild.sSdkPath, 'bindings', 'xpcom', 'python'))
1358 os.environ['VBOX_PROGRAM_PATH'] = self.oBuild.sInstallPath;
1359 reporter.log("sys.path: %s" % (sys.path));
1360
1361 try:
1362 from vboxapi import VirtualBoxManager; # pylint: disable=import-error
1363 except:
1364 reporter.logXcpt('Error importing vboxapi');
1365 return False;
1366
1367 # Exception and error hacks.
1368 try:
1369 # pylint: disable=import-error
1370 if self.sHost == 'win':
1371 from pythoncom import com_error as NativeComExceptionClass # pylint: disable=no-name-in-module
1372 import winerror as NativeComErrorClass
1373 else:
1374 from xpcom import Exception as NativeComExceptionClass
1375 from xpcom import nsError as NativeComErrorClass
1376 # pylint: enable=import-error
1377 except:
1378 reporter.logXcpt('Error importing (XP)COM related stuff for exception hacks and errors');
1379 return False;
1380 __deployExceptionHacks__(NativeComExceptionClass)
1381 ComError.copyErrors(NativeComErrorClass);
1382
1383 # Create the manager.
1384 try:
1385 self.oVBoxMgr = VirtualBoxManager(None, None)
1386 except:
1387 self.oVBoxMgr = None;
1388 reporter.logXcpt('VirtualBoxManager exception');
1389 return False;
1390
1391 # Figure the API version.
1392 try:
1393 oVBox = self.oVBoxMgr.getVirtualBox();
1394
1395 try:
1396 sVer = oVBox.version;
1397 except:
1398 reporter.logXcpt('Failed to get VirtualBox version, assuming 4.0.0');
1399 sVer = "4.0.0";
1400 reporter.log("IVirtualBox.version=%s" % (sVer,));
1401
1402 # Convert the string to three integer values and check ranges.
1403 asVerComponents = sVer.split('.');
1404 try:
1405 sLast = asVerComponents[2].split('_')[0].split('r')[0];
1406 aiVerComponents = (int(asVerComponents[0]), int(asVerComponents[1]), int(sLast));
1407 except:
1408 raise base.GenError('Malformed version "%s"' % (sVer,));
1409 if aiVerComponents[0] < 3 or aiVerComponents[0] > 19:
1410 raise base.GenError('Malformed version "%s" - 1st component is out of bounds 3..19: %u'
1411 % (sVer, aiVerComponents[0]));
1412 if aiVerComponents[1] < 0 or aiVerComponents[1] > 9:
1413 raise base.GenError('Malformed version "%s" - 2nd component is out of bounds 0..9: %u'
1414 % (sVer, aiVerComponents[1]));
1415 if aiVerComponents[2] < 0 or aiVerComponents[2] > 99:
1416 raise base.GenError('Malformed version "%s" - 3rd component is out of bounds 0..99: %u'
1417 % (sVer, aiVerComponents[2]));
1418
1419 # Convert the three integers into a floating point value. The API is stable within a
1420 # x.y release, so the third component only indicates whether it's a stable or
1421 # development build of the next release.
1422 self.fpApiVer = aiVerComponents[0] + 0.1 * aiVerComponents[1];
1423 if aiVerComponents[2] >= 51:
1424 if self.fpApiVer not in [6.1, 5.2, 4.3, 3.2,]:
1425 self.fpApiVer += 0.1;
1426 else:
1427 self.fpApiVer = int(self.fpApiVer) + 1.0;
1428 # fudge value to be always bigger than the nominal value (0.1 gets rounded down)
1429 if round(self.fpApiVer, 1) > self.fpApiVer:
1430 self.fpApiVer += sys.float_info.epsilon * self.fpApiVer / 2.0;
1431
1432 try:
1433 self.uRevision = oVBox.revision;
1434 except:
1435 reporter.logXcpt('Failed to get VirtualBox revision, assuming 0');
1436 self.uRevision = 0;
1437 reporter.log("IVirtualBox.revision=%u" % (self.uRevision,));
1438
1439 try:
1440 self.uApiRevision = oVBox.APIRevision;
1441 except:
1442 reporter.logXcpt('Failed to get VirtualBox APIRevision, faking it.');
1443 self.uApiRevision = self.makeApiRevision(aiVerComponents[0], aiVerComponents[1], aiVerComponents[2], 0);
1444 reporter.log("IVirtualBox.APIRevision=%#x" % (self.uApiRevision,));
1445
1446 # Patch VBox manage to gloss over portability issues (error constants, etc).
1447 self._patchVBoxMgr();
1448
1449 # Wrap oVBox.
1450 from testdriver.vboxwrappers import VirtualBoxWrapper;
1451 self.oVBox = VirtualBoxWrapper(oVBox, self.oVBoxMgr, self.fpApiVer, self);
1452
1453 # Install the constant wrapping hack.
1454 vboxcon.goHackModuleClass.oVBoxMgr = self.oVBoxMgr; # VBoxConstantWrappingHack.
1455 vboxcon.fpApiVer = self.fpApiVer;
1456 reporter.setComXcptFormatter(formatComOrXpComException);
1457
1458 except:
1459 self.oVBoxMgr = None;
1460 self.oVBox = None;
1461 reporter.logXcpt("getVirtualBox / API version exception");
1462 return False;
1463
1464 # Done
1465 self.fImportedVBoxApi = True;
1466 reporter.log('Found version %s (%s)' % (self.fpApiVer, sVer));
1467 return True;
1468
1469 def _patchVBoxMgr(self):
1470 """
1471 Glosses over missing self.oVBoxMgr methods on older VBox versions.
1472 """
1473
1474 def _xcptGetResult(oSelf, oXcpt = None):
1475 """ See vboxapi. """
1476 _ = oSelf;
1477 if oXcpt is None: oXcpt = sys.exc_info()[1];
1478 if sys.platform == 'win32':
1479 import winerror; # pylint: disable=import-error
1480 hrXcpt = oXcpt.hresult;
1481 if hrXcpt == winerror.DISP_E_EXCEPTION:
1482 hrXcpt = oXcpt.excepinfo[5];
1483 else:
1484 hrXcpt = oXcpt.error;
1485 return hrXcpt;
1486
1487 def _xcptIsDeadInterface(oSelf, oXcpt = None):
1488 """ See vboxapi. """
1489 return oSelf.xcptGetStatus(oXcpt) in [
1490 0x80004004, -2147467260, # NS_ERROR_ABORT
1491 0x800706be, -2147023170, # NS_ERROR_CALL_FAILED (RPC_S_CALL_FAILED)
1492 0x800706ba, -2147023174, # RPC_S_SERVER_UNAVAILABLE.
1493 0x800706be, -2147023170, # RPC_S_CALL_FAILED.
1494 0x800706bf, -2147023169, # RPC_S_CALL_FAILED_DNE.
1495 0x80010108, -2147417848, # RPC_E_DISCONNECTED.
1496 0x800706b5, -2147023179, # RPC_S_UNKNOWN_IF
1497 ];
1498
1499 def _xcptIsOurXcptKind(oSelf, oXcpt = None):
1500 """ See vboxapi. """
1501 _ = oSelf;
1502 if oXcpt is None: oXcpt = sys.exc_info()[1];
1503 if sys.platform == 'win32':
1504 from pythoncom import com_error as NativeComExceptionClass # pylint: disable=import-error,no-name-in-module
1505 else:
1506 from xpcom import Exception as NativeComExceptionClass # pylint: disable=import-error
1507 return isinstance(oXcpt, NativeComExceptionClass);
1508
1509 def _xcptIsEqual(oSelf, oXcpt, hrStatus):
1510 """ See vboxapi. """
1511 hrXcpt = oSelf.xcptGetResult(oXcpt);
1512 return hrXcpt == hrStatus or hrXcpt == hrStatus - 0x100000000; # pylint: disable=consider-using-in
1513
1514 def _xcptToString(oSelf, oXcpt):
1515 """ See vboxapi. """
1516 _ = oSelf;
1517 if oXcpt is None: oXcpt = sys.exc_info()[1];
1518 return str(oXcpt);
1519
1520 def _getEnumValueName(oSelf, sEnumTypeNm, oEnumValue, fTypePrefix = False):
1521 """ See vboxapi. """
1522 _ = oSelf; _ = fTypePrefix;
1523 return '%s::%s' % (sEnumTypeNm, oEnumValue);
1524
1525 # Add utilities found in newer vboxapi revision.
1526 if not hasattr(self.oVBoxMgr, 'xcptIsDeadInterface'):
1527 import types;
1528 self.oVBoxMgr.xcptGetResult = types.MethodType(_xcptGetResult, self.oVBoxMgr);
1529 self.oVBoxMgr.xcptIsDeadInterface = types.MethodType(_xcptIsDeadInterface, self.oVBoxMgr);
1530 self.oVBoxMgr.xcptIsOurXcptKind = types.MethodType(_xcptIsOurXcptKind, self.oVBoxMgr);
1531 self.oVBoxMgr.xcptIsEqual = types.MethodType(_xcptIsEqual, self.oVBoxMgr);
1532 self.oVBoxMgr.xcptToString = types.MethodType(_xcptToString, self.oVBoxMgr);
1533 if not hasattr(self.oVBoxMgr, 'getEnumValueName'):
1534 import types;
1535 self.oVBoxMgr.getEnumValueName = types.MethodType(_getEnumValueName, self.oVBoxMgr);
1536
1537
1538 def _teardownVBoxApi(self): # pylint: disable=too-many-statements
1539 """
1540 Drop all VBox object references and shutdown com/xpcom.
1541 """
1542 if not self.fImportedVBoxApi:
1543 return True;
1544 import gc;
1545
1546 # Drop all references we've have to COM objects.
1547 self.aoRemoteSessions = [];
1548 self.aoVMs = [];
1549 self.oVBoxMgr = None;
1550 self.oVBox = None;
1551 vboxcon.goHackModuleClass.oVBoxMgr = None; # VBoxConstantWrappingHack.
1552 reporter.setComXcptFormatter(None);
1553
1554 # Do garbage collection to try get rid of those objects.
1555 try:
1556 gc.collect();
1557 except:
1558 reporter.logXcpt();
1559 self.fImportedVBoxApi = False;
1560
1561 # Check whether the python is still having any COM objects/interfaces around.
1562 cVBoxMgrs = 0;
1563 aoObjsLeftBehind = [];
1564 if self.sHost == 'win':
1565 import pythoncom; # pylint: disable=import-error
1566 try:
1567 cIfs = pythoncom._GetInterfaceCount(); # pylint: disable=no-member,protected-access
1568 cObjs = pythoncom._GetGatewayCount(); # pylint: disable=no-member,protected-access
1569 if cObjs == 0 and cIfs == 0:
1570 reporter.log('_teardownVBoxApi: no interfaces or objects left behind.');
1571 else:
1572 reporter.log('_teardownVBoxApi: Python COM still has %s objects and %s interfaces...' % ( cObjs, cIfs));
1573
1574 from win32com.client import DispatchBaseClass; # pylint: disable=import-error
1575 for oObj in gc.get_objects():
1576 if isinstance(oObj, DispatchBaseClass):
1577 reporter.log('_teardownVBoxApi: %s' % (oObj,));
1578 aoObjsLeftBehind.append(oObj);
1579 elif utils.getObjectTypeName(oObj) == 'VirtualBoxManager':
1580 reporter.log('_teardownVBoxApi: %s' % (oObj,));
1581 cVBoxMgrs += 1;
1582 aoObjsLeftBehind.append(oObj);
1583 oObj = None;
1584 except:
1585 reporter.logXcpt();
1586
1587 # If not being used, we can safely uninitialize COM.
1588 if cIfs == 0 and cObjs == 0 and cVBoxMgrs == 0 and not aoObjsLeftBehind:
1589 reporter.log('_teardownVBoxApi: Calling CoUninitialize...');
1590 try: pythoncom.CoUninitialize(); # pylint: disable=no-member
1591 except: reporter.logXcpt();
1592 else:
1593 reporter.log('_teardownVBoxApi: Returned from CoUninitialize.');
1594 else:
1595 try:
1596 # XPCOM doesn't crash and burn like COM if you shut it down with interfaces and objects around.
1597 # Also, it keeps a number of internal objects and interfaces around to do its job, so shutting
1598 # it down before we go looking for dangling interfaces is more or less required.
1599 from xpcom import _xpcom as _xpcom; # pylint: disable=import-error,useless-import-alias
1600 hrc = _xpcom.DeinitCOM();
1601 cIfs = _xpcom._GetInterfaceCount(); # pylint: disable=protected-access
1602 cObjs = _xpcom._GetGatewayCount(); # pylint: disable=protected-access
1603
1604 if cObjs == 0 and cIfs == 0:
1605 reporter.log('_teardownVBoxApi: No XPCOM interfaces or objects active. (hrc=%#x)' % (hrc,));
1606 else:
1607 reporter.log('_teardownVBoxApi: %s XPCOM objects and %s interfaces still around! (hrc=%#x)'
1608 % (cObjs, cIfs, hrc));
1609 if hasattr(_xpcom, '_DumpInterfaces'):
1610 try: _xpcom._DumpInterfaces(); # pylint: disable=protected-access
1611 except: reporter.logXcpt('_teardownVBoxApi: _DumpInterfaces failed');
1612
1613 from xpcom.client import Component; # pylint: disable=import-error
1614 for oObj in gc.get_objects():
1615 if isinstance(oObj, Component):
1616 reporter.log('_teardownVBoxApi: %s' % (oObj,));
1617 aoObjsLeftBehind.append(oObj);
1618 if utils.getObjectTypeName(oObj) == 'VirtualBoxManager':
1619 reporter.log('_teardownVBoxApi: %s' % (oObj,));
1620 cVBoxMgrs += 1;
1621 aoObjsLeftBehind.append(oObj);
1622 oObj = None;
1623 except:
1624 reporter.logXcpt();
1625
1626 # Try get the referrers to (XP)COM interfaces and objects that was left behind.
1627 for iObj in range(len(aoObjsLeftBehind)): # pylint: disable=consider-using-enumerate
1628 try:
1629 aoReferrers = gc.get_referrers(aoObjsLeftBehind[iObj]);
1630 reporter.log('_teardownVBoxApi: Found %u referrers to %s:' % (len(aoReferrers), aoObjsLeftBehind[iObj],));
1631 for oReferrer in aoReferrers:
1632 oMyFrame = sys._getframe(0); # pylint: disable=protected-access
1633 if oReferrer is oMyFrame:
1634 reporter.log('_teardownVBoxApi: - frame of this function');
1635 elif oReferrer is aoObjsLeftBehind:
1636 reporter.log('_teardownVBoxApi: - aoObjsLeftBehind');
1637 else:
1638 fPrinted = False;
1639 if isinstance(oReferrer, (dict, list, tuple)):
1640 try:
1641 aoSubReferreres = gc.get_referrers(oReferrer);
1642 for oSubRef in aoSubReferreres:
1643 if not isinstance(oSubRef, list) \
1644 and not isinstance(oSubRef, dict) \
1645 and oSubRef is not oMyFrame \
1646 and oSubRef is not aoSubReferreres:
1647 reporter.log('_teardownVBoxApi: - %s :: %s:'
1648 % (utils.getObjectTypeName(oSubRef), utils.getObjectTypeName(oReferrer)));
1649 fPrinted = True;
1650 break;
1651 del aoSubReferreres;
1652 except:
1653 reporter.logXcpt('subref');
1654 if not fPrinted:
1655 reporter.log('_teardownVBoxApi: - %s:' % (utils.getObjectTypeName(oReferrer),));
1656 try:
1657 import pprint;
1658 for sLine in pprint.pformat(oReferrer, width = 130).split('\n'):
1659 reporter.log('_teardownVBoxApi: %s' % (sLine,));
1660 except:
1661 reporter.log('_teardownVBoxApi: %s' % (oReferrer,));
1662 except:
1663 reporter.logXcpt();
1664 del aoObjsLeftBehind;
1665
1666 # Force garbage collection again, just for good measure.
1667 try:
1668 gc.collect();
1669 time.sleep(0.5); # fudge factor
1670 except:
1671 reporter.logXcpt();
1672 return True;
1673
1674 def _powerOffAllVms(self):
1675 """
1676 Tries to power off all running VMs.
1677 """
1678 for oSession in self.aoRemoteSessions:
1679 uPid = oSession.getPid();
1680 if uPid is not None:
1681 reporter.log('_powerOffAllVms: PID is %s for %s, trying to kill it.' % (uPid, oSession.sName,));
1682 base.processKill(uPid);
1683 else:
1684 reporter.log('_powerOffAllVms: No PID for %s' % (oSession.sName,));
1685 oSession.close();
1686 return None;
1687
1688
1689
1690 #
1691 # Build type, OS and arch getters.
1692 #
1693
1694 def getBuildType(self):
1695 """
1696 Get the build type.
1697 """
1698 if not self._detectBuild():
1699 return 'release';
1700 return self.oBuild.sType;
1701
1702 def getBuildOs(self):
1703 """
1704 Get the build OS.
1705 """
1706 if not self._detectBuild():
1707 return self.sHost;
1708 return self.oBuild.sOs;
1709
1710 def getBuildArch(self):
1711 """
1712 Get the build arch.
1713 """
1714 if not self._detectBuild():
1715 return self.sHostArch;
1716 return self.oBuild.sArch;
1717
1718 def getGuestAdditionsIso(self):
1719 """
1720 Get the path to the guest addition iso.
1721 """
1722 if not self._detectBuild():
1723 return None;
1724 return self.oBuild.sGuestAdditionsIso;
1725
1726 #
1727 # Override everything from the base class so the testdrivers don't have to
1728 # check whether we have overridden a method or not.
1729 #
1730
1731 def showUsage(self):
1732 rc = base.TestDriver.showUsage(self);
1733 reporter.log('');
1734 reporter.log('Generic VirtualBox Options:');
1735 reporter.log(' --vbox-session-type <type>');
1736 reporter.log(' Sets the session type. Typical values are: gui, headless, sdl');
1737 reporter.log(' Default: %s' % (self.sSessionTypeDef));
1738 reporter.log(' --vrdp, --no-vrdp');
1739 reporter.log(' Enables VRDP, ports starting at 6000');
1740 reporter.log(' Default: --vrdp');
1741 reporter.log(' --vrdp-base-port <port>');
1742 reporter.log(' Sets the base for VRDP port assignments.');
1743 reporter.log(' Default: %s' % (self.uVrdpBasePortDef));
1744 reporter.log(' --vbox-default-bridged-nic <interface>');
1745 reporter.log(' Sets the default interface for bridged networking.');
1746 reporter.log(' Default: autodetect');
1747 reporter.log(' --vbox-use-svc-defaults');
1748 reporter.log(' Use default locations and files for VBoxSVC. This is useful');
1749 reporter.log(' for automatically configuring the test VMs for debugging.');
1750 reporter.log(' --vbox-log');
1751 reporter.log(' The VBox logger group settings for everyone.');
1752 reporter.log(' --vbox-log-flags');
1753 reporter.log(' The VBox logger flags settings for everyone.');
1754 reporter.log(' --vbox-log-dest');
1755 reporter.log(' The VBox logger destination settings for everyone.');
1756 reporter.log(' --vbox-self-log');
1757 reporter.log(' The VBox logger group settings for the testdriver.');
1758 reporter.log(' --vbox-self-log-flags');
1759 reporter.log(' The VBox logger flags settings for the testdriver.');
1760 reporter.log(' --vbox-self-log-dest');
1761 reporter.log(' The VBox logger destination settings for the testdriver.');
1762 reporter.log(' --vbox-session-log');
1763 reporter.log(' The VM session logger group settings.');
1764 reporter.log(' --vbox-session-log-flags');
1765 reporter.log(' The VM session logger flags.');
1766 reporter.log(' --vbox-session-log-dest');
1767 reporter.log(' The VM session logger destination settings.');
1768 reporter.log(' --vbox-svc-log');
1769 reporter.log(' The VBoxSVC logger group settings.');
1770 reporter.log(' --vbox-svc-log-flags');
1771 reporter.log(' The VBoxSVC logger flag settings.');
1772 reporter.log(' --vbox-svc-log-dest');
1773 reporter.log(' The VBoxSVC logger destination settings.');
1774 reporter.log(' --vbox-svc-debug');
1775 reporter.log(' Start VBoxSVC in a debugger.');
1776 reporter.log(' --vbox-svc-wait-debug');
1777 reporter.log(' Start VBoxSVC and wait for debugger to attach to it.');
1778 reporter.log(' --vbox-always-upload-logs');
1779 reporter.log(' Whether to always upload log files, or only do so on failure.');
1780 reporter.log(' --vbox-always-upload-screenshots');
1781 reporter.log(' Whether to always upload final screen shots, or only do so on failure.');
1782 reporter.log(' --vbox-debugger, --no-vbox-debugger');
1783 reporter.log(' Enables the VBox debugger, port at 5000');
1784 reporter.log(' Default: --vbox-debugger');
1785 if self.oTestVmSet is not None:
1786 self.oTestVmSet.showUsage();
1787 return rc;
1788
1789 def parseOption(self, asArgs, iArg): # pylint: disable=too-many-statements
1790 if asArgs[iArg] == '--vbox-session-type':
1791 iArg += 1;
1792 if iArg >= len(asArgs):
1793 raise base.InvalidOption('The "--vbox-session-type" takes an argument');
1794 self.sSessionType = asArgs[iArg];
1795 elif asArgs[iArg] == '--vrdp':
1796 self.fEnableVrdp = True;
1797 elif asArgs[iArg] == '--no-vrdp':
1798 self.fEnableVrdp = False;
1799 elif asArgs[iArg] == '--vrdp-base-port':
1800 iArg += 1;
1801 if iArg >= len(asArgs):
1802 raise base.InvalidOption('The "--vrdp-base-port" takes an argument');
1803 try: self.uVrdpBasePort = int(asArgs[iArg]);
1804 except: raise base.InvalidOption('The "--vrdp-base-port" value "%s" is not a valid integer' % (asArgs[iArg],));
1805 if self.uVrdpBasePort <= 0 or self.uVrdpBasePort >= 65530:
1806 raise base.InvalidOption('The "--vrdp-base-port" value "%s" is not in the valid range (1..65530)'
1807 % (asArgs[iArg],));
1808 elif asArgs[iArg] == '--vbox-default-bridged-nic':
1809 iArg += 1;
1810 if iArg >= len(asArgs):
1811 raise base.InvalidOption('The "--vbox-default-bridged-nic" takes an argument');
1812 self.sDefBridgedNic = asArgs[iArg];
1813 elif asArgs[iArg] == '--vbox-use-svc-defaults':
1814 self.fUseDefaultSvc = True;
1815 elif asArgs[iArg] == '--vbox-self-log':
1816 iArg += 1;
1817 if iArg >= len(asArgs):
1818 raise base.InvalidOption('The "--vbox-self-log" takes an argument');
1819 self.sLogSelfGroups = asArgs[iArg];
1820 elif asArgs[iArg] == '--vbox-self-log-flags':
1821 iArg += 1;
1822 if iArg >= len(asArgs):
1823 raise base.InvalidOption('The "--vbox-self-log-flags" takes an argument');
1824 self.sLogSelfFlags = asArgs[iArg];
1825 elif asArgs[iArg] == '--vbox-self-log-dest':
1826 iArg += 1;
1827 if iArg >= len(asArgs):
1828 raise base.InvalidOption('The "--vbox-self-log-dest" takes an argument');
1829 self.sLogSelfDest = asArgs[iArg];
1830 elif asArgs[iArg] == '--vbox-session-log':
1831 iArg += 1;
1832 if iArg >= len(asArgs):
1833 raise base.InvalidOption('The "--vbox-session-log" takes an argument');
1834 self.sLogSessionGroups = asArgs[iArg];
1835 elif asArgs[iArg] == '--vbox-session-log-flags':
1836 iArg += 1;
1837 if iArg >= len(asArgs):
1838 raise base.InvalidOption('The "--vbox-session-log-flags" takes an argument');
1839 self.sLogSessionFlags = asArgs[iArg];
1840 elif asArgs[iArg] == '--vbox-session-log-dest':
1841 iArg += 1;
1842 if iArg >= len(asArgs):
1843 raise base.InvalidOption('The "--vbox-session-log-dest" takes an argument');
1844 self.sLogSessionDest = asArgs[iArg];
1845 elif asArgs[iArg] == '--vbox-svc-log':
1846 iArg += 1;
1847 if iArg >= len(asArgs):
1848 raise base.InvalidOption('The "--vbox-svc-log" takes an argument');
1849 self.sLogSvcGroups = asArgs[iArg];
1850 elif asArgs[iArg] == '--vbox-svc-log-flags':
1851 iArg += 1;
1852 if iArg >= len(asArgs):
1853 raise base.InvalidOption('The "--vbox-svc-log-flags" takes an argument');
1854 self.sLogSvcFlags = asArgs[iArg];
1855 elif asArgs[iArg] == '--vbox-svc-log-dest':
1856 iArg += 1;
1857 if iArg >= len(asArgs):
1858 raise base.InvalidOption('The "--vbox-svc-log-dest" takes an argument');
1859 self.sLogSvcDest = asArgs[iArg];
1860 elif asArgs[iArg] == '--vbox-log':
1861 iArg += 1;
1862 if iArg >= len(asArgs):
1863 raise base.InvalidOption('The "--vbox-log" takes an argument');
1864 self.sLogSelfGroups = asArgs[iArg];
1865 self.sLogSessionGroups = asArgs[iArg];
1866 self.sLogSvcGroups = asArgs[iArg];
1867 elif asArgs[iArg] == '--vbox-log-flags':
1868 iArg += 1;
1869 if iArg >= len(asArgs):
1870 raise base.InvalidOption('The "--vbox-svc-flags" takes an argument');
1871 self.sLogSelfFlags = asArgs[iArg];
1872 self.sLogSessionFlags = asArgs[iArg];
1873 self.sLogSvcFlags = asArgs[iArg];
1874 elif asArgs[iArg] == '--vbox-log-dest':
1875 iArg += 1;
1876 if iArg >= len(asArgs):
1877 raise base.InvalidOption('The "--vbox-log-dest" takes an argument');
1878 self.sLogSelfDest = asArgs[iArg];
1879 self.sLogSessionDest = asArgs[iArg];
1880 self.sLogSvcDest = asArgs[iArg];
1881 elif asArgs[iArg] == '--vbox-svc-debug':
1882 self.fVBoxSvcInDebugger = True;
1883 elif asArgs[iArg] == '--vbox-svc-wait-debug':
1884 self.fVBoxSvcWaitForDebugger = True;
1885 elif asArgs[iArg] == '--vbox-always-upload-logs':
1886 self.fAlwaysUploadLogs = True;
1887 elif asArgs[iArg] == '--vbox-always-upload-screenshots':
1888 self.fAlwaysUploadScreenshots = True;
1889 elif asArgs[iArg] == '--vbox-debugger':
1890 self.fEnableDebugger = True;
1891 elif asArgs[iArg] == '--no-vbox-debugger':
1892 self.fEnableDebugger = False;
1893 else:
1894 # Relevant for selecting VMs to test?
1895 if self.oTestVmSet is not None:
1896 iRc = self.oTestVmSet.parseOption(asArgs, iArg);
1897 if iRc != iArg:
1898 return iRc;
1899
1900 # Hand it to the base class.
1901 return base.TestDriver.parseOption(self, asArgs, iArg);
1902 return iArg + 1;
1903
1904 def completeOptions(self):
1905 return base.TestDriver.completeOptions(self);
1906
1907 def getNetworkAdapterNameFromType(self, oNic):
1908 """
1909 Returns the network adapter name from a given adapter type.
1910
1911 Returns an empty string if not found / invalid.
1912 """
1913 sAdpName = '';
1914 if oNic.adapterType == vboxcon.NetworkAdapterType_Am79C970A \
1915 or oNic.adapterType == vboxcon.NetworkAdapterType_Am79C973 \
1916 or oNic.adapterType == vboxcon.NetworkAdapterType_Am79C960:
1917 sAdpName = 'pcnet';
1918 elif oNic.adapterType == vboxcon.NetworkAdapterType_I82540EM \
1919 or oNic.adapterType == vboxcon.NetworkAdapterType_I82543GC \
1920 or oNic.adapterType == vboxcon.NetworkAdapterType_I82545EM:
1921 sAdpName = 'e1000';
1922 elif oNic.adapterType == vboxcon.NetworkAdapterType_Virtio:
1923 sAdpName = 'virtio-net';
1924 return sAdpName;
1925
1926 def getResourceSet(self):
1927 asRsrcs = [];
1928 if self.oTestVmSet is not None:
1929 asRsrcs.extend(self.oTestVmSet.getResourceSet());
1930 asRsrcs.extend(base.TestDriver.getResourceSet(self));
1931 return asRsrcs;
1932
1933 def actionExtract(self):
1934 return base.TestDriver.actionExtract(self);
1935
1936 def actionVerify(self):
1937 return base.TestDriver.actionVerify(self);
1938
1939 def actionConfig(self):
1940 return base.TestDriver.actionConfig(self);
1941
1942 def actionExecute(self):
1943 return base.TestDriver.actionExecute(self);
1944
1945 def actionCleanupBefore(self):
1946 """
1947 Kill any VBoxSVC left behind by a previous test run.
1948 """
1949 self._killVBoxSVCByPidFile('%s/VBoxSVC.pid' % (self.sScratchPath,));
1950 return base.TestDriver.actionCleanupBefore(self);
1951
1952 def actionCleanupAfter(self):
1953 """
1954 Clean up the VBox bits and then call the base driver.
1955
1956 If your test driver overrides this, it should normally call us at the
1957 end of the job.
1958 """
1959 cErrorsEntry = reporter.getErrorCount();
1960
1961 # Kill any left over VM processes.
1962 self._powerOffAllVms();
1963
1964 # Drop all VBox object references and shutdown xpcom then
1965 # terminating VBoxSVC, with extreme prejudice if need be.
1966 self._teardownVBoxApi();
1967 self._stopVBoxSVC();
1968
1969 # Add the VBoxSVC and testdriver debug+release log files.
1970 if self.fAlwaysUploadLogs or reporter.getErrorCount() > 0:
1971 if self.sVBoxSvcLogFile is not None and os.path.isfile(self.sVBoxSvcLogFile):
1972 reporter.addLogFile(self.sVBoxSvcLogFile, 'log/debug/svc', 'Debug log file for VBoxSVC');
1973 self.sVBoxSvcLogFile = None;
1974
1975 if self.sSelfLogFile is not None and os.path.isfile(self.sSelfLogFile):
1976 reporter.addLogFile(self.sSelfLogFile, 'log/debug/client', 'Debug log file for the test driver');
1977 self.sSelfLogFile = None;
1978
1979 sVBoxSvcRelLog = os.path.join(self.sScratchPath, 'VBoxUserHome', 'VBoxSVC.log');
1980 if os.path.isfile(sVBoxSvcRelLog):
1981 reporter.addLogFile(sVBoxSvcRelLog, 'log/release/svc', 'Release log file for VBoxSVC');
1982 for sSuff in [ '.1', '.2', '.3', '.4', '.5', '.6', '.7', '.8' ]:
1983 if os.path.isfile(sVBoxSvcRelLog + sSuff):
1984 reporter.addLogFile(sVBoxSvcRelLog + sSuff, 'log/release/svc', 'Release log file for VBoxSVC');
1985
1986 # Finally, call the base driver to wipe the scratch space.
1987 fRc = base.TestDriver.actionCleanupAfter(self);
1988
1989 # Flag failure if the error count increased.
1990 if reporter.getErrorCount() > cErrorsEntry:
1991 fRc = False;
1992 return fRc;
1993
1994
1995 def actionAbort(self):
1996 """
1997 Terminate VBoxSVC if we've got a pid file.
1998 """
1999 #
2000 # Take default action first, then kill VBoxSVC. The other way around
2001 # is problematic since the testscript would continue running and possibly
2002 # trigger a new VBoxSVC to start.
2003 #
2004 fRc1 = base.TestDriver.actionAbort(self);
2005 fRc2 = self._killVBoxSVCByPidFile('%s/VBoxSVC.pid' % (self.sScratchPath,));
2006 return fRc1 is True and fRc2 is True;
2007
2008 def onExit(self, iRc):
2009 """
2010 Stop VBoxSVC if we've started it.
2011 """
2012 if self.oVBoxSvcProcess is not None:
2013 reporter.log('*** Shutting down the VBox API... (iRc=%s)' % (iRc,));
2014 self._powerOffAllVms();
2015 self._teardownVBoxApi();
2016 self._stopVBoxSVC();
2017 reporter.log('*** VBox API shutdown done.');
2018 return base.TestDriver.onExit(self, iRc);
2019
2020
2021 #
2022 # Task wait method override.
2023 #
2024
2025 def notifyAboutReadyTask(self, oTask):
2026 """
2027 Overriding base.TestDriver.notifyAboutReadyTask.
2028 """
2029 try:
2030 self.oVBoxMgr.interruptWaitEvents();
2031 reporter.log2('vbox.notifyAboutReadyTask: called interruptWaitEvents');
2032 except:
2033 reporter.logXcpt('vbox.notifyAboutReadyTask');
2034 return base.TestDriver.notifyAboutReadyTask(self, oTask);
2035
2036 def waitForTasksSleepWorker(self, cMsTimeout):
2037 """
2038 Overriding base.TestDriver.waitForTasksSleepWorker.
2039 """
2040 try:
2041 rc = self.oVBoxMgr.waitForEvents(int(cMsTimeout));
2042 _ = rc; #reporter.log2('vbox.waitForTasksSleepWorker(%u): true (waitForEvents -> %s)' % (cMsTimeout, rc));
2043 reporter.doPollWork('vbox.TestDriver.waitForTasksSleepWorker');
2044 return True;
2045 except KeyboardInterrupt:
2046 raise;
2047 except:
2048 reporter.logXcpt('vbox.waitForTasksSleepWorker');
2049 return False;
2050
2051 #
2052 # Utility methods.
2053 #
2054
2055 def processEvents(self, cMsTimeout = 0):
2056 """
2057 Processes events, returning after the first batch has been processed
2058 or the time limit has been reached.
2059
2060 Only Ctrl-C exception, no return.
2061 """
2062 try:
2063 self.oVBoxMgr.waitForEvents(cMsTimeout);
2064 except KeyboardInterrupt:
2065 raise;
2066 except:
2067 pass;
2068 return None;
2069
2070 def processPendingEvents(self):
2071 """ processEvents(0) - no waiting. """
2072 return self.processEvents(0);
2073
2074 def sleep(self, cSecs):
2075 """
2076 Sleep for a specified amount of time, processing XPCOM events all the while.
2077 """
2078 cMsTimeout = long(cSecs * 1000);
2079 msStart = base.timestampMilli();
2080 self.processEvents(0);
2081 while True:
2082 cMsElapsed = base.timestampMilli() - msStart;
2083 if cMsElapsed > cMsTimeout:
2084 break;
2085 #reporter.log2('cMsTimeout=%s - cMsElapsed=%d => %s' % (cMsTimeout, cMsElapsed, cMsTimeout - cMsElapsed));
2086 self.processEvents(cMsTimeout - cMsElapsed);
2087 return None;
2088
2089 def _logVmInfoUnsafe(self, oVM): # pylint: disable=too-many-statements,too-many-branches
2090 """
2091 Internal worker for logVmInfo that is wrapped in try/except.
2092 """
2093 reporter.log(" Name: %s" % (oVM.name,));
2094 reporter.log(" ID: %s" % (oVM.id,));
2095 oOsType = self.oVBox.getGuestOSType(oVM.OSTypeId);
2096 reporter.log(" OS Type: %s - %s" % (oVM.OSTypeId, oOsType.description,));
2097 reporter.log(" Machine state: %s" % (oVM.state,));
2098 reporter.log(" Session state: %s" % (oVM.sessionState,));
2099 if self.fpApiVer >= 4.2:
2100 reporter.log(" Session PID: %u (%#x)" % (oVM.sessionPID, oVM.sessionPID,));
2101 else:
2102 reporter.log(" Session PID: %u (%#x)" % (oVM.sessionPid, oVM.sessionPid,));
2103 if self.fpApiVer >= 5.0:
2104 reporter.log(" Session Name: %s" % (oVM.sessionName,));
2105 else:
2106 reporter.log(" Session Name: %s" % (oVM.sessionType,));
2107 reporter.log(" CPUs: %s" % (oVM.CPUCount,));
2108 reporter.log(" RAM: %sMB" % (oVM.memorySize,));
2109 if self.fpApiVer >= 6.1 and hasattr(oVM, 'graphicsAdapter'):
2110 reporter.log(" VRAM: %sMB" % (oVM.graphicsAdapter.VRAMSize,));
2111 reporter.log(" Monitors: %s" % (oVM.graphicsAdapter.monitorCount,));
2112 reporter.log(" GraphicsController: %s"
2113 % (self.oVBoxMgr.getEnumValueName('GraphicsControllerType', # pylint: disable=not-callable
2114 oVM.graphicsAdapter.graphicsControllerType),));
2115 else:
2116 reporter.log(" VRAM: %sMB" % (oVM.VRAMSize,));
2117 reporter.log(" Monitors: %s" % (oVM.monitorCount,));
2118 reporter.log(" GraphicsController: %s"
2119 % (self.oVBoxMgr.getEnumValueName('GraphicsControllerType', oVM.graphicsControllerType),)); # pylint: disable=not-callable
2120 reporter.log(" Chipset: %s" % (self.oVBoxMgr.getEnumValueName('ChipsetType', oVM.chipsetType),)); # pylint: disable=not-callable
2121 if self.fpApiVer >= 6.2 and hasattr(vboxcon, 'IommuType_None'):
2122 reporter.log(" IOMMU: %s" % (self.oVBoxMgr.getEnumValueName('IommuType', oVM.iommuType),)); # pylint: disable=not-callable
2123 reporter.log(" Firmware: %s" % (self.oVBoxMgr.getEnumValueName('FirmwareType', oVM.firmwareType),)); # pylint: disable=not-callable
2124 reporter.log(" HwVirtEx: %s" % (oVM.getHWVirtExProperty(vboxcon.HWVirtExPropertyType_Enabled),));
2125 reporter.log(" VPID support: %s" % (oVM.getHWVirtExProperty(vboxcon.HWVirtExPropertyType_VPID),));
2126 reporter.log(" Nested paging: %s" % (oVM.getHWVirtExProperty(vboxcon.HWVirtExPropertyType_NestedPaging),));
2127 atTypes = [
2128 ( 'CPUPropertyType_PAE', 'PAE: '),
2129 ( 'CPUPropertyType_LongMode', 'Long-mode: '),
2130 ( 'CPUPropertyType_HWVirt', 'Nested VT-x/AMD-V: '),
2131 ( 'CPUPropertyType_APIC', 'APIC: '),
2132 ( 'CPUPropertyType_X2APIC', 'X2APIC: '),
2133 ( 'CPUPropertyType_TripleFaultReset', 'TripleFaultReset: '),
2134 ( 'CPUPropertyType_IBPBOnVMExit', 'IBPBOnVMExit: '),
2135 ( 'CPUPropertyType_SpecCtrl', 'SpecCtrl: '),
2136 ( 'CPUPropertyType_SpecCtrlByHost', 'SpecCtrlByHost: '),
2137 ];
2138 for sEnumValue, sDesc in atTypes:
2139 if hasattr(vboxcon, sEnumValue):
2140 reporter.log(" %s%s" % (sDesc, oVM.getCPUProperty(getattr(vboxcon, sEnumValue)),));
2141 reporter.log(" ACPI: %s" % (oVM.BIOSSettings.ACPIEnabled,));
2142 reporter.log(" IO-APIC: %s" % (oVM.BIOSSettings.IOAPICEnabled,));
2143 if self.fpApiVer >= 3.2:
2144 if self.fpApiVer >= 4.2:
2145 reporter.log(" HPET: %s" % (oVM.HPETEnabled,));
2146 else:
2147 reporter.log(" HPET: %s" % (oVM.hpetEnabled,));
2148 if self.fpApiVer >= 6.1 and hasattr(oVM, 'graphicsAdapter'):
2149 reporter.log(" 3D acceleration: %s" % (oVM.graphicsAdapter.accelerate3DEnabled,));
2150 reporter.log(" 2D acceleration: %s" % (oVM.graphicsAdapter.accelerate2DVideoEnabled,));
2151 else:
2152 reporter.log(" 3D acceleration: %s" % (oVM.accelerate3DEnabled,));
2153 reporter.log(" 2D acceleration: %s" % (oVM.accelerate2DVideoEnabled,));
2154 reporter.log(" TeleporterEnabled: %s" % (oVM.teleporterEnabled,));
2155 reporter.log(" TeleporterPort: %s" % (oVM.teleporterPort,));
2156 reporter.log(" TeleporterAddress: %s" % (oVM.teleporterAddress,));
2157 reporter.log(" TeleporterPassword: %s" % (oVM.teleporterPassword,));
2158 reporter.log(" Clipboard mode: %s" % (oVM.clipboardMode,));
2159 if self.fpApiVer >= 5.0:
2160 reporter.log(" Drag and drop mode: %s" % (oVM.dnDMode,));
2161 elif self.fpApiVer >= 4.3:
2162 reporter.log(" Drag and drop mode: %s" % (oVM.dragAndDropMode,));
2163 if self.fpApiVer >= 4.0:
2164 reporter.log(" VRDP server: %s" % (oVM.VRDEServer.enabled,));
2165 try: sPorts = oVM.VRDEServer.getVRDEProperty("TCP/Ports");
2166 except: sPorts = "";
2167 reporter.log(" VRDP server ports: %s" % (sPorts,));
2168 reporter.log(" VRDP auth: %s (%s)" % (oVM.VRDEServer.authType, oVM.VRDEServer.authLibrary,));
2169 else:
2170 reporter.log(" VRDP server: %s" % (oVM.VRDPServer.enabled,));
2171 reporter.log(" VRDP server ports: %s" % (oVM.VRDPServer.ports,));
2172 reporter.log(" Last changed: %s" % (oVM.lastStateChange,));
2173
2174 aoControllers = self.oVBoxMgr.getArray(oVM, 'storageControllers')
2175 if aoControllers:
2176 reporter.log(" Controllers:");
2177 for oCtrl in aoControllers:
2178 reporter.log(" %s %s bus: %s type: %s" % (oCtrl.name, oCtrl.controllerType, oCtrl.bus, oCtrl.controllerType,));
2179 reporter.log(" AudioController: %s"
2180 % (self.oVBoxMgr.getEnumValueName('AudioControllerType', oVM.audioAdapter.audioController),)); # pylint: disable=not-callable
2181 reporter.log(" AudioEnabled: %s" % (oVM.audioAdapter.enabled,));
2182 reporter.log(" Host AudioDriver: %s"
2183 % (self.oVBoxMgr.getEnumValueName('AudioDriverType', oVM.audioAdapter.audioDriver),)); # pylint: disable=not-callable
2184
2185 self.processPendingEvents();
2186 aoAttachments = self.oVBoxMgr.getArray(oVM, 'mediumAttachments')
2187 if aoAttachments:
2188 reporter.log(" Attachments:");
2189 for oAtt in aoAttachments:
2190 sCtrl = "Controller: %s port: %s device: %s type: %s" % (oAtt.controller, oAtt.port, oAtt.device, oAtt.type);
2191 oMedium = oAtt.medium
2192 if oAtt.type == vboxcon.DeviceType_HardDisk:
2193 reporter.log(" %s: HDD" % sCtrl);
2194 reporter.log(" Id: %s" % (oMedium.id,));
2195 reporter.log(" Name: %s" % (oMedium.name,));
2196 reporter.log(" Format: %s" % (oMedium.format,));
2197 reporter.log(" Location: %s" % (oMedium.location,));
2198
2199 if oAtt.type == vboxcon.DeviceType_DVD:
2200 reporter.log(" %s: DVD" % sCtrl);
2201 if oMedium:
2202 reporter.log(" Id: %s" % (oMedium.id,));
2203 reporter.log(" Name: %s" % (oMedium.name,));
2204 if oMedium.hostDrive:
2205 reporter.log(" Host DVD %s" % (oMedium.location,));
2206 if oAtt.passthrough:
2207 reporter.log(" [passthrough mode]");
2208 else:
2209 reporter.log(" Virtual image: %s" % (oMedium.location,));
2210 reporter.log(" Size: %s" % (oMedium.size,));
2211 else:
2212 reporter.log(" empty");
2213
2214 if oAtt.type == vboxcon.DeviceType_Floppy:
2215 reporter.log(" %s: Floppy" % sCtrl);
2216 if oMedium:
2217 reporter.log(" Id: %s" % (oMedium.id,));
2218 reporter.log(" Name: %s" % (oMedium.name,));
2219 if oMedium.hostDrive:
2220 reporter.log(" Host floppy: %s" % (oMedium.location,));
2221 else:
2222 reporter.log(" Virtual image: %s" % (oMedium.location,));
2223 reporter.log(" Size: %s" % (oMedium.size,));
2224 else:
2225 reporter.log(" empty");
2226 self.processPendingEvents();
2227
2228 reporter.log(" Network Adapter:");
2229 for iSlot in range(0, 32):
2230 try: oNic = oVM.getNetworkAdapter(iSlot)
2231 except: break;
2232 if not oNic.enabled:
2233 reporter.log2(" slot #%d found but not enabled, skipping" % (iSlot,));
2234 continue;
2235 reporter.log(" slot #%d: type: %s (%s) MAC Address: %s lineSpeed: %s"
2236 % (iSlot, self.oVBoxMgr.getEnumValueName('NetworkAdapterType', oNic.adapterType), # pylint: disable=not-callable
2237 oNic.adapterType, oNic.MACAddress, oNic.lineSpeed) );
2238
2239 if oNic.attachmentType == vboxcon.NetworkAttachmentType_NAT:
2240 reporter.log(" attachmentType: NAT (%s)" % (oNic.attachmentType,));
2241 if self.fpApiVer >= 4.1:
2242 reporter.log(" nat-network: %s" % (oNic.NATNetwork,));
2243 if self.fpApiVer >= 7.0 and hasattr(oNic.NATEngine, 'localhostReachable'):
2244 reporter.log(" localhostReachable: %s" % (oNic.NATEngine.localhostReachable,));
2245
2246 elif oNic.attachmentType == vboxcon.NetworkAttachmentType_Bridged:
2247 reporter.log(" attachmentType: Bridged (%s)" % (oNic.attachmentType,));
2248 if self.fpApiVer >= 4.1:
2249 reporter.log(" hostInterface: %s" % (oNic.bridgedInterface,));
2250 else:
2251 reporter.log(" hostInterface: %s" % (oNic.hostInterface,));
2252 elif oNic.attachmentType == vboxcon.NetworkAttachmentType_Internal:
2253 reporter.log(" attachmentType: Internal (%s)" % (oNic.attachmentType,));
2254 reporter.log(" intnet-name: %s" % (oNic.internalNetwork,));
2255 elif oNic.attachmentType == vboxcon.NetworkAttachmentType_HostOnly:
2256 reporter.log(" attachmentType: HostOnly (%s)" % (oNic.attachmentType,));
2257 if self.fpApiVer >= 4.1:
2258 reporter.log(" hostInterface: %s" % (oNic.hostOnlyInterface,));
2259 else:
2260 reporter.log(" hostInterface: %s" % (oNic.hostInterface,));
2261 else:
2262 if self.fpApiVer >= 7.0:
2263 if oNic.attachmentType == vboxcon.NetworkAttachmentType_HostOnlyNetwork:
2264 reporter.log(" attachmentType: HostOnlyNetwork (%s)" % (oNic.attachmentType,));
2265 reporter.log(" hostonly-net: %s" % (oNic.hostOnlyNetwork,));
2266 elif self.fpApiVer >= 4.1:
2267 if oNic.attachmentType == vboxcon.NetworkAttachmentType_Generic:
2268 reporter.log(" attachmentType: Generic (%s)" % (oNic.attachmentType,));
2269 reporter.log(" generic-driver: %s" % (oNic.GenericDriver,));
2270 else:
2271 reporter.log(" attachmentType: unknown-%s" % (oNic.attachmentType,));
2272 else:
2273 reporter.log(" attachmentType: unknown-%s" % (oNic.attachmentType,));
2274 if oNic.traceEnabled:
2275 reporter.log(" traceFile: %s" % (oNic.traceFile,));
2276 self.processPendingEvents();
2277
2278 reporter.log(" Serial ports:");
2279 for iSlot in range(0, 8):
2280 try: oPort = oVM.getSerialPort(iSlot)
2281 except: break;
2282 if oPort is not None and oPort.enabled:
2283 enmHostMode = oPort.hostMode;
2284 reporter.log(" slot #%d: hostMode: %s (%s) I/O port: %s IRQ: %s server: %s path: %s" %
2285 (iSlot, self.oVBoxMgr.getEnumValueName('PortMode', enmHostMode), # pylint: disable=not-callable
2286 enmHostMode, oPort.IOBase, oPort.IRQ, oPort.server, oPort.path,) );
2287 self.processPendingEvents();
2288
2289 return True;
2290
2291 def logVmInfo(self, oVM): # pylint: disable=too-many-statements,too-many-branches
2292 """
2293 Logs VM configuration details.
2294
2295 This is copy, past, search, replace and edit of infoCmd from vboxshell.py.
2296 """
2297 try:
2298 fRc = self._logVmInfoUnsafe(oVM);
2299 except:
2300 reporter.logXcpt();
2301 fRc = False;
2302 return fRc;
2303
2304 def logVmInfoByName(self, sName):
2305 """
2306 logVmInfo + getVmByName.
2307 """
2308 return self.logVmInfo(self.getVmByName(sName));
2309
2310 def tryFindGuestOsId(self, sIdOrDesc):
2311 """
2312 Takes a guest OS ID or Description and returns the ID.
2313 If nothing matching it is found, the input is returned unmodified.
2314 """
2315
2316 if self.fpApiVer >= 4.0:
2317 if sIdOrDesc == 'Solaris (64 bit)':
2318 sIdOrDesc = 'Oracle Solaris 10 5/09 and earlier (64 bit)';
2319
2320 try:
2321 aoGuestTypes = self.oVBoxMgr.getArray(self.oVBox, 'GuestOSTypes');
2322 except:
2323 reporter.logXcpt();
2324 else:
2325 for oGuestOS in aoGuestTypes:
2326 try:
2327 sId = oGuestOS.id;
2328 sDesc = oGuestOS.description;
2329 except:
2330 reporter.logXcpt();
2331 else:
2332 if sIdOrDesc in (sId, sDesc,):
2333 sIdOrDesc = sId;
2334 break;
2335 self.processPendingEvents();
2336 return sIdOrDesc
2337
2338 def resourceFindVmHd(self, sVmName, sFlavor):
2339 """
2340 Search the test resources for the most recent VM HD.
2341
2342 Returns path relative to the test resource root.
2343 """
2344 ## @todo implement a proper search algo here.
2345 return '4.2/' + sFlavor + '/' + sVmName + '/t-' + sVmName + '.vdi';
2346
2347
2348 #
2349 # VM Api wrappers that logs errors, hides exceptions and other details.
2350 #
2351
2352 def createTestVMOnly(self, sName, sKind):
2353 """
2354 Creates and register a test VM without doing any kind of configuration.
2355
2356 Returns VM object (IMachine) on success, None on failure.
2357 """
2358 if not self.importVBoxApi():
2359 return None;
2360
2361 # create + register the VM
2362 try:
2363 if self.fpApiVer >= 4.2: # Introduces grouping (third parameter, empty for now).
2364 oVM = self.oVBox.createMachine("", sName, [], self.tryFindGuestOsId(sKind), "");
2365 elif self.fpApiVer >= 4.0:
2366 oVM = self.oVBox.createMachine("", sName, self.tryFindGuestOsId(sKind), "", False);
2367 elif self.fpApiVer >= 3.2:
2368 oVM = self.oVBox.createMachine(sName, self.tryFindGuestOsId(sKind), "", "", False);
2369 else:
2370 oVM = self.oVBox.createMachine(sName, self.tryFindGuestOsId(sKind), "", "");
2371 try:
2372 oVM.saveSettings();
2373 try:
2374 self.oVBox.registerMachine(oVM);
2375 return oVM;
2376 except:
2377 reporter.logXcpt();
2378 raise;
2379 except:
2380 reporter.logXcpt();
2381 if self.fpApiVer >= 4.0:
2382 try:
2383 if self.fpApiVer >= 4.3:
2384 oProgress = oVM.deleteConfig([]);
2385 else:
2386 oProgress = oVM.delete(None);
2387 self.waitOnProgress(oProgress);
2388 except:
2389 reporter.logXcpt();
2390 else:
2391 try: oVM.deleteSettings();
2392 except: reporter.logXcpt();
2393 raise;
2394 except:
2395 reporter.errorXcpt('failed to create vm "%s"' % (sName));
2396 return None;
2397
2398 # pylint: disable=too-many-arguments,too-many-locals,too-many-statements
2399 def createTestVM(self,
2400 sName,
2401 iGroup,
2402 sHd = None,
2403 cMbRam = None,
2404 cCpus = 1,
2405 fVirtEx = None,
2406 fNestedPaging = None,
2407 sDvdImage = None,
2408 sKind = "Other",
2409 fIoApic = None,
2410 fNstHwVirt = None,
2411 fPae = None,
2412 fFastBootLogo = True,
2413 eNic0Type = None,
2414 eNic0AttachType = None,
2415 sNic0NetName = 'default',
2416 sNic0MacAddr = 'grouped',
2417 sFloppy = None,
2418 fNatForwardingForTxs = None,
2419 sHddControllerType = 'IDE Controller',
2420 fVmmDevTestingPart = None,
2421 fVmmDevTestingMmio = False,
2422 sFirmwareType = 'bios',
2423 sChipsetType = 'piix3',
2424 sIommuType = 'none',
2425 sDvdControllerType = 'IDE Controller',
2426 sCom1RawFile = None):
2427 """
2428 Creates a test VM with a immutable HD from the test resources.
2429 """
2430 # create + register the VM
2431 oVM = self.createTestVMOnly(sName, sKind);
2432 if not oVM:
2433 return None;
2434
2435 # Configure the VM.
2436 fRc = True;
2437 oSession = self.openSession(oVM);
2438 if oSession is not None:
2439 fRc = oSession.setupPreferredConfig();
2440
2441 if fRc and cMbRam is not None :
2442 fRc = oSession.setRamSize(cMbRam);
2443 if fRc and cCpus is not None:
2444 fRc = oSession.setCpuCount(cCpus);
2445 if fRc and fVirtEx is not None:
2446 fRc = oSession.enableVirtEx(fVirtEx);
2447 if fRc and fNestedPaging is not None:
2448 fRc = oSession.enableNestedPaging(fNestedPaging);
2449 if fRc and fIoApic is not None:
2450 fRc = oSession.enableIoApic(fIoApic);
2451 if fRc and fNstHwVirt is not None:
2452 fRc = oSession.enableNestedHwVirt(fNstHwVirt);
2453 if fRc and fPae is not None:
2454 fRc = oSession.enablePae(fPae);
2455 if fRc and sDvdImage is not None:
2456 fRc = oSession.attachDvd(sDvdImage, sDvdControllerType);
2457 if fRc and sHd is not None:
2458 fRc = oSession.attachHd(sHd, sHddControllerType);
2459 if fRc and sFloppy is not None:
2460 fRc = oSession.attachFloppy(sFloppy);
2461 if fRc and eNic0Type is not None:
2462 fRc = oSession.setNicType(eNic0Type, 0);
2463 if fRc and (eNic0AttachType is not None or (sNic0NetName is not None and sNic0NetName != 'default')):
2464 fRc = oSession.setNicAttachment(eNic0AttachType, sNic0NetName, 0);
2465 if fRc and sNic0MacAddr is not None:
2466 if sNic0MacAddr == 'grouped':
2467 sNic0MacAddr = '%02X' % (iGroup);
2468 fRc = oSession.setNicMacAddress(sNic0MacAddr, 0);
2469 # Needed to reach the host (localhost) from the guest. See xTracker #9896.
2470 if fRc and self.fpApiVer >= 7.0:
2471 fRc = oSession.setNicLocalhostReachable(True, 0);
2472 if fRc and fNatForwardingForTxs is True:
2473 fRc = oSession.setupNatForwardingForTxs();
2474 if fRc and fFastBootLogo is not None:
2475 fRc = oSession.setupBootLogo(fFastBootLogo);
2476 if fRc and self.fEnableVrdp:
2477 fRc = oSession.setupVrdp(True, self.uVrdpBasePort + iGroup);
2478 if fRc and fVmmDevTestingPart is not None:
2479 fRc = oSession.enableVmmDevTestingPart(fVmmDevTestingPart, fVmmDevTestingMmio);
2480 if fRc and sFirmwareType == 'bios':
2481 fRc = oSession.setFirmwareType(vboxcon.FirmwareType_BIOS);
2482 elif fRc and sFirmwareType == 'efi':
2483 fRc = oSession.setFirmwareType(vboxcon.FirmwareType_EFI);
2484 if fRc and self.fEnableDebugger:
2485 fRc = oSession.setExtraData('VBoxInternal/DBGC/Enabled', '1');
2486 if fRc and sChipsetType == 'piix3':
2487 fRc = oSession.setChipsetType(vboxcon.ChipsetType_PIIX3);
2488 elif fRc and sChipsetType == 'ich9':
2489 fRc = oSession.setChipsetType(vboxcon.ChipsetType_ICH9);
2490 if fRc and sCom1RawFile:
2491 fRc = oSession.setupSerialToRawFile(0, sCom1RawFile);
2492 if fRc and self.fpApiVer >= 6.2 and hasattr(vboxcon, 'IommuType_AMD') and sIommuType == 'amd':
2493 fRc = oSession.setIommuType(vboxcon.IommuType_AMD);
2494 elif fRc and self.fpApiVer >= 6.2 and hasattr(vboxcon, 'IommuType_Intel') and sIommuType == 'intel':
2495 fRc = oSession.setIommuType(vboxcon.IommuType_Intel);
2496
2497 if fRc: fRc = oSession.saveSettings();
2498 if not fRc: oSession.discardSettings(True);
2499 oSession.close();
2500 if not fRc:
2501 if self.fpApiVer >= 4.0:
2502 try: oVM.unregister(vboxcon.CleanupMode_Full);
2503 except: reporter.logXcpt();
2504 try:
2505 if self.fpApiVer >= 4.3:
2506 oProgress = oVM.deleteConfig([]);
2507 else:
2508 oProgress = oVM.delete([]);
2509 self.waitOnProgress(oProgress);
2510 except:
2511 reporter.logXcpt();
2512 else:
2513 try: self.oVBox.unregisterMachine(oVM.id);
2514 except: reporter.logXcpt();
2515 try: oVM.deleteSettings();
2516 except: reporter.logXcpt();
2517 return None;
2518
2519 # success.
2520 reporter.log('created "%s" with name "%s"' % (oVM.id, sName));
2521 self.aoVMs.append(oVM);
2522 self.logVmInfo(oVM); # testing...
2523 return oVM;
2524 # pylint: enable=too-many-arguments,too-many-locals,too-many-statements
2525
2526 def createTestVmWithDefaults(self, # pylint: disable=too-many-arguments
2527 sName,
2528 iGroup,
2529 sKind,
2530 sDvdImage = None,
2531 fFastBootLogo = True,
2532 eNic0AttachType = None,
2533 sNic0NetName = 'default',
2534 sNic0MacAddr = 'grouped',
2535 fVmmDevTestingPart = None,
2536 fVmmDevTestingMmio = False,
2537 sCom1RawFile = None):
2538 """
2539 Creates a test VM with all defaults and no HDs.
2540 """
2541 # create + register the VM
2542 oVM = self.createTestVMOnly(sName, sKind);
2543 if oVM is not None:
2544 # Configure the VM with defaults according to sKind.
2545 fRc = True;
2546 oSession = self.openSession(oVM);
2547 if oSession is not None:
2548 if self.fpApiVer >= 6.0:
2549 try:
2550 oSession.o.machine.applyDefaults('');
2551 except:
2552 reporter.errorXcpt('failed to apply defaults to vm "%s"' % (sName,));
2553 fRc = False;
2554 else:
2555 reporter.error("Implement applyDefaults for vbox version %s" % (self.fpApiVer,));
2556 #fRc = oSession.setupPreferredConfig();
2557 fRc = False;
2558
2559 # Apply the specified configuration:
2560 if fRc and sDvdImage is not None:
2561 #fRc = oSession.insertDvd(sDvdImage); # attachDvd
2562 reporter.error('Implement: oSession.insertDvd(%s)' % (sDvdImage,));
2563 fRc = False;
2564
2565 if fRc and fFastBootLogo is not None:
2566 fRc = oSession.setupBootLogo(fFastBootLogo);
2567
2568 if fRc and (eNic0AttachType is not None or (sNic0NetName is not None and sNic0NetName != 'default')):
2569 fRc = oSession.setNicAttachment(eNic0AttachType, sNic0NetName, 0);
2570 if fRc and sNic0MacAddr is not None:
2571 if sNic0MacAddr == 'grouped':
2572 sNic0MacAddr = '%02X' % (iGroup,);
2573 fRc = oSession.setNicMacAddress(sNic0MacAddr, 0);
2574 # Needed to reach the host (localhost) from the guest. See xTracker #9896.
2575 if fRc and self.fpApiVer >= 7.0:
2576 fRc = oSession.setNicLocalhostReachable(True, 0);
2577
2578 if fRc and self.fEnableVrdp:
2579 fRc = oSession.setupVrdp(True, self.uVrdpBasePort + iGroup);
2580
2581 if fRc and fVmmDevTestingPart is not None:
2582 fRc = oSession.enableVmmDevTestingPart(fVmmDevTestingPart, fVmmDevTestingMmio);
2583
2584 if fRc and sCom1RawFile:
2585 fRc = oSession.setupSerialToRawFile(0, sCom1RawFile);
2586
2587 # Save the settings if we were successfull, otherwise discard them.
2588 if fRc:
2589 fRc = oSession.saveSettings();
2590 if not fRc:
2591 oSession.discardSettings(True);
2592 oSession.close();
2593
2594 if fRc is True:
2595 # If we've been successful, add the VM to the list and return it.
2596 # success.
2597 reporter.log('created "%s" with name "%s"' % (oVM.id, sName, ));
2598 self.aoVMs.append(oVM);
2599 self.logVmInfo(oVM); # testing...
2600 return oVM;
2601
2602 # Failed. Unregister the machine and delete it.
2603 if self.fpApiVer >= 4.0:
2604 try: oVM.unregister(vboxcon.CleanupMode_Full);
2605 except: reporter.logXcpt();
2606 try:
2607 if self.fpApiVer >= 4.3:
2608 oProgress = oVM.deleteConfig([]);
2609 else:
2610 oProgress = oVM.delete([]);
2611 self.waitOnProgress(oProgress);
2612 except:
2613 reporter.logXcpt();
2614 else:
2615 try: self.oVBox.unregisterMachine(oVM.id);
2616 except: reporter.logXcpt();
2617 try: oVM.deleteSettings();
2618 except: reporter.logXcpt();
2619 return None;
2620
2621 def addTestMachine(self, sNameOrId, fQuiet = False):
2622 """
2623 Adds an already existing (that is, configured) test VM to the
2624 test VM list.
2625
2626 Returns the VM object on success, None if failed.
2627 """
2628 # find + add the VM to the list.
2629 oVM = None;
2630 try:
2631 if self.fpApiVer >= 4.0:
2632 oVM = self.oVBox.findMachine(sNameOrId);
2633 else:
2634 reporter.error('fpApiVer=%s - did you remember to initialize the API' % (self.fpApiVer,));
2635 except:
2636 reporter.errorXcpt('could not find vm "%s"' % (sNameOrId,));
2637
2638 if oVM:
2639 self.aoVMs.append(oVM);
2640 if not fQuiet:
2641 reporter.log('Added "%s" with name "%s"' % (oVM.id, sNameOrId));
2642 self.logVmInfo(oVM);
2643 return oVM;
2644
2645 def forgetTestMachine(self, oVM, fQuiet = False):
2646 """
2647 Forget about an already known test VM in the test VM list.
2648
2649 Returns True on success, False if failed.
2650 """
2651 try:
2652 sUuid = oVM.id;
2653 sName = oVM.name;
2654 except:
2655 reporter.errorXcpt('failed to get the UUID for VM "%s"' % (oVM,));
2656 return False;
2657 try:
2658 self.aoVMs.remove(oVM);
2659 if not fQuiet:
2660 reporter.log('Removed "%s" with name "%s"' % (sUuid, sName));
2661 except:
2662 reporter.errorXcpt('could not find vm "%s"' % (sName,));
2663 return False;
2664 return True;
2665
2666 def openSession(self, oVM):
2667 """
2668 Opens a session for the VM. Returns the a Session wrapper object that
2669 will automatically close the session when the wrapper goes out of scope.
2670
2671 On failure None is returned and an error is logged.
2672 """
2673 try:
2674 sUuid = oVM.id;
2675 except:
2676 reporter.errorXcpt('failed to get the UUID for VM "%s"' % (oVM,));
2677 return None;
2678
2679 # This loop is a kludge to deal with us racing the closing of the
2680 # direct session of a previous VM run. See waitOnDirectSessionClose.
2681 for i in range(10):
2682 try:
2683 if self.fpApiVer <= 3.2:
2684 oSession = self.oVBoxMgr.openMachineSession(sUuid);
2685 else:
2686 oSession = self.oVBoxMgr.openMachineSession(oVM);
2687 break;
2688 except:
2689 if i == 9:
2690 reporter.errorXcpt('failed to open session for "%s" ("%s")' % (sUuid, oVM));
2691 return None;
2692 if i > 0:
2693 reporter.logXcpt('warning: failed to open session for "%s" ("%s") - retrying in %u secs' % (sUuid, oVM, i));
2694 self.waitOnDirectSessionClose(oVM, 5000 + i * 1000);
2695 from testdriver.vboxwrappers import SessionWrapper;
2696 return SessionWrapper(oSession, oVM, self.oVBox, self.oVBoxMgr, self, False);
2697
2698 #
2699 # Guest locations.
2700 #
2701
2702 @staticmethod
2703 def getGuestTempDir(oTestVm):
2704 """
2705 Helper for finding a temporary directory in the test VM.
2706
2707 Note! It may be necessary to create it!
2708 """
2709 if oTestVm.isWindows():
2710 return "C:\\Temp";
2711 if oTestVm.isOS2():
2712 return "C:\\Temp";
2713 return '/var/tmp';
2714
2715 @staticmethod
2716 def getGuestSystemDir(oTestVm, sPathPrefix = ''):
2717 """
2718 Helper for finding a system directory in the test VM that we can play around with.
2719 sPathPrefix can be used to specify other directories, such as /usr/local/bin/ or /usr/bin, for instance.
2720
2721 On Windows this is always the System32 directory, so this function can be used as
2722 basis for locating other files in or under that directory.
2723 """
2724 if oTestVm.isWindows():
2725 return oTestVm.pathJoin(TestDriver.getGuestWinDir(oTestVm), 'System32');
2726 if oTestVm.isOS2():
2727 return 'C:\\OS2\\DLL';
2728
2729 # OL / RHEL symlinks "/bin"/ to "/usr/bin". To avoid (unexpectedly) following symlinks, use "/usr/bin" then instead.
2730 if not sPathPrefix \
2731 and oTestVm.sKind in ('Oracle_64', 'Oracle'): ## @todo Does this apply for "RedHat" as well?
2732 return "/usr/bin";
2733
2734 return sPathPrefix + "/bin";
2735
2736 @staticmethod
2737 def getGuestSystemAdminDir(oTestVm, sPathPrefix = ''):
2738 """
2739 Helper for finding a system admin directory ("sbin") in the test VM that we can play around with.
2740 sPathPrefix can be used to specify other directories, such as /usr/local/sbin/ or /usr/sbin, for instance.
2741
2742 On Windows this is always the System32 directory, so this function can be used as
2743 basis for locating other files in or under that directory.
2744 On UNIX-y systems this always is the "sh" shell to guarantee a common shell syntax.
2745 """
2746 if oTestVm.isWindows():
2747 return oTestVm.pathJoin(TestDriver.getGuestWinDir(oTestVm), 'System32');
2748 if oTestVm.isOS2():
2749 return 'C:\\OS2\\DLL'; ## @todo r=andy Not sure here.
2750
2751 # OL / RHEL symlinks "/sbin"/ to "/usr/sbin". To avoid (unexpectedly) following symlinks, use "/usr/sbin" then instead.
2752 if not sPathPrefix \
2753 and oTestVm.sKind in ('Oracle_64', 'Oracle'): ## @todo Does this apply for "RedHat" as well?
2754 return "/usr/sbin";
2755
2756 return sPathPrefix + "/sbin";
2757
2758 @staticmethod
2759 def getGuestWinDir(oTestVm):
2760 """
2761 Helper for finding the Windows directory in the test VM that we can play around with.
2762 ASSUMES that we always install Windows on drive C.
2763
2764 Returns the Windows directory, or an empty string when executed on a non-Windows guest (asserts).
2765 """
2766 sWinDir = '';
2767 if oTestVm.isWindows():
2768 if oTestVm.sKind in ['WindowsNT4', 'WindowsNT3x',]:
2769 sWinDir = 'C:\\WinNT\\';
2770 else:
2771 sWinDir = 'C:\\Windows\\';
2772 assert sWinDir != '', 'Retrieving Windows directory for non-Windows OS';
2773 return sWinDir;
2774
2775 @staticmethod
2776 def getGuestSystemShell(oTestVm):
2777 """
2778 Helper for finding the default system shell in the test VM.
2779 """
2780 if oTestVm.isWindows():
2781 return TestDriver.getGuestSystemDir(oTestVm) + '\\cmd.exe';
2782 if oTestVm.isOS2():
2783 return TestDriver.getGuestSystemDir(oTestVm) + '\\..\\CMD.EXE';
2784 return "/bin/sh";
2785
2786 @staticmethod
2787 def getGuestSystemFileForReading(oTestVm):
2788 """
2789 Helper for finding a file in the test VM that we can read.
2790 """
2791 if oTestVm.isWindows():
2792 return TestDriver.getGuestSystemDir(oTestVm) + '\\ntdll.dll';
2793 if oTestVm.isOS2():
2794 return TestDriver.getGuestSystemDir(oTestVm) + '\\DOSCALL1.DLL';
2795 return "/bin/sh";
2796
2797 def getVmByName(self, sName):
2798 """
2799 Get a test VM by name. Returns None if not found, logged.
2800 """
2801 # Look it up in our 'cache'.
2802 for oVM in self.aoVMs:
2803 try:
2804 #reporter.log2('cur: %s / %s (oVM=%s)' % (oVM.name, oVM.id, oVM));
2805 if oVM.name == sName:
2806 return oVM;
2807 except:
2808 reporter.errorXcpt('failed to get the name from the VM "%s"' % (oVM));
2809
2810 # Look it up the standard way.
2811 return self.addTestMachine(sName, fQuiet = True);
2812
2813 def getVmByUuid(self, sUuid):
2814 """
2815 Get a test VM by uuid. Returns None if not found, logged.
2816 """
2817 # Look it up in our 'cache'.
2818 for oVM in self.aoVMs:
2819 try:
2820 if oVM.id == sUuid:
2821 return oVM;
2822 except:
2823 reporter.errorXcpt('failed to get the UUID from the VM "%s"' % (oVM));
2824
2825 # Look it up the standard way.
2826 return self.addTestMachine(sUuid, fQuiet = True);
2827
2828 def waitOnProgress(self, oProgress, cMsTimeout = 1000000, fErrorOnTimeout = True, cMsInterval = 1000):
2829 """
2830 Waits for a progress object to complete. Returns the status code.
2831 """
2832 # Wait for progress no longer than cMsTimeout time period.
2833 tsStart = datetime.datetime.now()
2834 while True:
2835 self.processPendingEvents();
2836 try:
2837 if oProgress.completed:
2838 break;
2839 except:
2840 return -1;
2841 self.processPendingEvents();
2842
2843 tsNow = datetime.datetime.now()
2844 tsDelta = tsNow - tsStart
2845 if ((tsDelta.microseconds + tsDelta.seconds * 1000000) // 1000) > cMsTimeout:
2846 if fErrorOnTimeout:
2847 reporter.errorTimeout('Timeout while waiting for progress.')
2848 return -1
2849
2850 reporter.doPollWork('vbox.TestDriver.waitOnProgress');
2851 try: oProgress.waitForCompletion(cMsInterval);
2852 except: return -2;
2853
2854 try: rc = oProgress.resultCode;
2855 except: rc = -2;
2856 self.processPendingEvents();
2857 return rc;
2858
2859 def waitOnDirectSessionClose(self, oVM, cMsTimeout):
2860 """
2861 Waits for the VM process to close it's current direct session.
2862
2863 Returns None.
2864 """
2865 # Get the original values so we're not subject to
2866 try:
2867 eCurState = oVM.sessionState;
2868 if self.fpApiVer >= 5.0:
2869 sCurName = sOrgName = oVM.sessionName;
2870 else:
2871 sCurName = sOrgName = oVM.sessionType;
2872 if self.fpApiVer >= 4.2:
2873 iCurPid = iOrgPid = oVM.sessionPID;
2874 else:
2875 iCurPid = iOrgPid = oVM.sessionPid;
2876 except Exception as oXcpt:
2877 if ComError.notEqual(oXcpt, ComError.E_ACCESSDENIED):
2878 reporter.logXcpt();
2879 self.processPendingEvents();
2880 return None;
2881 self.processPendingEvents();
2882
2883 msStart = base.timestampMilli();
2884 while iCurPid == iOrgPid \
2885 and sCurName == sOrgName \
2886 and sCurName != '' \
2887 and base.timestampMilli() - msStart < cMsTimeout \
2888 and eCurState in (vboxcon.SessionState_Unlocking, vboxcon.SessionState_Spawning, vboxcon.SessionState_Locked,):
2889 self.processEvents(1000);
2890 try:
2891 eCurState = oVM.sessionState;
2892 sCurName = oVM.sessionName if self.fpApiVer >= 5.0 else oVM.sessionType;
2893 iCurPid = oVM.sessionPID if self.fpApiVer >= 4.2 else oVM.sessionPid;
2894 except Exception as oXcpt:
2895 if ComError.notEqual(oXcpt, ComError.E_ACCESSDENIED):
2896 reporter.logXcpt();
2897 break;
2898 self.processPendingEvents();
2899 self.processPendingEvents();
2900 return None;
2901
2902 def uploadStartupLogFile(self, oVM, sVmName):
2903 """
2904 Uploads the VBoxStartup.log when present.
2905 """
2906 fRc = True;
2907 try:
2908 sLogFile = os.path.join(oVM.logFolder, 'VBoxHardening.log');
2909 except:
2910 reporter.logXcpt();
2911 fRc = False;
2912 else:
2913 if os.path.isfile(sLogFile):
2914 reporter.addLogFile(sLogFile, 'log/release/vm', '%s hardening log' % (sVmName, ),
2915 sAltName = '%s-%s' % (sVmName, os.path.basename(sLogFile),));
2916 return fRc;
2917
2918 def annotateAndUploadProcessReport(self, sProcessReport, sFilename, sKind, sDesc):
2919 """
2920 Annotates the given VM process report and uploads it if successfull.
2921 """
2922 fRc = False;
2923 if self.oBuild is not None and self.oBuild.sInstallPath is not None:
2924 oResolver = btresolver.BacktraceResolver(self.sScratchPath, self.oBuild.sInstallPath,
2925 self.getBuildOs(), self.getBuildArch(),
2926 fnLog = reporter.log);
2927 fRcTmp = oResolver.prepareEnv();
2928 if fRcTmp:
2929 reporter.log('Successfully prepared environment');
2930 sReportDbgSym = oResolver.annotateReport(sProcessReport);
2931 if sReportDbgSym and len(sReportDbgSym) > 8:
2932 reporter.addLogString(sReportDbgSym, sFilename, sKind, sDesc);
2933 fRc = True;
2934 else:
2935 reporter.log('Annotating report failed');
2936 oResolver.cleanupEnv();
2937 return fRc;
2938
2939 def startVmEx(self, oVM, fWait = True, sType = None, sName = None, asEnv = None): # pylint: disable=too-many-locals,too-many-statements
2940 """
2941 Start the VM, returning the VM session and progress object on success.
2942 The session is also added to the task list and to the aoRemoteSessions set.
2943
2944 asEnv is a list of string on the putenv() form.
2945
2946 On failure (None, None) is returned and an error is logged.
2947 """
2948 # Massage and check the input.
2949 if sType is None:
2950 sType = self.sSessionType;
2951 if sName is None:
2952 try: sName = oVM.name;
2953 except: sName = 'bad-vm-handle';
2954 reporter.log('startVmEx: sName=%s fWait=%s sType=%s' % (sName, fWait, sType));
2955 if oVM is None:
2956 return (None, None);
2957
2958 ## @todo Do this elsewhere.
2959 # Hack alert. Disables all annoying GUI popups.
2960 if sType == 'gui' and not self.aoRemoteSessions:
2961 try:
2962 self.oVBox.setExtraData('GUI/Input/AutoCapture', 'false');
2963 if self.fpApiVer >= 3.2:
2964 self.oVBox.setExtraData('GUI/LicenseAgreed', '8');
2965 else:
2966 self.oVBox.setExtraData('GUI/LicenseAgreed', '7');
2967 self.oVBox.setExtraData('GUI/RegistrationData', 'triesLeft=0');
2968 self.oVBox.setExtraData('GUI/SUNOnlineData', 'triesLeft=0');
2969 self.oVBox.setExtraData('GUI/SuppressMessages', 'confirmVMReset,remindAboutMouseIntegrationOn,'
2970 'remindAboutMouseIntegrationOff,remindAboutPausedVMInput,confirmInputCapture,'
2971 'confirmGoingFullscreen,remindAboutInaccessibleMedia,remindAboutWrongColorDepth,'
2972 'confirmRemoveMedium,allPopupPanes,allMessageBoxes,all');
2973 self.oVBox.setExtraData('GUI/UpdateDate', 'never');
2974 self.oVBox.setExtraData('GUI/PreventBetaWarning', self.oVBox.version);
2975 except:
2976 reporter.logXcpt();
2977
2978 # The UUID for the name.
2979 try:
2980 sUuid = oVM.id;
2981 except:
2982 reporter.errorXcpt('failed to get the UUID for VM "%s"' % (oVM));
2983 return (None, None);
2984 self.processPendingEvents();
2985
2986 # Construct the environment.
2987 sLogFile = '%s/VM-%s.log' % (self.sScratchPath, sUuid);
2988 try: os.remove(sLogFile);
2989 except: pass;
2990 if self.sLogSessionDest:
2991 sLogDest = self.sLogSessionDest;
2992 else:
2993 sLogDest = 'file=%s' % (sLogFile,);
2994 asEnvFinal = [
2995 'VBOX_LOG=%s' % (self.sLogSessionGroups,),
2996 'VBOX_LOG_FLAGS=%s' % (self.sLogSessionFlags,),
2997 'VBOX_LOG_DEST=nodeny %s' % (sLogDest,),
2998 'VBOX_RELEASE_LOG_FLAGS=append time',
2999 ];
3000 if sType == 'gui':
3001 asEnvFinal.append('VBOX_GUI_DBG_ENABLED=1');
3002 if asEnv is not None and asEnv:
3003 asEnvFinal += asEnv;
3004
3005 # Shortcuts for local testing.
3006 oProgress = oWrapped = None;
3007 oTestVM = self.oTestVmSet.findTestVmByName(sName) if self.oTestVmSet is not None else None;
3008 try:
3009 if oTestVM is not None \
3010 and oTestVM.fSnapshotRestoreCurrent is True:
3011 if oVM.state is vboxcon.MachineState_Running:
3012 reporter.log2('Machine "%s" already running.' % (sName,));
3013 oProgress = None;
3014 oWrapped = self.openSession(oVM);
3015 else:
3016 reporter.log2('Checking if snapshot for machine "%s" exists.' % (sName,));
3017 oSessionWrapperRestore = self.openSession(oVM);
3018 if oSessionWrapperRestore is not None:
3019 oSnapshotCur = oVM.currentSnapshot;
3020 if oSnapshotCur is not None:
3021 reporter.log2('Restoring snapshot for machine "%s".' % (sName,));
3022 oSessionWrapperRestore.restoreSnapshot(oSnapshotCur);
3023 reporter.log2('Current snapshot for machine "%s" restored.' % (sName,));
3024 else:
3025 reporter.log('warning: no current snapshot for machine "%s" found.' % (sName,));
3026 oSessionWrapperRestore.close();
3027 except:
3028 reporter.errorXcpt();
3029 return (None, None);
3030
3031 oSession = None; # Must be initialized, otherwise the log statement at the end of the function can fail.
3032
3033 # Open a remote session, wait for this operation to complete.
3034 # (The loop is a kludge to deal with us racing the closing of the
3035 # direct session of a previous VM run. See waitOnDirectSessionClose.)
3036 if oWrapped is None:
3037 for i in range(10):
3038 try:
3039 if self.fpApiVer < 4.3 \
3040 or (self.fpApiVer == 4.3 and not hasattr(self.oVBoxMgr, 'getSessionObject')):
3041 oSession = self.oVBoxMgr.mgr.getSessionObject(self.oVBox); # pylint: disable=no-member
3042 elif self.fpApiVer < 5.2 \
3043 or (self.fpApiVer == 5.2 and hasattr(self.oVBoxMgr, 'vbox')):
3044 oSession = self.oVBoxMgr.getSessionObject(self.oVBox); # pylint: disable=no-member
3045 else:
3046 oSession = self.oVBoxMgr.getSessionObject(); # pylint: disable=no-member,no-value-for-parameter
3047 if self.fpApiVer < 3.3:
3048 oProgress = self.oVBox.openRemoteSession(oSession, sUuid, sType, '\n'.join(asEnvFinal));
3049 else:
3050 if self.uApiRevision >= self.makeApiRevision(6, 1, 0, 1):
3051 oProgress = oVM.launchVMProcess(oSession, sType, asEnvFinal);
3052 else:
3053 oProgress = oVM.launchVMProcess(oSession, sType, '\n'.join(asEnvFinal));
3054 break;
3055 except:
3056 if i == 9:
3057 reporter.errorXcpt('failed to start VM "%s" ("%s"), aborting.' % (sUuid, sName));
3058 return (None, None);
3059 oSession = None;
3060 if i >= 0:
3061 reporter.logXcpt('warning: failed to start VM "%s" ("%s") - retrying in %u secs.' % (sUuid, oVM, i)); # pylint: disable=line-too-long
3062 self.waitOnDirectSessionClose(oVM, 5000 + i * 1000);
3063 if fWait and oProgress is not None:
3064 rc = self.waitOnProgress(oProgress);
3065 if rc < 0:
3066 self.waitOnDirectSessionClose(oVM, 5000);
3067
3068 # VM failed to power up, still collect VBox.log, need to wrap the session object
3069 # in order to use the helper for adding the log files to the report.
3070 from testdriver.vboxwrappers import SessionWrapper;
3071 oTmp = SessionWrapper(oSession, oVM, self.oVBox, self.oVBoxMgr, self, True, sName, sLogFile);
3072 oTmp.addLogsToReport();
3073
3074 # Try to collect a stack trace of the process for further investigation of any startup hangs.
3075 uPid = oTmp.getPid();
3076 if uPid is not None:
3077 sHostProcessInfoHung = utils.processGetInfo(uPid, fSudo = True);
3078 if sHostProcessInfoHung is not None:
3079 reporter.log('Trying to annotate the hung VM startup process report, please stand by...');
3080 fRcTmp = self.annotateAndUploadProcessReport(sHostProcessInfoHung, 'vmprocess-startup-hung.log',
3081 'process/report/vm', 'Annotated hung VM process state during startup'); # pylint: disable=line-too-long
3082 # Upload the raw log for manual annotation in case resolving failed.
3083 if not fRcTmp:
3084 reporter.log('Failed to annotate hung VM process report, uploading raw report');
3085 reporter.addLogString(sHostProcessInfoHung, 'vmprocess-startup-hung.log', 'process/report/vm',
3086 'Hung VM process state during startup');
3087
3088 try:
3089 if oSession is not None:
3090 oSession.close();
3091 except: pass;
3092 reportError(oProgress, 'failed to open session for "%s"' % (sName));
3093 self.uploadStartupLogFile(oVM, sName);
3094 return (None, None);
3095 reporter.log2('waitOnProgress -> %s' % (rc,));
3096
3097 # Wrap up the session object and push on to the list before returning it.
3098 if oWrapped is None:
3099 from testdriver.vboxwrappers import SessionWrapper;
3100 oWrapped = SessionWrapper(oSession, oVM, self.oVBox, self.oVBoxMgr, self, True, sName, sLogFile);
3101
3102 oWrapped.registerEventHandlerForTask();
3103 self.aoRemoteSessions.append(oWrapped);
3104 if oWrapped is not self.aoRemoteSessions[len(self.aoRemoteSessions) - 1]:
3105 reporter.error('not by reference: oWrapped=%s aoRemoteSessions[%s]=%s'
3106 % (oWrapped, len(self.aoRemoteSessions) - 1,
3107 self.aoRemoteSessions[len(self.aoRemoteSessions) - 1]));
3108 self.addTask(oWrapped);
3109
3110 reporter.log2('startVmEx: oSession=%s, oSessionWrapper=%s, oProgress=%s' % (oSession, oWrapped, oProgress));
3111
3112 from testdriver.vboxwrappers import ProgressWrapper;
3113 return (oWrapped, ProgressWrapper(oProgress, self.oVBoxMgr, self,
3114 'starting %s' % (sName,)) if oProgress else None);
3115
3116 def startVm(self, oVM, sType=None, sName = None, asEnv = None):
3117 """ Simplified version of startVmEx. """
3118 oSession, _ = self.startVmEx(oVM, True, sType, sName, asEnv = asEnv);
3119 return oSession;
3120
3121 def startVmByNameEx(self, sName, fWait=True, sType=None, asEnv = None):
3122 """
3123 Start the VM, returning the VM session and progress object on success.
3124 The session is also added to the task list and to the aoRemoteSessions set.
3125
3126 On failure (None, None) is returned and an error is logged.
3127 """
3128 oVM = self.getVmByName(sName);
3129 if oVM is None:
3130 return (None, None);
3131 return self.startVmEx(oVM, fWait, sType, sName, asEnv = asEnv);
3132
3133 def startVmByName(self, sName, sType=None, asEnv = None):
3134 """
3135 Start the VM, returning the VM session on success. The session is
3136 also added to the task list and to the aoRemoteSessions set.
3137
3138 On failure None is returned and an error is logged.
3139 """
3140 oSession, _ = self.startVmByNameEx(sName, True, sType, asEnv = asEnv);
3141 return oSession;
3142
3143 def terminateVmBySession(self, oSession, oProgress = None, fTakeScreenshot = None): # pylint: disable=too-many-statements
3144 """
3145 Terminates the VM specified by oSession and adds the release logs to
3146 the test report.
3147
3148 This will try achieve this by using powerOff, but will resort to
3149 tougher methods if that fails.
3150
3151 The session will always be removed from the task list.
3152 The session will be closed unless we fail to kill the process.
3153 The session will be removed from the remote session list if closed.
3154
3155 The progress object (a wrapper!) is for teleportation and similar VM
3156 operations, it will be attempted canceled before powering off the VM.
3157 Failures are logged but ignored.
3158 The progress object will always be removed from the task list.
3159
3160 Returns True if powerOff and session close both succeed.
3161 Returns False if on failure (logged), including when we successfully
3162 kill the VM process.
3163 """
3164 reporter.log2('terminateVmBySession: oSession=%s (pid=%s) oProgress=%s' % (oSession.sName, oSession.getPid(), oProgress));
3165
3166 # Call getPid first to make sure the PID is cached in the wrapper.
3167 oSession.getPid();
3168
3169 #
3170 # If the host is out of memory, just skip all the info collection as it
3171 # requires memory too and seems to wedge.
3172 #
3173 sHostProcessInfo = None;
3174 sHostProcessInfoHung = None;
3175 sLastScreenshotPath = None;
3176 sOsKernelLog = None;
3177 sVgaText = None;
3178 asMiscInfos = [];
3179
3180 if not oSession.fHostMemoryLow:
3181 # Try to fetch the VM process info before meddling with its state.
3182 if self.fAlwaysUploadLogs or reporter.testErrorCount() > 0:
3183 sHostProcessInfo = utils.processGetInfo(oSession.getPid(), fSudo = True);
3184
3185 #
3186 # Pause the VM if we're going to take any screenshots or dig into the
3187 # guest. Failures are quitely ignored.
3188 #
3189 if self.fAlwaysUploadLogs or reporter.testErrorCount() > 0:
3190 try:
3191 if oSession.oVM.state in [ vboxcon.MachineState_Running,
3192 vboxcon.MachineState_LiveSnapshotting,
3193 vboxcon.MachineState_Teleporting ]:
3194 oSession.o.console.pause();
3195 except:
3196 reporter.logXcpt();
3197
3198 #
3199 # Take Screenshot and upload it (see below) to Test Manager if appropriate/requested.
3200 #
3201 if fTakeScreenshot is True or self.fAlwaysUploadScreenshots or reporter.testErrorCount() > 0:
3202 sLastScreenshotPath = os.path.join(self.sScratchPath, "LastScreenshot-%s.png" % oSession.sName);
3203 fRc = oSession.takeScreenshot(sLastScreenshotPath);
3204 if fRc is not True:
3205 sLastScreenshotPath = None;
3206
3207 # Query the OS kernel log from the debugger if appropriate/requested.
3208 if self.fAlwaysUploadLogs or reporter.testErrorCount() > 0:
3209 sOsKernelLog = oSession.queryOsKernelLog();
3210
3211 # Do "info vgatext all" separately.
3212 if self.fAlwaysUploadLogs or reporter.testErrorCount() > 0:
3213 sVgaText = oSession.queryDbgInfoVgaText();
3214
3215 # Various infos (do after kernel because of symbols).
3216 if self.fAlwaysUploadLogs or reporter.testErrorCount() > 0:
3217 # Dump the guest stack for all CPUs.
3218 cCpus = oSession.getCpuCount();
3219 if cCpus > 0:
3220 for iCpu in xrange(0, cCpus):
3221 sThis = oSession.queryDbgGuestStack(iCpu);
3222 if sThis:
3223 asMiscInfos += [
3224 '================ start guest stack VCPU %s ================\n' % (iCpu,),
3225 sThis,
3226 '================ end guest stack VCPU %s ==================\n' % (iCpu,),
3227 ];
3228
3229 for sInfo, sArg in [ ('mode', 'all'),
3230 ('fflags', ''),
3231 ('cpumguest', 'verbose all'),
3232 ('cpumguestinstr', 'symbol all'),
3233 ('exits', ''),
3234 ('pic', ''),
3235 ('apic', ''),
3236 ('apiclvt', ''),
3237 ('apictimer', ''),
3238 ('ioapic', ''),
3239 ('pit', ''),
3240 ('phys', ''),
3241 ('clocks', ''),
3242 ('timers', ''),
3243 ('gdt', ''),
3244 ('ldt', ''),
3245 ]:
3246 if sInfo in ['apic',] and self.fpApiVer < 5.1: # asserts and burns
3247 continue;
3248 sThis = oSession.queryDbgInfo(sInfo, sArg);
3249 if sThis:
3250 if sThis[-1] != '\n':
3251 sThis += '\n';
3252 asMiscInfos += [
3253 '================ start %s %s ================\n' % (sInfo, sArg),
3254 sThis,
3255 '================ end %s %s ==================\n' % (sInfo, sArg),
3256 ];
3257
3258 #
3259 # Terminate the VM
3260 #
3261
3262 # Cancel the progress object if specified.
3263 if oProgress is not None:
3264 if not oProgress.isCompleted() and oProgress.isCancelable():
3265 reporter.log2('terminateVmBySession: canceling "%s"...' % (oProgress.sName));
3266 try:
3267 oProgress.o.cancel();
3268 except:
3269 reporter.logXcpt();
3270 else:
3271 oProgress.wait();
3272 self.removeTask(oProgress);
3273
3274 # Check if the VM has terminated by itself before powering it off.
3275 fClose = True;
3276 fRc = True;
3277 if oSession.needsPoweringOff():
3278 reporter.log('terminateVmBySession: powering off "%s"...' % (oSession.sName,));
3279 fRc = oSession.powerOff(fFudgeOnFailure = False);
3280 if fRc is not True:
3281 # power off failed, try terminate it in a nice manner.
3282 fRc = False;
3283 uPid = oSession.getPid();
3284 if uPid is not None:
3285 #
3286 # Collect some information about the VM process first to have
3287 # some state information for further investigation why powering off failed.
3288 #
3289 sHostProcessInfoHung = utils.processGetInfo(uPid, fSudo = True);
3290
3291 # Exterminate...
3292 reporter.error('terminateVmBySession: Terminating PID %u (VM %s)' % (uPid, oSession.sName));
3293 fClose = base.processTerminate(uPid);
3294 if fClose is True:
3295 self.waitOnDirectSessionClose(oSession.oVM, 5000);
3296 fClose = oSession.waitForTask(1000);
3297
3298 if fClose is not True:
3299 # Being nice failed...
3300 reporter.error('terminateVmBySession: Termination failed, trying to kill PID %u (VM %s) instead' \
3301 % (uPid, oSession.sName));
3302 fClose = base.processKill(uPid);
3303 if fClose is True:
3304 self.waitOnDirectSessionClose(oSession.oVM, 5000);
3305 fClose = oSession.waitForTask(1000);
3306 if fClose is not True:
3307 reporter.error('terminateVmBySession: Failed to kill PID %u (VM %s)' % (uPid, oSession.sName));
3308
3309 # The final steps.
3310 if fClose is True:
3311 reporter.log('terminateVmBySession: closing session "%s"...' % (oSession.sName,));
3312 oSession.close();
3313 self.waitOnDirectSessionClose(oSession.oVM, 10000);
3314 try:
3315 eState = oSession.oVM.state;
3316 except:
3317 reporter.logXcpt();
3318 else:
3319 if eState == vboxcon.MachineState_Aborted:
3320 reporter.error('terminateVmBySession: The VM "%s" aborted!' % (oSession.sName,));
3321 self.removeTask(oSession);
3322
3323 #
3324 # Add the release log, debug log and a screenshot of the VM to the test report.
3325 #
3326 if self.fAlwaysUploadLogs or reporter.testErrorCount() > 0:
3327 oSession.addLogsToReport();
3328
3329 # Add a screenshot if it has been requested and taken successfully.
3330 if sLastScreenshotPath is not None:
3331 if reporter.testErrorCount() > 0:
3332 reporter.addLogFile(sLastScreenshotPath, 'screenshot/failure', 'Last VM screenshot');
3333 else:
3334 reporter.addLogFile(sLastScreenshotPath, 'screenshot/success', 'Last VM screenshot');
3335
3336 # Add the guest OS log if it has been requested and taken successfully.
3337 if sOsKernelLog is not None:
3338 reporter.addLogString(sOsKernelLog, 'kernel.log', 'log/guest/kernel', 'Guest OS kernel log');
3339
3340 # Add "info vgatext all" if we've got it.
3341 if sVgaText is not None:
3342 reporter.addLogString(sVgaText, 'vgatext.txt', 'info/vgatext', 'info vgatext all');
3343
3344 # Add the "info xxxx" items if we've got any.
3345 if asMiscInfos:
3346 reporter.addLogString(u''.join(asMiscInfos), 'info.txt', 'info/collection', 'A bunch of info items.');
3347
3348 # Add the host process info if we were able to retrieve it.
3349 if sHostProcessInfo is not None:
3350 reporter.log('Trying to annotate the VM process report, please stand by...');
3351 fRcTmp = self.annotateAndUploadProcessReport(sHostProcessInfo, 'vmprocess.log',
3352 'process/report/vm', 'Annotated VM process state');
3353 # Upload the raw log for manual annotation in case resolving failed.
3354 if not fRcTmp:
3355 reporter.log('Failed to annotate VM process report, uploading raw report');
3356 reporter.addLogString(sHostProcessInfo, 'vmprocess.log', 'process/report/vm', 'VM process state');
3357
3358 # Add the host process info for failed power off attempts if we were able to retrieve it.
3359 if sHostProcessInfoHung is not None:
3360 reporter.log('Trying to annotate the hung VM process report, please stand by...');
3361 fRcTmp = self.annotateAndUploadProcessReport(sHostProcessInfoHung, 'vmprocess-hung.log',
3362 'process/report/vm', 'Annotated hung VM process state');
3363 # Upload the raw log for manual annotation in case resolving failed.
3364 if not fRcTmp:
3365 reporter.log('Failed to annotate hung VM process report, uploading raw report');
3366 fRcTmp = reporter.addLogString(sHostProcessInfoHung, 'vmprocess-hung.log', 'process/report/vm',
3367 'Hung VM process state');
3368 if not fRcTmp:
3369 try: reporter.log('******* START vmprocess-hung.log *******\n%s\n******* END vmprocess-hung.log *******\n'
3370 % (sHostProcessInfoHung,));
3371 except: pass; # paranoia
3372
3373
3374 return fRc;
3375
3376
3377 #
3378 # Some information query functions (mix).
3379 #
3380 # Methods require the VBox API. If the information is provided by both
3381 # the testboxscript as well as VBox API, we'll check if it matches.
3382 #
3383
3384 def _hasHostCpuFeature(self, sEnvVar, sEnum, fpApiMinVer, fQuiet):
3385 """
3386 Common Worker for hasHostNestedPaging() and hasHostHwVirt().
3387
3388 Returns True / False.
3389 Raises exception on environment / host mismatch.
3390 """
3391 fEnv = os.environ.get(sEnvVar, None);
3392 if fEnv is not None:
3393 fEnv = fEnv.lower() not in [ 'false', 'f', 'not', 'no', 'n', '0', ];
3394
3395 fVBox = None;
3396 self.importVBoxApi();
3397 if self.fpApiVer >= fpApiMinVer and hasattr(vboxcon, sEnum):
3398 try:
3399 fVBox = self.oVBox.host.getProcessorFeature(getattr(vboxcon, sEnum));
3400 except:
3401 if not fQuiet:
3402 reporter.logXcpt();
3403
3404 if fVBox is not None:
3405 if fEnv is not None:
3406 if fEnv != fVBox and not fQuiet:
3407 reporter.log('TestBox configuration overwritten: fVBox=%s (%s) vs. fEnv=%s (%s)'
3408 % (fVBox, sEnum, fEnv, sEnvVar));
3409 return fEnv;
3410 return fVBox;
3411 if fEnv is not None:
3412 return fEnv;
3413 return False;
3414
3415 def hasHostHwVirt(self, fQuiet = False):
3416 """
3417 Checks if hardware assisted virtualization is supported by the host.
3418
3419 Returns True / False.
3420 Raises exception on environment / host mismatch.
3421 """
3422 return self._hasHostCpuFeature('TESTBOX_HAS_HW_VIRT', 'ProcessorFeature_HWVirtEx', 3.1, fQuiet);
3423
3424 def hasHostNestedPaging(self, fQuiet = False):
3425 """
3426 Checks if nested paging is supported by the host.
3427
3428 Returns True / False.
3429 Raises exception on environment / host mismatch.
3430 """
3431 return self._hasHostCpuFeature('TESTBOX_HAS_NESTED_PAGING', 'ProcessorFeature_NestedPaging', 4.2, fQuiet) \
3432 and self.hasHostHwVirt(fQuiet);
3433
3434 def hasHostNestedHwVirt(self, fQuiet = False):
3435 """
3436 Checks if nested hardware-assisted virtualization is supported by the host.
3437
3438 Returns True / False.
3439 Raises exception on environment / host mismatch.
3440 """
3441 return self._hasHostCpuFeature('TESTBOX_HAS_NESTED_HWVIRT', 'ProcessorFeature_NestedHWVirt', 6.0, fQuiet) \
3442 and self.hasHostHwVirt(fQuiet);
3443
3444 def hasHostLongMode(self, fQuiet = False):
3445 """
3446 Checks if the host supports 64-bit guests.
3447
3448 Returns True / False.
3449 Raises exception on environment / host mismatch.
3450 """
3451 # Note that the testboxscript doesn't export this variable atm.
3452 return self._hasHostCpuFeature('TESTBOX_HAS_LONG_MODE', 'ProcessorFeature_LongMode', 3.1, fQuiet);
3453
3454 def getHostCpuCount(self, fQuiet = False):
3455 """
3456 Returns the number of CPUs on the host.
3457
3458 Returns True / False.
3459 Raises exception on environment / host mismatch.
3460 """
3461 cEnv = os.environ.get('TESTBOX_CPU_COUNT', None);
3462 if cEnv is not None:
3463 cEnv = int(cEnv);
3464
3465 try:
3466 cVBox = self.oVBox.host.processorOnlineCount;
3467 except:
3468 if not fQuiet:
3469 reporter.logXcpt();
3470 cVBox = None;
3471
3472 if cVBox is not None:
3473 if cEnv is not None:
3474 assert cVBox == cEnv, 'Misconfigured TestBox: VBox: %u CPUs, testboxscript: %u CPUs' % (cVBox, cEnv);
3475 return cVBox;
3476 if cEnv is not None:
3477 return cEnv;
3478 return 1;
3479
3480 def _getHostCpuDesc(self, fQuiet = False):
3481 """
3482 Internal method used for getting the host CPU description from VBoxSVC.
3483 Returns description string, on failure an empty string is returned.
3484 """
3485 try:
3486 return self.oVBox.host.getProcessorDescription(0);
3487 except:
3488 if not fQuiet:
3489 reporter.logXcpt();
3490 return '';
3491
3492 def isHostCpuAmd(self, fQuiet = False):
3493 """
3494 Checks if the host CPU vendor is AMD.
3495
3496 Returns True / False.
3497 """
3498 sCpuDesc = self._getHostCpuDesc(fQuiet);
3499 return 'AMD' in sCpuDesc or sCpuDesc == 'AuthenticAMD';
3500
3501 def isHostCpuIntel(self, fQuiet = False):
3502 """
3503 Checks if the host CPU vendor is Intel.
3504
3505 Returns True / False.
3506 """
3507 sCpuDesc = self._getHostCpuDesc(fQuiet);
3508 return sCpuDesc.startswith("Intel") or sCpuDesc == 'GenuineIntel';
3509
3510 def isHostCpuVia(self, fQuiet = False):
3511 """
3512 Checks if the host CPU vendor is VIA (or Centaur).
3513
3514 Returns True / False.
3515 """
3516 sCpuDesc = self._getHostCpuDesc(fQuiet);
3517 return sCpuDesc.startswith("VIA") or sCpuDesc == 'CentaurHauls';
3518
3519 def isHostCpuShanghai(self, fQuiet = False):
3520 """
3521 Checks if the host CPU vendor is Shanghai (or Zhaoxin).
3522
3523 Returns True / False.
3524 """
3525 sCpuDesc = self._getHostCpuDesc(fQuiet);
3526 return sCpuDesc.startswith("ZHAOXIN") or sCpuDesc.strip(' ') == 'Shanghai';
3527
3528 def isHostCpuP4(self, fQuiet = False):
3529 """
3530 Checks if the host CPU is a Pentium 4 / Pentium D.
3531
3532 Returns True / False.
3533 """
3534 if not self.isHostCpuIntel(fQuiet):
3535 return False;
3536
3537 (uFamilyModel, _, _, _) = self.oVBox.host.getProcessorCPUIDLeaf(0, 0x1, 0);
3538 return ((uFamilyModel >> 8) & 0xf) == 0xf;
3539
3540 def hasRawModeSupport(self, fQuiet = False):
3541 """
3542 Checks if raw-mode is supported by VirtualBox that the testbox is
3543 configured for it.
3544
3545 Returns True / False.
3546 Raises no exceptions.
3547
3548 Note! Differs from the rest in that we don't require the
3549 TESTBOX_WITH_RAW_MODE value to match the API. It is
3550 sometimes helpful to disable raw-mode on individual
3551 test boxes. (This probably goes for
3552 """
3553 # The environment variable can be used to disable raw-mode.
3554 fEnv = os.environ.get('TESTBOX_WITH_RAW_MODE', None);
3555 if fEnv is not None:
3556 fEnv = fEnv.lower() not in [ 'false', 'f', 'not', 'no', 'n', '0', ];
3557 if fEnv is False:
3558 return False;
3559
3560 # Starting with 5.0 GA / RC2 the API can tell us whether VBox was built
3561 # with raw-mode support or not.
3562 self.importVBoxApi();
3563 if self.fpApiVer >= 5.0:
3564 try:
3565 fVBox = self.oVBox.systemProperties.rawModeSupported;
3566 except:
3567 if not fQuiet:
3568 reporter.logXcpt();
3569 fVBox = True;
3570 if fVBox is False:
3571 return False;
3572
3573 return True;
3574
3575 #
3576 # Testdriver execution methods.
3577 #
3578
3579 def handleTask(self, oTask, sMethod):
3580 """
3581 Callback method for handling unknown tasks in the various run loops.
3582
3583 The testdriver should override this if it already tasks running when
3584 calling startVmAndConnectToTxsViaTcp, txsRunTest or similar methods.
3585 Call super to handle unknown tasks.
3586
3587 Returns True if handled, False if not.
3588 """
3589 reporter.error('%s: unknown task %s' % (sMethod, oTask));
3590 return False;
3591
3592 def txsDoTask(self, oSession, oTxsSession, fnAsync, aArgs):
3593 """
3594 Generic TXS task wrapper which waits both on the TXS and the session tasks.
3595
3596 Returns False on error, logged.
3597 Returns task result on success.
3598 """
3599 # All async methods ends with the following two args.
3600 cMsTimeout = aArgs[-2];
3601 fIgnoreErrors = aArgs[-1];
3602
3603 fRemoveVm = self.addTask(oSession);
3604 fRemoveTxs = self.addTask(oTxsSession);
3605
3606 rc = fnAsync(*aArgs); # pylint: disable=star-args
3607 if rc is True:
3608 rc = False;
3609 oTask = self.waitForTasks(cMsTimeout + 1);
3610 if oTask is oTxsSession:
3611 if oTxsSession.isSuccess():
3612 rc = oTxsSession.getResult();
3613 elif fIgnoreErrors is True:
3614 reporter.log( 'txsDoTask: task failed (%s)' % (oTxsSession.getLastReply()[1],));
3615 else:
3616 reporter.error('txsDoTask: task failed (%s)' % (oTxsSession.getLastReply()[1],));
3617 else:
3618 oTxsSession.cancelTask();
3619 if oTask is None:
3620 if fIgnoreErrors is True:
3621 reporter.log( 'txsDoTask: The task timed out.');
3622 else:
3623 reporter.errorTimeout('txsDoTask: The task timed out.');
3624 elif oTask is oSession:
3625 reporter.error('txsDoTask: The VM terminated unexpectedly');
3626 else:
3627 if fIgnoreErrors is True:
3628 reporter.log( 'txsDoTask: An unknown task %s was returned' % (oTask,));
3629 else:
3630 reporter.error('txsDoTask: An unknown task %s was returned' % (oTask,));
3631 else:
3632 reporter.error('txsDoTask: fnAsync returned %s' % (rc,));
3633
3634 if fRemoveTxs:
3635 self.removeTask(oTxsSession);
3636 if fRemoveVm:
3637 self.removeTask(oSession);
3638 return rc;
3639
3640 # pylint: disable=missing-docstring
3641
3642 def txsDisconnect(self, oSession, oTxsSession, cMsTimeout = 30000, fIgnoreErrors = False):
3643 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncDisconnect,
3644 (self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3645
3646 def txsVer(self, oSession, oTxsSession, cMsTimeout = 30000, fIgnoreErrors = False):
3647 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncVer,
3648 (self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3649
3650 def txsUuid(self, oSession, oTxsSession, cMsTimeout = 30000, fIgnoreErrors = False):
3651 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncUuid,
3652 (self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3653
3654 def txsMkDir(self, oSession, oTxsSession, sRemoteDir, fMode = 0o700, cMsTimeout = 30000, fIgnoreErrors = False):
3655 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncMkDir,
3656 (sRemoteDir, fMode, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3657
3658 def txsMkDirPath(self, oSession, oTxsSession, sRemoteDir, fMode = 0o700, cMsTimeout = 30000, fIgnoreErrors = False):
3659 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncMkDirPath,
3660 (sRemoteDir, fMode, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3661
3662 def txsMkSymlink(self, oSession, oTxsSession, sLinkTarget, sLink, cMsTimeout = 30000, fIgnoreErrors = False):
3663 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncMkSymlink,
3664 (sLinkTarget, sLink, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3665
3666 def txsRmDir(self, oSession, oTxsSession, sRemoteDir, cMsTimeout = 30000, fIgnoreErrors = False):
3667 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncRmDir,
3668 (sRemoteDir, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3669
3670 def txsRmFile(self, oSession, oTxsSession, sRemoteFile, cMsTimeout = 30000, fIgnoreErrors = False):
3671 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncRmFile,
3672 (sRemoteFile, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3673
3674 def txsRmSymlink(self, oSession, oTxsSession, sRemoteSymlink, cMsTimeout = 30000, fIgnoreErrors = False):
3675 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncRmSymlink,
3676 (sRemoteSymlink, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3677
3678 def txsRmTree(self, oSession, oTxsSession, sRemoteTree, cMsTimeout = 30000, fIgnoreErrors = False):
3679 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncRmTree,
3680 (sRemoteTree, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3681
3682 def txsIsDir(self, oSession, oTxsSession, sRemoteDir, cMsTimeout = 30000, fIgnoreErrors = False):
3683 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncIsDir,
3684 (sRemoteDir, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3685
3686 def txsIsFile(self, oSession, oTxsSession, sRemoteFile, cMsTimeout = 30000, fIgnoreErrors = False):
3687 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncIsFile,
3688 (sRemoteFile, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3689
3690 def txsIsSymlink(self, oSession, oTxsSession, sRemoteSymlink, cMsTimeout = 30000, fIgnoreErrors = False):
3691 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncIsSymlink,
3692 (sRemoteSymlink, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3693
3694 def txsCopyFile(self, oSession, oTxsSession, sSrcFile, sDstFile, fMode = 0, cMsTimeout = 30000, fIgnoreErrors = False):
3695 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncCopyFile, \
3696 (sSrcFile, sDstFile, fMode, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3697
3698 def txsUploadFile(self, oSession, oTxsSession, sLocalFile, sRemoteFile, cMsTimeout = 30000, fIgnoreErrors = False):
3699 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncUploadFile, \
3700 (sLocalFile, sRemoteFile, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3701
3702 def txsUploadString(self, oSession, oTxsSession, sContent, sRemoteFile, cMsTimeout = 30000, fIgnoreErrors = False):
3703 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncUploadString, \
3704 (sContent, sRemoteFile, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3705
3706 def txsDownloadFile(self, oSession, oTxsSession, sRemoteFile, sLocalFile, cMsTimeout = 30000, fIgnoreErrors = False):
3707 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncDownloadFile, \
3708 (sRemoteFile, sLocalFile, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3709
3710 def txsDownloadFiles(self, oSession, oTxsSession, aasFiles, fAddToLog = True, fIgnoreErrors = False):
3711 """
3712 Convenience function to get files from the guest, storing them in the
3713 scratch and adding them to the test result set (optional, but default).
3714
3715 The aasFiles parameter contains an array of with guest-path + host-path
3716 pairs, optionally a file 'kind', description and an alternative upload
3717 filename can also be specified.
3718
3719 Host paths are relative to the scratch directory or they must be given
3720 in absolute form. The guest path should be using guest path style.
3721
3722 Returns True on success.
3723 Returns False on failure (unless fIgnoreErrors is set), logged.
3724 """
3725 for asEntry in aasFiles:
3726 # Unpack:
3727 sGstFile = asEntry[0];
3728 sHstFile = asEntry[1];
3729 sKind = asEntry[2] if len(asEntry) > 2 and asEntry[2] else 'misc/other';
3730 sDescription = asEntry[3] if len(asEntry) > 3 and asEntry[3] else '';
3731 sAltName = asEntry[4] if len(asEntry) > 4 and asEntry[4] else None;
3732 assert len(asEntry) <= 5 and sGstFile and sHstFile;
3733 if not os.path.isabs(sHstFile):
3734 sHstFile = os.path.join(self.sScratchPath, sHstFile);
3735
3736 reporter.log2('Downloading file "%s" to "%s" ...' % (sGstFile, sHstFile,));
3737
3738 try: os.unlink(sHstFile); ## @todo txsDownloadFile doesn't truncate the output file.
3739 except: pass;
3740
3741 fRc = self.txsDownloadFile(oSession, oTxsSession, sGstFile, sHstFile, 30 * 1000, fIgnoreErrors);
3742 if fRc:
3743 if fAddToLog:
3744 reporter.addLogFile(sHstFile, sKind, sDescription, sAltName);
3745 else:
3746 if fIgnoreErrors is not True:
3747 return reporter.error('error downloading file "%s" to "%s"' % (sGstFile, sHstFile));
3748 reporter.log('warning: file "%s" was not downloaded, ignoring.' % (sGstFile,));
3749 return True;
3750
3751 def txsDownloadString(self, oSession, oTxsSession, sRemoteFile, sEncoding = 'utf-8', fIgnoreEncodingErrors = True,
3752 cMsTimeout = 30000, fIgnoreErrors = False):
3753 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncDownloadString,
3754 (sRemoteFile, sEncoding, fIgnoreEncodingErrors, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3755
3756 def txsPackFile(self, oSession, oTxsSession, sRemoteFile, sRemoteSource, cMsTimeout = 30000, fIgnoreErrors = False):
3757 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncPackFile, \
3758 (sRemoteFile, sRemoteSource, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3759
3760 def txsUnpackFile(self, oSession, oTxsSession, sRemoteFile, sRemoteDir, cMsTimeout = 30000, fIgnoreErrors = False):
3761 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncUnpackFile, \
3762 (sRemoteFile, sRemoteDir, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3763
3764 def txsExpandString(self, oSession, oTxsSession, sString, cMsTimeout = 30000, fIgnoreErrors = False):
3765 return self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncExpandString, \
3766 (sString, self.adjustTimeoutMs(cMsTimeout), fIgnoreErrors));
3767
3768 # pylint: enable=missing-docstring
3769
3770 def txsCdWait(self,
3771 oSession, # type: vboxwrappers.SessionWrapper
3772 oTxsSession, # type: txsclient.Session
3773 cMsTimeout = 30000, # type: int
3774 sFile = None # type: String
3775 ): # -> bool
3776 """
3777 Mostly an internal helper for txsRebootAndReconnectViaTcp and
3778 startVmAndConnectToTxsViaTcp that waits for the CDROM drive to become
3779 ready. It does this by polling for a file it knows to exist on the CD.
3780
3781 Returns True on success.
3782
3783 Returns False on failure, logged.
3784 """
3785
3786 if sFile is None:
3787 sFile = 'valkit.txt';
3788
3789 reporter.log('txsCdWait: Waiting for file "%s" to become available ...' % (sFile,));
3790
3791 fRemoveVm = self.addTask(oSession);
3792 fRemoveTxs = self.addTask(oTxsSession);
3793 cMsTimeout = self.adjustTimeoutMs(cMsTimeout);
3794 msStart = base.timestampMilli();
3795 cMsTimeout2 = cMsTimeout;
3796 fRc = oTxsSession.asyncIsFile('${CDROM}/%s' % (sFile,), cMsTimeout2);
3797 if fRc is True:
3798 while True:
3799 # wait for it to complete.
3800 oTask = self.waitForTasks(cMsTimeout2 + 1);
3801 if oTask is not oTxsSession:
3802 oTxsSession.cancelTask();
3803 if oTask is None:
3804 reporter.errorTimeout('txsCdWait: The task timed out (after %s ms).'
3805 % (base.timestampMilli() - msStart,));
3806 elif oTask is oSession:
3807 reporter.error('txsCdWait: The VM terminated unexpectedly');
3808 else:
3809 reporter.error('txsCdWait: An unknown task %s was returned' % (oTask,));
3810 fRc = False;
3811 break;
3812 if oTxsSession.isSuccess():
3813 break;
3814
3815 # Check for timeout.
3816 cMsElapsed = base.timestampMilli() - msStart;
3817 if cMsElapsed >= cMsTimeout:
3818 reporter.error('txsCdWait: timed out');
3819 fRc = False;
3820 break;
3821 # delay.
3822 self.sleep(1);
3823
3824 # resubmit the task.
3825 cMsTimeout2 = msStart + cMsTimeout - base.timestampMilli();
3826 cMsTimeout2 = max(cMsTimeout2, 500);
3827 fRc = oTxsSession.asyncIsFile('${CDROM}/%s' % (sFile,), cMsTimeout2);
3828 if fRc is not True:
3829 reporter.error('txsCdWait: asyncIsFile failed');
3830 break;
3831 else:
3832 reporter.error('txsCdWait: asyncIsFile failed');
3833
3834 if not fRc:
3835 # Do some diagnosis to find out why this failed.
3836 ## @todo Identify guest OS type and only run one of the following commands.
3837 fIsNotWindows = True;
3838 reporter.log('txsCdWait: Listing root contents of ${CDROM}:');
3839 if fIsNotWindows:
3840 reporter.log('txsCdWait: Tiggering udevadm ...');
3841 oTxsSession.syncExec("/sbin/udevadm", ("/sbin/udevadm", "trigger", "--verbose"), fIgnoreErrors = True);
3842 time.sleep(15);
3843 oTxsSession.syncExec("/bin/ls", ("/bin/ls", "-al", "${CDROM}"), fIgnoreErrors = True);
3844 reporter.log('txsCdWait: Listing media directory:');
3845 oTxsSession.syncExec('/bin/ls', ('/bin/ls', '-l', '-a', '-R', '/media'), fIgnoreErrors = True);
3846 reporter.log('txsCdWait: Listing mount points / drives:');
3847 oTxsSession.syncExec('/bin/mount', ('/bin/mount',), fIgnoreErrors = True);
3848 oTxsSession.syncExec('/bin/cat', ('/bin/cat', '/etc/fstab'), fIgnoreErrors = True);
3849 oTxsSession.syncExec('/bin/dmesg', ('/bin/dmesg',), fIgnoreErrors = True);
3850 oTxsSession.syncExec('/usr/bin/lshw', ('/usr/bin/lshw', '-c', 'disk'), fIgnoreErrors = True);
3851 oTxsSession.syncExec('/bin/journalctl',
3852 ('/bin/journalctl', '-x', '-b'), fIgnoreErrors = True);
3853 oTxsSession.syncExec('/bin/journalctl',
3854 ('/bin/journalctl', '-x', '-b', '/usr/lib/udisks2/udisksd'), fIgnoreErrors = True);
3855 oTxsSession.syncExec('/usr/bin/udisksctl',
3856 ('/usr/bin/udisksctl', 'info', '-b', '/dev/sr0'), fIgnoreErrors = True);
3857 oTxsSession.syncExec('/bin/systemctl',
3858 ('/bin/systemctl', 'status', 'udisks2'), fIgnoreErrors = True);
3859 oTxsSession.syncExec('/bin/ps',
3860 ('/bin/ps', '-a', '-u', '-x'), fIgnoreErrors = True);
3861 reporter.log('txsCdWait: Mounting manually ...');
3862 for _ in range(3):
3863 oTxsSession.syncExec('/bin/mount', ('/bin/mount', '/dev/sr0', '${CDROM}'), fIgnoreErrors = True);
3864 time.sleep(5);
3865 reporter.log('txsCdWait: Re-Listing media directory:');
3866 oTxsSession.syncExec('/bin/ls', ('/bin/ls', '-l', '-a', '-R', '/media'), fIgnoreErrors = True);
3867 else:
3868 # ASSUMES that we always install Windows on drive C right now.
3869 sWinDir = "C:\\Windows\\System32\\";
3870 # Should work since WinXP Pro.
3871 oTxsSession.syncExec(sWinDir + "wbem\\WMIC.exe",
3872 ("WMIC.exe", "logicaldisk", "get",
3873 "deviceid, volumename, description"),
3874 fIgnoreErrors = True);
3875 oTxsSession.syncExec(sWinDir + " cmd.exe",
3876 ('cmd.exe', '/C', 'dir', '${CDROM}'),
3877 fIgnoreErrors = True);
3878
3879 if fRemoveTxs:
3880 self.removeTask(oTxsSession);
3881 if fRemoveVm:
3882 self.removeTask(oSession);
3883 return fRc;
3884
3885 def txsDoConnectViaTcp(self, oSession, cMsTimeout, fNatForwardingForTxs = False):
3886 """
3887 Mostly an internal worker for connecting to TXS via TCP used by the
3888 *ViaTcp methods.
3889
3890 Returns a tuplet with True/False and TxsSession/None depending on the
3891 result. Errors are logged.
3892 """
3893
3894 reporter.log2('txsDoConnectViaTcp: oSession=%s, cMsTimeout=%s, fNatForwardingForTxs=%s'
3895 % (oSession, cMsTimeout, fNatForwardingForTxs));
3896
3897 cMsTimeout = self.adjustTimeoutMs(cMsTimeout);
3898 oTxsConnect = oSession.txsConnectViaTcp(cMsTimeout, fNatForwardingForTxs = fNatForwardingForTxs);
3899 if oTxsConnect is not None:
3900 self.addTask(oTxsConnect);
3901 fRemoveVm = self.addTask(oSession);
3902 oTask = self.waitForTasks(cMsTimeout + 1);
3903 reporter.log2('txsDoConnectViaTcp: waitForTasks returned %s' % (oTask,));
3904 self.removeTask(oTxsConnect);
3905 if oTask is oTxsConnect:
3906 oTxsSession = oTxsConnect.getResult();
3907 if oTxsSession is not None:
3908 reporter.log('txsDoConnectViaTcp: Connected to TXS on %s.' % (oTxsSession.oTransport.sHostname,));
3909 return (True, oTxsSession);
3910
3911 reporter.error('txsDoConnectViaTcp: failed to connect to TXS.');
3912 else:
3913 oTxsConnect.cancelTask();
3914 if oTask is None:
3915 reporter.errorTimeout('txsDoConnectViaTcp: connect stage 1 timed out');
3916 elif oTask is oSession:
3917 oSession.reportPrematureTermination('txsDoConnectViaTcp: ');
3918 else:
3919 reporter.error('txsDoConnectViaTcp: unknown/wrong task %s' % (oTask,));
3920 if fRemoveVm:
3921 self.removeTask(oSession);
3922 else:
3923 reporter.error('txsDoConnectViaTcp: txsConnectViaTcp failed');
3924 return (False, None);
3925
3926 def startVmAndConnectToTxsViaTcp(self, sVmName, fCdWait = False, cMsTimeout = 15*60000, \
3927 cMsCdWait = 30000, sFileCdWait = None, \
3928 fNatForwardingForTxs = False):
3929 """
3930 Starts the specified VM and tries to connect to its TXS via TCP.
3931 The VM will be powered off if TXS doesn't respond before the specified
3932 time has elapsed.
3933
3934 Returns a the VM and TXS sessions (a two tuple) on success. The VM
3935 session is in the task list, the TXS session is not.
3936 Returns (None, None) on failure, fully logged.
3937 """
3938
3939 # Zap the guest IP to make sure we're not getting a stale entry
3940 # (unless we're restoring the VM of course).
3941 oTestVM = self.oTestVmSet.findTestVmByName(sVmName) if self.oTestVmSet is not None else None;
3942 if oTestVM is None \
3943 or oTestVM.fSnapshotRestoreCurrent is False:
3944 try:
3945 oSession1 = self.openSession(self.getVmByName(sVmName));
3946 oSession1.delGuestPropertyValue('/VirtualBox/GuestInfo/Net/0/V4/IP');
3947 oSession1.saveSettings(True);
3948 del oSession1;
3949 except:
3950 reporter.logXcpt();
3951
3952 # Start the VM.
3953 reporter.log('startVmAndConnectToTxsViaTcp: Starting(/preparing) "%s" (timeout %s s)...' % (sVmName, cMsTimeout / 1000));
3954 reporter.flushall();
3955 oSession = self.startVmByName(sVmName);
3956 if oSession is not None:
3957 # Connect to TXS.
3958 reporter.log2('startVmAndConnectToTxsViaTcp: Started(/prepared) "%s", connecting to TXS ...' % (sVmName,));
3959 (fRc, oTxsSession) = self.txsDoConnectViaTcp(oSession, cMsTimeout, fNatForwardingForTxs);
3960 if fRc is True:
3961 if fCdWait:
3962 # Wait for CD?
3963 reporter.log2('startVmAndConnectToTxsViaTcp: Waiting for file "%s" to become available ...' % (sFileCdWait,));
3964 fRc = self.txsCdWait(oSession, oTxsSession, cMsCdWait, sFileCdWait);
3965 if fRc is not True:
3966 reporter.error('startVmAndConnectToTxsViaTcp: txsCdWait failed');
3967
3968 sVer = self.txsVer(oSession, oTxsSession, cMsTimeout, fIgnoreErrors = True);
3969 if sVer is not False:
3970 reporter.log('startVmAndConnectToTxsViaTcp: TestExecService version %s' % (sVer,));
3971 else:
3972 reporter.log('startVmAndConnectToTxsViaTcp: Unable to retrieve TestExecService version');
3973
3974 if fRc is True:
3975 # Success!
3976 return (oSession, oTxsSession);
3977 else:
3978 reporter.error('startVmAndConnectToTxsViaTcp: txsDoConnectViaTcp failed');
3979 # If something went wrong while waiting for TXS to be started - take VM screenshot before terminate it
3980 self.terminateVmBySession(oSession);
3981 return (None, None);
3982
3983 def txsRebootAndReconnectViaTcp(self, oSession, oTxsSession, fCdWait = False, cMsTimeout = 15*60000, \
3984 cMsCdWait = 30000, sFileCdWait = None, fNatForwardingForTxs = False):
3985 """
3986 Executes the TXS reboot command
3987
3988 Returns A tuple of True and the new TXS session on success.
3989
3990 Returns A tuple of False and either the old TXS session or None on failure.
3991 """
3992 reporter.log2('txsRebootAndReconnect: cMsTimeout=%u' % (cMsTimeout,));
3993
3994 #
3995 # This stuff is a bit complicated because of rebooting being kind of
3996 # disruptive to the TXS and such... The protocol is that TXS will:
3997 # - ACK the reboot command.
3998 # - Shutdown the transport layer, implicitly disconnecting us.
3999 # - Execute the reboot operation.
4000 # - On failure, it will be re-init the transport layer and be
4001 # available pretty much immediately. UUID unchanged.
4002 # - On success, it will be respawed after the reboot (hopefully),
4003 # with a different UUID.
4004 #
4005 fRc = False;
4006 iStart = base.timestampMilli();
4007
4008 # Get UUID.
4009 cMsTimeout2 = min(60000, cMsTimeout);
4010 sUuidBefore = self.txsUuid(oSession, oTxsSession, self.adjustTimeoutMs(cMsTimeout2, 60000));
4011 if sUuidBefore is not False:
4012 # Reboot.
4013 cMsElapsed = base.timestampMilli() - iStart;
4014 cMsTimeout2 = cMsTimeout - cMsElapsed;
4015 fRc = self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncReboot,
4016 (self.adjustTimeoutMs(cMsTimeout2, 60000), False));
4017 if fRc is True:
4018 # Reconnect.
4019 if fNatForwardingForTxs is True:
4020 self.sleep(22); # NAT fudge - Two fixes are wanted: 1. TXS connect retries. 2. Main API reboot/reset hint.
4021 cMsElapsed = base.timestampMilli() - iStart;
4022 (fRc, oTxsSession) = self.txsDoConnectViaTcp(oSession, cMsTimeout - cMsElapsed, fNatForwardingForTxs);
4023 if fRc is True:
4024 # Check the UUID.
4025 cMsElapsed = base.timestampMilli() - iStart;
4026 cMsTimeout2 = min(60000, cMsTimeout - cMsElapsed);
4027 sUuidAfter = self.txsDoTask(oSession, oTxsSession, oTxsSession.asyncUuid,
4028 (self.adjustTimeoutMs(cMsTimeout2, 60000), False));
4029 if sUuidBefore is not False:
4030 if sUuidAfter != sUuidBefore:
4031 reporter.log('The guest rebooted (UUID %s -> %s)' % (sUuidBefore, sUuidAfter))
4032
4033 # Do CD wait if specified.
4034 if fCdWait:
4035 fRc = self.txsCdWait(oSession, oTxsSession, cMsCdWait, sFileCdWait);
4036 if fRc is not True:
4037 reporter.error('txsRebootAndReconnectViaTcp: txsCdWait failed');
4038
4039 sVer = self.txsVer(oSession, oTxsSession, cMsTimeout, fIgnoreErrors = True);
4040 if sVer is not False:
4041 reporter.log('txsRebootAndReconnectViaTcp: TestExecService version %s' % (sVer,));
4042 else:
4043 reporter.log('txsRebootAndReconnectViaTcp: Unable to retrieve TestExecService version');
4044 else:
4045 reporter.error('txsRebootAndReconnectViaTcp: failed to get UUID (after)');
4046 else:
4047 reporter.error('txsRebootAndReconnectViaTcp: did not reboot (UUID %s)' % (sUuidBefore,));
4048 else:
4049 reporter.error('txsRebootAndReconnectViaTcp: txsDoConnectViaTcp failed');
4050 else:
4051 reporter.error('txsRebootAndReconnectViaTcp: reboot failed');
4052 else:
4053 reporter.error('txsRebootAndReconnectViaTcp: failed to get UUID (before)');
4054 return (fRc, oTxsSession);
4055
4056 # pylint: disable=too-many-locals,too-many-arguments
4057
4058 def txsRunTest(self, oTxsSession, sTestName, cMsTimeout, sExecName, asArgs = (), asAddEnv = (), sAsUser = "",
4059 fCheckSessionStatus = False):
4060 """
4061 Executes the specified test task, waiting till it completes or times out.
4062
4063 The VM session (if any) must be in the task list.
4064
4065 Returns True if we executed the task and nothing abnormal happend.
4066 Query the process status from the TXS session.
4067
4068 Returns False if some unexpected task was signalled or we failed to
4069 submit the job.
4070
4071 If fCheckSessionStatus is set to True, the overall session status will be
4072 taken into account and logged as an error on failure.
4073 """
4074 reporter.testStart(sTestName);
4075 reporter.log2('txsRunTest: cMsTimeout=%u sExecName=%s asArgs=%s' % (cMsTimeout, sExecName, asArgs));
4076
4077 # Submit the job.
4078 fRc = False;
4079 if oTxsSession.asyncExec(sExecName, asArgs, asAddEnv, sAsUser, cMsTimeout = self.adjustTimeoutMs(cMsTimeout)):
4080 self.addTask(oTxsSession);
4081
4082 # Wait for the job to complete.
4083 while True:
4084 oTask = self.waitForTasks(cMsTimeout + 1);
4085 if oTask is None:
4086 if fCheckSessionStatus:
4087 reporter.error('txsRunTest: waitForTasks for test "%s" timed out' % (sTestName,));
4088 else:
4089 reporter.log('txsRunTest: waitForTasks for test "%s" timed out' % (sTestName,));
4090 break;
4091 if oTask is oTxsSession:
4092 if fCheckSessionStatus \
4093 and not oTxsSession.isSuccess():
4094 reporter.error('txsRunTest: Test "%s" failed' % (sTestName,));
4095 else:
4096 fRc = True;
4097 reporter.log('txsRunTest: isSuccess=%s getResult=%s' \
4098 % (oTxsSession.isSuccess(), oTxsSession.getResult()));
4099 break;
4100 if not self.handleTask(oTask, 'txsRunTest'):
4101 break;
4102
4103 self.removeTask(oTxsSession);
4104 if not oTxsSession.pollTask():
4105 oTxsSession.cancelTask();
4106 else:
4107 reporter.error('txsRunTest: asyncExec failed');
4108
4109 reporter.testDone();
4110 return fRc;
4111
4112 def txsRunTestRedirectStd(self, oTxsSession, sTestName, cMsTimeout, sExecName, asArgs = (), asAddEnv = (), sAsUser = "",
4113 oStdIn = '/dev/null', oStdOut = '/dev/null', oStdErr = '/dev/null', oTestPipe = '/dev/null'):
4114 """
4115 Executes the specified test task, waiting till it completes or times out,
4116 redirecting stdin, stdout and stderr to the given objects.
4117
4118 The VM session (if any) must be in the task list.
4119
4120 Returns True if we executed the task and nothing abnormal happend.
4121 Query the process status from the TXS session.
4122
4123 Returns False if some unexpected task was signalled or we failed to
4124 submit the job.
4125 """
4126 reporter.testStart(sTestName);
4127 reporter.log2('txsRunTestRedirectStd: cMsTimeout=%u sExecName=%s asArgs=%s' % (cMsTimeout, sExecName, asArgs));
4128
4129 # Submit the job.
4130 fRc = False;
4131 if oTxsSession.asyncExecEx(sExecName, asArgs, asAddEnv, oStdIn, oStdOut, oStdErr,
4132 oTestPipe, sAsUser, cMsTimeout = self.adjustTimeoutMs(cMsTimeout)):
4133 self.addTask(oTxsSession);
4134
4135 # Wait for the job to complete.
4136 while True:
4137 oTask = self.waitForTasks(cMsTimeout + 1);
4138 if oTask is None:
4139 reporter.log('txsRunTestRedirectStd: waitForTasks timed out');
4140 break;
4141 if oTask is oTxsSession:
4142 fRc = True;
4143 reporter.log('txsRunTestRedirectStd: isSuccess=%s getResult=%s'
4144 % (oTxsSession.isSuccess(), oTxsSession.getResult()));
4145 break;
4146 if not self.handleTask(oTask, 'txsRunTestRedirectStd'):
4147 break;
4148
4149 self.removeTask(oTxsSession);
4150 if not oTxsSession.pollTask():
4151 oTxsSession.cancelTask();
4152 else:
4153 reporter.error('txsRunTestRedirectStd: asyncExec failed');
4154
4155 reporter.testDone();
4156 return fRc;
4157
4158 def txsRunTest2(self, oTxsSession1, oTxsSession2, sTestName, cMsTimeout,
4159 sExecName1, asArgs1,
4160 sExecName2, asArgs2,
4161 asAddEnv1 = (), sAsUser1 = '', fWithTestPipe1 = True,
4162 asAddEnv2 = (), sAsUser2 = '', fWithTestPipe2 = True):
4163 """
4164 Executes the specified test tasks, waiting till they complete or
4165 times out. The 1st task is started after the 2nd one.
4166
4167 The VM session (if any) must be in the task list.
4168
4169 Returns True if we executed the task and nothing abnormal happend.
4170 Query the process status from the TXS sessions.
4171
4172 Returns False if some unexpected task was signalled or we failed to
4173 submit the job.
4174 """
4175 reporter.testStart(sTestName);
4176
4177 # Submit the jobs.
4178 fRc = False;
4179 if oTxsSession1.asyncExec(sExecName1, asArgs1, asAddEnv1, sAsUser1, fWithTestPipe1, '1-',
4180 self.adjustTimeoutMs(cMsTimeout)):
4181 self.addTask(oTxsSession1);
4182
4183 self.sleep(2); # fudge! grr
4184
4185 if oTxsSession2.asyncExec(sExecName2, asArgs2, asAddEnv2, sAsUser2, fWithTestPipe2, '2-',
4186 self.adjustTimeoutMs(cMsTimeout)):
4187 self.addTask(oTxsSession2);
4188
4189 # Wait for the jobs to complete.
4190 cPendingJobs = 2;
4191 while True:
4192 oTask = self.waitForTasks(cMsTimeout + 1);
4193 if oTask is None:
4194 reporter.log('txsRunTest2: waitForTasks timed out');
4195 break;
4196
4197 if oTask is oTxsSession1 or oTask is oTxsSession2:
4198 if oTask is oTxsSession1: iTask = 1;
4199 else: iTask = 2;
4200 reporter.log('txsRunTest2: #%u - isSuccess=%s getResult=%s' \
4201 % (iTask, oTask.isSuccess(), oTask.getResult()));
4202 self.removeTask(oTask);
4203 cPendingJobs -= 1;
4204 if cPendingJobs <= 0:
4205 fRc = True;
4206 break;
4207
4208 elif not self.handleTask(oTask, 'txsRunTest'):
4209 break;
4210
4211 self.removeTask(oTxsSession2);
4212 if not oTxsSession2.pollTask():
4213 oTxsSession2.cancelTask();
4214 else:
4215 reporter.error('txsRunTest2: asyncExec #2 failed');
4216
4217 self.removeTask(oTxsSession1);
4218 if not oTxsSession1.pollTask():
4219 oTxsSession1.cancelTask();
4220 else:
4221 reporter.error('txsRunTest2: asyncExec #1 failed');
4222
4223 reporter.testDone();
4224 return fRc;
4225
4226 # pylint: enable=too-many-locals,too-many-arguments
4227
4228
4229 #
4230 # Working with test results via serial port.
4231 #
4232
4233 class TxsMonitorComFile(base.TdTaskBase):
4234 """
4235 Class that monitors a COM output file.
4236 """
4237
4238 def __init__(self, sComRawFile, asStopWords = None):
4239 base.TdTaskBase.__init__(self, utils.getCallerName());
4240 self.sComRawFile = sComRawFile;
4241 self.oStopRegExp = re.compile('\\b(' + '|'.join(asStopWords if asStopWords else ('PASSED', 'FAILED',)) + ')\\b');
4242 self.sResult = None; ##< The result.
4243 self.cchDisplayed = 0; ##< Offset into the file string of what we've already fed to the logger.
4244
4245 def toString(self):
4246 return '<%s sComRawFile=%s oStopRegExp=%s sResult=%s cchDisplayed=%s>' \
4247 % (base.TdTaskBase.toString(self), self.sComRawFile, self.oStopRegExp, self.sResult, self.cchDisplayed,);
4248
4249 def pollTask(self, fLocked = False):
4250 """
4251 Overrides TdTaskBase.pollTask() for the purpose of polling the file.
4252 """
4253 if not fLocked:
4254 self.lockTask();
4255
4256 sFile = utils.noxcptReadFile(self.sComRawFile, '', 'rU');
4257 if len(sFile) > self.cchDisplayed:
4258 sNew = sFile[self.cchDisplayed:];
4259 oMatch = self.oStopRegExp.search(sNew);
4260 if oMatch:
4261 # Done! Get result, flush all the output and signal the task.
4262 self.sResult = oMatch.group(1);
4263 for sLine in sNew.split('\n'):
4264 reporter.log('COM OUTPUT: %s' % (sLine,));
4265 self.cchDisplayed = len(sFile);
4266 self.signalTaskLocked();
4267 else:
4268 # Output whole lines only.
4269 offNewline = sFile.find('\n', self.cchDisplayed);
4270 while offNewline >= 0:
4271 reporter.log('COM OUTPUT: %s' % (sFile[self.cchDisplayed:offNewline]))
4272 self.cchDisplayed = offNewline + 1;
4273 offNewline = sFile.find('\n', self.cchDisplayed);
4274
4275 fRet = self.fSignalled;
4276 if not fLocked:
4277 self.unlockTask();
4278 return fRet;
4279
4280 # Our stuff.
4281 def getResult(self):
4282 """
4283 Returns the connected TXS session object on success.
4284 Returns None on failure or if the task has not yet completed.
4285 """
4286 self.oCv.acquire();
4287 sResult = self.sResult;
4288 self.oCv.release();
4289 return sResult;
4290
4291 def cancelTask(self):
4292 """ Cancels the task. """
4293 self.signalTask();
4294 return True;
4295
4296
4297 def monitorComRawFile(self, oSession, sComRawFile, cMsTimeout = 15*60000, asStopWords = None):
4298 """
4299 Monitors the COM output file for stop words (PASSED and FAILED by default).
4300
4301 Returns the stop word.
4302 Returns None on VM error and timeout.
4303 """
4304
4305 reporter.log2('monitorComRawFile: oSession=%s, cMsTimeout=%s, sComRawFile=%s' % (oSession, cMsTimeout, sComRawFile));
4306
4307 oMonitorTask = self.TxsMonitorComFile(sComRawFile, asStopWords);
4308 self.addTask(oMonitorTask);
4309
4310 cMsTimeout = self.adjustTimeoutMs(cMsTimeout);
4311 oTask = self.waitForTasks(cMsTimeout + 1);
4312 reporter.log2('monitorComRawFile: waitForTasks returned %s' % (oTask,));
4313
4314 if oTask is not oMonitorTask:
4315 oMonitorTask.cancelTask();
4316 self.removeTask(oMonitorTask);
4317
4318 oMonitorTask.pollTask();
4319 return oMonitorTask.getResult();
4320
4321
4322 def runVmAndMonitorComRawFile(self, sVmName, sComRawFile, cMsTimeout = 15*60000, asStopWords = None):
4323 """
4324 Runs the specified VM and monitors the given COM output file for stop
4325 words (PASSED and FAILED by default).
4326
4327 The caller is assumed to have configured the VM to use the given
4328 file. The method will take no action to verify this.
4329
4330 Returns the stop word.
4331 Returns None on VM error and timeout.
4332 """
4333
4334 # Start the VM.
4335 reporter.log('runVmAndMonitorComRawFile: Starting(/preparing) "%s" (timeout %s s)...' % (sVmName, cMsTimeout / 1000));
4336 reporter.flushall();
4337 oSession = self.startVmByName(sVmName);
4338 if oSession is not None:
4339 # Let it run and then terminate it.
4340 sRet = self.monitorComRawFile(oSession, sComRawFile, cMsTimeout, asStopWords);
4341 self.terminateVmBySession(oSession);
4342 else:
4343 sRet = None;
4344 return sRet;
4345
4346 #
4347 # Other stuff
4348 #
4349
4350 def waitForGAs(self,
4351 oSession, # type: vboxwrappers.SessionWrapper
4352 cMsTimeout = 120000, aenmWaitForRunLevels = None, aenmWaitForActive = None, aenmWaitForInactive = None):
4353 """
4354 Waits for the guest additions to enter a certain state.
4355
4356 aenmWaitForRunLevels - List of run level values to wait for (success if one matches).
4357 aenmWaitForActive - List facilities (type values) that must be active.
4358 aenmWaitForInactive - List facilities (type values) that must be inactive.
4359
4360 Defaults to wait for AdditionsRunLevelType_Userland if nothing else is given.
4361
4362 Returns True on success, False w/ error logging on timeout or failure.
4363 """
4364 reporter.log2('waitForGAs: oSession=%s, cMsTimeout=%s' % (oSession, cMsTimeout,));
4365
4366 #
4367 # Get IGuest:
4368 #
4369 try:
4370 oIGuest = oSession.o.console.guest;
4371 except:
4372 return reporter.errorXcpt();
4373
4374 #
4375 # Create a wait task:
4376 #
4377 from testdriver.vboxwrappers import AdditionsStatusTask;
4378 try:
4379 oGaStatusTask = AdditionsStatusTask(oSession = oSession,
4380 oIGuest = oIGuest,
4381 cMsTimeout = cMsTimeout,
4382 aenmWaitForRunLevels = aenmWaitForRunLevels,
4383 aenmWaitForActive = aenmWaitForActive,
4384 aenmWaitForInactive = aenmWaitForInactive);
4385 except:
4386 return reporter.errorXcpt();
4387
4388 #
4389 # Add the task and make sure the VM session is also present.
4390 #
4391 self.addTask(oGaStatusTask);
4392 fRemoveSession = self.addTask(oSession);
4393 oTask = self.waitForTasks(cMsTimeout + 1);
4394 reporter.log2('waitForGAs: returned %s (oGaStatusTask=%s, oSession=%s)' % (oTask, oGaStatusTask, oSession,));
4395 self.removeTask(oGaStatusTask);
4396 if fRemoveSession:
4397 self.removeTask(oSession);
4398
4399 #
4400 # Digest the result.
4401 #
4402 if oTask is oGaStatusTask:
4403 fSucceeded = oGaStatusTask.getResult();
4404 if fSucceeded is True:
4405 reporter.log('waitForGAs: Succeeded.');
4406 else:
4407 reporter.error('waitForGAs: Failed.');
4408 else:
4409 oGaStatusTask.cancelTask();
4410 if oTask is None:
4411 reporter.error('waitForGAs: Timed out.');
4412 elif oTask is oSession:
4413 oSession.reportPrematureTermination('waitForGAs: ');
4414 else:
4415 reporter.error('waitForGAs: unknown/wrong task %s' % (oTask,));
4416 fSucceeded = False;
4417 return fSucceeded;
4418
4419 @staticmethod
4420 def controllerTypeToName(eControllerType):
4421 """
4422 Translate a controller type to a standard controller name.
4423 """
4424 if eControllerType in (vboxcon.StorageControllerType_PIIX3, vboxcon.StorageControllerType_PIIX4,):
4425 sName = "IDE Controller";
4426 elif eControllerType == vboxcon.StorageControllerType_IntelAhci:
4427 sName = "SATA Controller";
4428 elif eControllerType == vboxcon.StorageControllerType_LsiLogicSas:
4429 sName = "SAS Controller";
4430 elif eControllerType in (vboxcon.StorageControllerType_LsiLogic, vboxcon.StorageControllerType_BusLogic,):
4431 sName = "SCSI Controller";
4432 elif eControllerType == vboxcon.StorageControllerType_NVMe:
4433 sName = "NVMe Controller";
4434 elif eControllerType == vboxcon.StorageControllerType_VirtioSCSI:
4435 sName = "VirtIO SCSI Controller";
4436 else:
4437 sName = "Storage Controller";
4438 return sName;
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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