VirtualBox

source: vbox/trunk/src/VBox/ValidationKit/testdriver/vboxwrappers.py

Last change on this file was 106061, checked in by vboxsync, 6 weeks ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 151.6 KB
Line 
1# -*- coding: utf-8 -*-
2# $Id: vboxwrappers.py 106061 2024-09-16 14:03:52Z vboxsync $
3# pylint: disable=too-many-lines
4
5"""
6VirtualBox Wrapper Classes
7"""
8
9__copyright__ = \
10"""
11Copyright (C) 2010-2024 Oracle and/or its affiliates.
12
13This file is part of VirtualBox base platform packages, as
14available from https://www.virtualbox.org.
15
16This program is free software; you can redistribute it and/or
17modify it under the terms of the GNU General Public License
18as published by the Free Software Foundation, in version 3 of the
19License.
20
21This program is distributed in the hope that it will be useful, but
22WITHOUT ANY WARRANTY; without even the implied warranty of
23MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24General Public License for more details.
25
26You should have received a copy of the GNU General Public License
27along with this program; if not, see <https://www.gnu.org/licenses>.
28
29The contents of this file may alternatively be used under the terms
30of the Common Development and Distribution License Version 1.0
31(CDDL), a copy of it is provided in the "COPYING.CDDL" file included
32in the VirtualBox distribution, in which case the provisions of the
33CDDL are applicable instead of those of the GPL.
34
35You may elect to license modified versions of this file under the
36terms and conditions of either the GPL or the CDDL or both.
37
38SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
39"""
40__version__ = "$Revision: 106061 $"
41
42
43# Standard Python imports.
44import os;
45import socket;
46import sys;
47import uuid;
48
49# Validation Kit imports.
50from common import utils;
51from common import netutils;
52from testdriver import base;
53from testdriver import reporter;
54from testdriver import txsclient;
55from testdriver import vboxcon;
56from testdriver import vbox;
57from testdriver.base import TdTaskBase;
58
59
60def _ControllerNameToBusAndType(sController):
61 """ Translate a controller name to a storage bus. """
62 if sController == "IDE Controller":
63 eBus = vboxcon.StorageBus_IDE;
64 eType = vboxcon.StorageControllerType_PIIX4;
65 elif sController == "SATA Controller":
66 eBus = vboxcon.StorageBus_SATA;
67 eType = vboxcon.StorageControllerType_IntelAhci;
68 elif sController == "Floppy Controller":
69 eType = vboxcon.StorageControllerType_I82078;
70 eBus = vboxcon.StorageBus_Floppy;
71 elif sController == "SAS Controller":
72 eBus = vboxcon.StorageBus_SAS;
73 eType = vboxcon.StorageControllerType_LsiLogicSas;
74 elif sController == "SCSI Controller":
75 eBus = vboxcon.StorageBus_SCSI;
76 eType = vboxcon.StorageControllerType_LsiLogic;
77 elif sController == "BusLogic SCSI Controller":
78 eBus = vboxcon.StorageBus_SCSI;
79 eType = vboxcon.StorageControllerType_BusLogic;
80 elif sController == "NVMe Controller":
81 eBus = vboxcon.StorageBus_PCIe;
82 eType = vboxcon.StorageControllerType_NVMe;
83 elif sController == "VirtIO SCSI Controller":
84 eBus = vboxcon.StorageBus_VirtioSCSI;
85 eType = vboxcon.StorageControllerType_VirtioSCSI;
86 else:
87 eBus = vboxcon.StorageBus_Null;
88 eType = vboxcon.StorageControllerType_Null;
89 return (eBus, eType);
90
91
92def _nameMachineState(eState):
93 """ Gets the name (string) of a machine state."""
94 if eState == vboxcon.MachineState_PoweredOff: return 'PoweredOff';
95 if eState == vboxcon.MachineState_Saved: return 'Saved';
96 if eState == vboxcon.MachineState_Teleported: return 'Teleported';
97 if eState == vboxcon.MachineState_Aborted: return 'Aborted';
98 if eState == vboxcon.MachineState_Running: return 'Running';
99 if eState == vboxcon.MachineState_Paused: return 'Paused';
100 if eState == vboxcon.MachineState_Stuck: return 'GuruMeditation';
101 if eState == vboxcon.MachineState_Teleporting: return 'Teleporting';
102 if eState == vboxcon.MachineState_LiveSnapshotting: return 'LiveSnapshotting';
103 if eState == vboxcon.MachineState_Starting: return 'Starting';
104 if eState == vboxcon.MachineState_Stopping: return 'Stopping';
105 if eState == vboxcon.MachineState_Saving: return 'Saving';
106 if eState == vboxcon.MachineState_Restoring: return 'Restoring';
107 if eState == vboxcon.MachineState_TeleportingPausedVM: return 'TeleportingPausedVM';
108 if eState == vboxcon.MachineState_TeleportingIn: return 'TeleportingIn';
109 if eState == vboxcon.MachineState_DeletingSnapshotOnline: return 'DeletingSnapshotOnline';
110 if eState == vboxcon.MachineState_DeletingSnapshotPaused: return 'DeletingSnapshotPaused';
111 if eState == vboxcon.MachineState_RestoringSnapshot: return 'RestoringSnapshot';
112 if eState == vboxcon.MachineState_DeletingSnapshot: return 'DeletingSnapshot';
113 if eState == vboxcon.MachineState_SettingUp: return 'SettingUp';
114 if hasattr(vboxcon, 'MachineState_FaultTolerantSyncing'):
115 if eState == vboxcon.MachineState_FaultTolerantSyncing: return 'FaultTolerantSyncing';
116 if hasattr(vboxcon, 'MachineState_AbortedSaved'): # since r147033 / 7.0
117 if eState == vboxcon.MachineState_AbortedSaved: return 'Aborted-Saved';
118 return 'Unknown-%s' % (eState,);
119
120
121class VirtualBoxWrapper(object): # pylint: disable=too-few-public-methods
122 """
123 Wrapper around the IVirtualBox object that adds some (hopefully) useful
124 utility methods
125
126 The real object can be accessed thru the o member. That said, members can
127 be accessed directly as well.
128 """
129
130 def __init__(self, oVBox, oVBoxMgr, fpApiVer, oTstDrv):
131 self.o = oVBox;
132 self.oVBoxMgr = oVBoxMgr;
133 self.fpApiVer = fpApiVer;
134 self.oTstDrv = oTstDrv;
135
136 def __getattr__(self, sName):
137 # Try ourselves first.
138 try:
139 oAttr = self.__dict__[sName];
140 except:
141 #try:
142 # oAttr = dir(self)[sName];
143 #except AttributeError:
144 oAttr = getattr(self.o, sName);
145 return oAttr;
146
147 #
148 # Utilities.
149 #
150
151 def registerDerivedEventHandler(self, oSubClass, dArgs = None):
152 """
153 Create an instance of the given VirtualBoxEventHandlerBase sub-class
154 and register it.
155
156 The new instance is returned on success. None is returned on error.
157 """
158 dArgsCopy = dArgs.copy() if dArgs is not None else {};
159 dArgsCopy['oVBox'] = self;
160 return oSubClass.registerDerivedEventHandler(self.oVBoxMgr, self.fpApiVer, oSubClass, dArgsCopy,
161 self.o, 'IVirtualBox', 'IVirtualBoxCallback');
162
163 def deleteHdByLocation(self, sHdLocation):
164 """
165 Deletes a disk image from the host, given it's location.
166 Returns True on success and False on failure. Error information is logged.
167 """
168 try:
169 oIMedium = self.o.findHardDisk(sHdLocation);
170 except:
171 try:
172 if self.fpApiVer >= 4.1:
173 oIMedium = self.o.openMedium(sHdLocation, vboxcon.DeviceType_HardDisk,
174 vboxcon.AccessMode_ReadWrite, False);
175 elif self.fpApiVer >= 4.0:
176 oIMedium = self.o.openMedium(sHdLocation, vboxcon.DeviceType_HardDisk,
177 vboxcon.AccessMode_ReadWrite);
178 else:
179 oIMedium = self.o.openHardDisk(sHdLocation, vboxcon.AccessMode_ReadOnly, False, "", False, "");
180 except:
181 return reporter.errorXcpt('failed to open hd "%s"' % (sHdLocation));
182 return self.deleteHdByMedium(oIMedium)
183
184 def deleteHdByMedium(self, oIMedium):
185 """
186 Deletes a disk image from the host, given an IMedium reference.
187 Returns True on success and False on failure. Error information is logged.
188 """
189 try: oProgressCom = oIMedium.deleteStorage();
190 except: return reporter.errorXcpt('deleteStorage() for disk %s failed' % (oIMedium,));
191 try: oProgress = ProgressWrapper(oProgressCom, self.oVBoxMgr, self.oTstDrv, 'delete disk %s' % (oIMedium.location));
192 except: return reporter.errorXcpt();
193 oProgress.wait();
194 oProgress.logResult();
195 return oProgress.isSuccess();
196
197
198
199class ProgressWrapper(TdTaskBase):
200 """
201 Wrapper around a progress object for making it a task and providing useful
202 utility methods.
203 The real progress object can be accessed thru the o member.
204 """
205
206 def __init__(self, oProgress, oVBoxMgr, oTstDrv, sName):
207 TdTaskBase.__init__(self, utils.getCallerName());
208 self.o = oProgress;
209 self.oVBoxMgr = oVBoxMgr;
210 self.oTstDrv = oTstDrv;
211 self.sName = sName;
212
213 def toString(self):
214 return '<%s sName=%s, oProgress=%s >' \
215 % (TdTaskBase.toString(self), self.sName, self.o);
216
217 #
218 # TdTaskBase overrides.
219 #
220
221 def pollTask(self, fLocked = False):
222 """
223 Overrides TdTaskBase.pollTask().
224
225 This method returns False until the progress object has completed.
226 """
227 self.doQuickApiTest();
228 try:
229 try:
230 if self.o.completed:
231 return True;
232 except:
233 pass;
234 finally:
235 self.oTstDrv.processPendingEvents();
236 return False;
237
238 def waitForTask(self, cMsTimeout = 0):
239 """
240 Overrides TdTaskBase.waitForTask().
241 Process XPCOM/COM events while waiting.
242 """
243 msStart = base.timestampMilli();
244 fState = self.pollTask(False);
245 while not fState:
246 cMsElapsed = base.timestampMilli() - msStart;
247 if cMsElapsed > cMsTimeout:
248 break;
249 cMsToWait = cMsTimeout - cMsElapsed;
250 cMsToWait = min(cMsToWait, 500);
251 try:
252 self.o.waitForCompletion(cMsToWait);
253 except KeyboardInterrupt: raise;
254 except: pass;
255 if self.fnProcessEvents:
256 self.fnProcessEvents();
257 reporter.doPollWork('ProgressWrapper.waitForTask');
258 fState = self.pollTask(False);
259 return fState;
260
261 #
262 # Utility methods.
263 #
264
265 def isSuccess(self):
266 """
267 Tests if the progress object completed successfully.
268 Returns True on success, False on failure or incomplete.
269 """
270 if not self.isCompleted():
271 return False;
272 return self.getResult() >= 0;
273
274 def isCompleted(self):
275 """
276 Wrapper around IProgress.completed.
277 """
278 return self.pollTask();
279
280 def isCancelable(self):
281 """
282 Wrapper around IProgress.cancelable.
283 """
284 try:
285 fRc = self.o.cancelable;
286 except:
287 reporter.logXcpt();
288 fRc = False;
289 return fRc;
290
291 def wasCanceled(self):
292 """
293 Wrapper around IProgress.canceled.
294 """
295 try:
296 fRc = self.o.canceled;
297 except:
298 reporter.logXcpt(self.sName);
299 fRc = False;
300 return fRc;
301
302 def cancel(self):
303 """
304 Wrapper around IProgress.cancel()
305 Returns True on success, False on failure (logged as error).
306 """
307 try:
308 self.o.cancel();
309 except:
310 reporter.errorXcpt(self.sName);
311 return False;
312 return True;
313
314 def getResult(self):
315 """
316 Wrapper around IProgress.resultCode.
317 """
318 try:
319 iRc = self.o.resultCode;
320 except:
321 reporter.logXcpt(self.sName);
322 iRc = -1;
323 return iRc;
324
325 def getErrInfoResultCode(self):
326 """
327 Wrapper around IProgress.errorInfo.resultCode.
328
329 Returns the string on success, -1 on bad objects (logged as error), and
330 -2 on missing errorInfo object.
331 """
332 iRc = -1;
333 try:
334 oErrInfo = self.o.errorInfo;
335 except:
336 reporter.errorXcpt(self.sName);
337 else:
338 if oErrInfo is None:
339 iRc = -2;
340 else:
341 try:
342 iRc = oErrInfo.resultCode;
343 except:
344 reporter.errorXcpt();
345 return iRc;
346
347 def getErrInfoText(self):
348 """
349 Wrapper around IProgress.errorInfo.text.
350
351 Returns the string on success, None on failure. Missing errorInfo is
352 not logged as an error, all other failures are.
353 """
354 sText = None;
355 try:
356 oErrInfo = self.o.errorInfo;
357 except:
358 reporter.log2Xcpt(self.sName);
359 else:
360 if oErrInfo is not None:
361 try:
362 sText = oErrInfo.text;
363 except:
364 reporter.errorXcpt();
365 return sText;
366
367 def stringifyErrorInfo(self):
368 """
369 Formats IProgress.errorInfo into a string.
370 """
371 try:
372 oErrInfo = self.o.errorInfo;
373 except:
374 reporter.logXcpt(self.sName);
375 sErr = 'no error info';
376 else:
377 sErr = vbox.stringifyErrorInfo(oErrInfo);
378 return sErr;
379
380 def stringifyResult(self):
381 """
382 Stringify the result.
383 """
384 if self.isCompleted():
385 if self.wasCanceled():
386 sRet = 'Progress %s: Canceled, hrc=%s' % (self.sName, vbox.ComError.toString(self.getResult()));
387 elif self.getResult() == 0:
388 sRet = 'Progress %s: Success' % (self.sName,);
389 elif self.getResult() > 0:
390 sRet = 'Progress %s: Success (hrc=%s)' % (self.sName, vbox.ComError.toString(self.getResult()));
391 else:
392 sRet = 'Progress %s: Failed! %s' % (self.sName, self.stringifyErrorInfo());
393 else:
394 sRet = 'Progress %s: Not completed yet...' % (self.sName);
395 return sRet;
396
397 def logResult(self, fIgnoreErrors = False):
398 """
399 Logs the result, failure logged as error unless fIgnoreErrors is True.
400 Return True on success, False on failure (and fIgnoreErrors is false).
401 """
402 sText = self.stringifyResult();
403 if self.isCompleted() and self.getResult() < 0 and fIgnoreErrors is False:
404 return reporter.error(sText);
405 reporter.log(sText);
406 return True;
407
408 def waitOnProgress(self, cMsInterval = 1000):
409 """
410 See vbox.TestDriver.waitOnProgress.
411 """
412 self.doQuickApiTest();
413 return self.oTstDrv.waitOnProgress(self.o, cMsInterval);
414
415 def wait(self, cMsTimeout = 60000, fErrorOnTimeout = True, cMsInterval = 1000):
416 """
417 Wait on the progress object for a while.
418
419 Returns the resultCode of the progress object if completed.
420 Returns -1 on timeout, logged as error if fErrorOnTimeout is set.
421 Returns -2 is the progress object is invalid or waitForCompletion
422 fails (logged as errors).
423 """
424 msStart = base.timestampMilli();
425 while True:
426 self.oTstDrv.processPendingEvents();
427 self.doQuickApiTest();
428 try:
429 if self.o.completed:
430 break;
431 except:
432 reporter.errorXcpt(self.sName);
433 return -2;
434 self.oTstDrv.processPendingEvents();
435
436 cMsElapsed = base.timestampMilli() - msStart;
437 if cMsElapsed > cMsTimeout:
438 if fErrorOnTimeout:
439 reporter.error('Timing out after waiting for %u s on "%s"' % (cMsTimeout / 1000, self.sName))
440 return -1;
441
442 try:
443 self.o.waitForCompletion(cMsInterval);
444 except:
445 reporter.errorXcpt(self.sName);
446 return -2;
447 reporter.doPollWork('ProgressWrapper.wait');
448
449 try:
450 rc = self.o.resultCode;
451 except:
452 rc = -2;
453 reporter.errorXcpt(self.sName);
454 self.oTstDrv.processPendingEvents();
455 return rc;
456
457 def waitForOperation(self, iOperation, cMsTimeout = 60000, fErrorOnTimeout = True, cMsInterval = 1000, \
458 fIgnoreErrors = False):
459 """
460 Wait for the completion of a operation.
461
462 Negative iOperation values are relative to operationCount (this
463 property may changed at runtime).
464
465 Returns 0 if the operation completed normally.
466 Returns -1 on timeout, logged as error if fErrorOnTimeout is set.
467 Returns -2 is the progress object is invalid or waitForCompletion
468 fails (logged as errors).
469 Returns -3 if if the operation completed with an error, this is logged
470 as an error.
471 """
472 msStart = base.timestampMilli();
473 while True:
474 self.oTstDrv.processPendingEvents();
475 self.doQuickApiTest();
476 try:
477 iCurrentOperation = self.o.operation;
478 cOperations = self.o.operationCount;
479 if iOperation >= 0:
480 iRealOperation = iOperation;
481 else:
482 iRealOperation = cOperations + iOperation;
483
484 if iCurrentOperation > iRealOperation:
485 return 0;
486 if iCurrentOperation == iRealOperation \
487 and iRealOperation >= cOperations - 1 \
488 and self.o.completed:
489 if self.o.resultCode < 0:
490 self.logResult(fIgnoreErrors);
491 return -3;
492 return 0;
493 except:
494 if fIgnoreErrors:
495 reporter.logXcpt();
496 else:
497 reporter.errorXcpt();
498 return -2;
499 self.oTstDrv.processPendingEvents();
500
501 cMsElapsed = base.timestampMilli() - msStart;
502 if cMsElapsed > cMsTimeout:
503 if fErrorOnTimeout:
504 if fIgnoreErrors:
505 reporter.log('Timing out after waiting for %s s on "%s" operation %d' \
506 % (cMsTimeout / 1000, self.sName, iOperation))
507 else:
508 reporter.error('Timing out after waiting for %s s on "%s" operation %d' \
509 % (cMsTimeout / 1000, self.sName, iOperation))
510 return -1;
511
512 try:
513 self.o.waitForOperationCompletion(iRealOperation, cMsInterval);
514 except:
515 if fIgnoreErrors:
516 reporter.logXcpt(self.sName);
517 else:
518 reporter.errorXcpt(self.sName);
519 return -2;
520 reporter.doPollWork('ProgressWrapper.waitForOperation');
521 # Not reached.
522 return -3; # Make pylin happy (for now).
523
524 def doQuickApiTest(self):
525 """
526 Queries everything that is stable and easy to get at and checks that
527 they don't throw errors.
528 """
529 if True is True: # pylint: disable=comparison-with-itself,comparison-of-constants
530 try:
531 iPct = self.o.operationPercent;
532 sDesc = self.o.description;
533 fCancelable = self.o.cancelable;
534 cSecsRemain = self.o.timeRemaining;
535 fCanceled = self.o.canceled;
536 fCompleted = self.o.completed;
537 iOp = self.o.operation;
538 cOps = self.o.operationCount;
539 iOpPct = self.o.operationPercent;
540 sOpDesc = self.o.operationDescription;
541 except:
542 reporter.errorXcpt('%s: %s' % (self.sName, self.o,));
543 return False;
544 try:
545 # Very noisy -- only enable for debugging purposes.
546 #reporter.log2('%s: op=%u/%u/%s: %u%%; total=%u%% cancel=%s/%s compl=%s rem=%us; desc=%s' \
547 # % (self.sName, iOp, cOps, sOpDesc, iOpPct, iPct, fCanceled, fCancelable, fCompleted, \
548 # cSecsRemain, sDesc));
549 _ = iPct; _ = sDesc; _ = fCancelable; _ = cSecsRemain; _ = fCanceled; _ = fCompleted; _ = iOp;
550 _ = cOps; _ = iOpPct; _ = sOpDesc;
551 except:
552 reporter.errorXcpt();
553 return False;
554
555 return True;
556
557
558class SessionWrapper(TdTaskBase):
559 """
560 Wrapper around a machine session. The real session object can be accessed
561 thru the o member (short is good, right :-).
562 """
563
564 def __init__(self, oSession, oVM, oVBox, oVBoxMgr, oTstDrv, fRemoteSession, sFallbackName = None, sLogFile = None):
565 """
566 Initializes the session wrapper.
567 """
568 TdTaskBase.__init__(self, utils.getCallerName());
569 self.o = oSession;
570 self.oVBox = oVBox;
571 self.oVBoxMgr = oVBoxMgr;
572 self.oVM = oVM; # Not the session machine. Useful backdoor...
573 self.oTstDrv = oTstDrv;
574 self.fpApiVer = oTstDrv.fpApiVer;
575 self.fRemoteSession = fRemoteSession;
576 self.sLogFile = sLogFile;
577 self.oConsoleEventHandler = None;
578 self.uPid = None;
579 self.fPidFile = True;
580 self.fHostMemoryLow = False; # see signalHostMemoryLow; read-only for outsiders.
581
582 try:
583 self.sName = oSession.machine.name;
584 except:
585 if sFallbackName is not None:
586 self.sName = sFallbackName;
587 else:
588 try: self.sName = str(oSession.machine);
589 except: self.sName = 'is-this-vm-already-off'
590
591 try:
592 self.sUuid = oSession.machine.id;
593 except:
594 self.sUuid = None;
595
596 # Try cache the SessionPID.
597 self.getPid();
598
599 def __del__(self):
600 """
601 Destructor that makes sure the callbacks are deregistered and
602 that the session is closed.
603 """
604 self.deregisterEventHandlerForTask();
605
606 if self.o is not None:
607 try:
608 self.close();
609 reporter.log('close session %s' % (self.o));
610 except:
611 pass;
612 self.o = None;
613
614 TdTaskBase.__del__(self);
615
616 def toString(self):
617 return '<%s: sUuid=%s, sName=%s, uPid=%s, sDbgCreated=%s, fRemoteSession=%s, oSession=%s,' \
618 ' oConsoleEventHandler=%s, oVM=%s >' \
619 % (type(self).__name__, self.sUuid, self.sName, self.uPid, self.sDbgCreated, self.fRemoteSession,
620 self.o, self.oConsoleEventHandler, self.oVM,);
621
622 def __str__(self):
623 return self.toString();
624
625 #
626 # TdTaskBase overrides.
627 #
628
629 def __pollTask(self):
630 """ Internal poller """
631 # Poll for events after doing the remote GetState call, otherwise we
632 # might end up sleepless because XPCOM queues a cleanup event.
633 try:
634 try:
635 eState = self.o.machine.state;
636 except Exception as oXcpt:
637 if vbox.ComError.notEqual(oXcpt, vbox.ComError.E_UNEXPECTED):
638 reporter.logXcpt();
639 return True;
640 finally:
641 self.oTstDrv.processPendingEvents();
642
643 # Switch
644 if eState == vboxcon.MachineState_Running:
645 return False;
646 if eState == vboxcon.MachineState_Paused:
647 return False;
648 if eState == vboxcon.MachineState_Teleporting:
649 return False;
650 if eState == vboxcon.MachineState_LiveSnapshotting:
651 return False;
652 if eState == vboxcon.MachineState_Starting:
653 return False;
654 if eState == vboxcon.MachineState_Stopping:
655 return False;
656 if eState == vboxcon.MachineState_Saving:
657 return False;
658 if eState == vboxcon.MachineState_Restoring:
659 return False;
660 if eState == vboxcon.MachineState_TeleportingPausedVM:
661 return False;
662 if eState == vboxcon.MachineState_TeleportingIn:
663 return False;
664
665 # *Beeep* fudge!
666 if self.fpApiVer < 3.2 \
667 and eState == vboxcon.MachineState_PoweredOff \
668 and self.getAgeAsMs() < 3000:
669 return False;
670
671 reporter.log('SessionWrapper::pollTask: eState=%s' % (eState));
672 return True;
673
674
675 def pollTask(self, fLocked = False):
676 """
677 Overrides TdTaskBase.pollTask().
678
679 This method returns False while the VM is online and running normally.
680 """
681
682 # Call super to check if the task was signalled by runtime error or similar,
683 # if not then check the VM state via __pollTask.
684 fRc = super(SessionWrapper, self).pollTask(fLocked);
685 if not fRc:
686 fRc = self.__pollTask();
687
688 # HACK ALERT: Lazily try registering the console event handler if
689 # we're not ready.
690 if not fRc and self.oConsoleEventHandler is None:
691 self.registerEventHandlerForTask();
692
693 # HACK ALERT: Lazily try get the PID and add it to the PID file.
694 if not fRc and self.uPid is None:
695 self.getPid();
696
697 return fRc;
698
699 def waitForTask(self, cMsTimeout = 0):
700 """
701 Overrides TdTaskBase.waitForTask().
702 Process XPCOM/COM events while waiting.
703 """
704 msStart = base.timestampMilli();
705 fState = self.pollTask(False);
706 while not fState:
707 cMsElapsed = base.timestampMilli() - msStart;
708 if cMsElapsed > cMsTimeout:
709 break;
710 cMsSleep = cMsTimeout - cMsElapsed;
711 cMsSleep = min(cMsSleep, 10000);
712 try: self.oVBoxMgr.waitForEvents(cMsSleep);
713 except KeyboardInterrupt: raise;
714 except: pass;
715 if self.fnProcessEvents:
716 self.fnProcessEvents();
717 reporter.doPollWork('SessionWrapper.waitForTask');
718 fState = self.pollTask(False);
719 return fState;
720
721 def setTaskOwner(self, oOwner):
722 """
723 HACK ALERT!
724 Overrides TdTaskBase.setTaskOwner() so we can try call
725 registerEventHandlerForTask() again when when the testdriver calls
726 addTask() after VM has been spawned. Related to pollTask() above.
727
728 The testdriver must not add the task too early for this to work!
729 """
730 if oOwner is not None:
731 self.registerEventHandlerForTask()
732 return TdTaskBase.setTaskOwner(self, oOwner);
733
734
735 #
736 # Task helpers.
737 #
738
739 def registerEventHandlerForTask(self):
740 """
741 Registers the console event handlers for working the task state.
742 """
743 if self.oConsoleEventHandler is not None:
744 return True;
745 self.oConsoleEventHandler = self.registerDerivedEventHandler(vbox.SessionConsoleEventHandler, {}, False);
746 return self.oConsoleEventHandler is not None;
747
748 def deregisterEventHandlerForTask(self):
749 """
750 Deregisters the console event handlers.
751 """
752 if self.oConsoleEventHandler is not None:
753 self.oConsoleEventHandler.unregister();
754 self.oConsoleEventHandler = None;
755
756 def signalHostMemoryLow(self):
757 """
758 Used by a runtime error event handler to indicate that we're low on memory.
759 Signals the task.
760 """
761 self.fHostMemoryLow = True;
762 self.signalTask();
763 return True;
764
765 def needsPoweringOff(self):
766 """
767 Examins the machine state to see if the VM needs powering off.
768 """
769 try:
770 try:
771 eState = self.o.machine.state;
772 except Exception as oXcpt:
773 if vbox.ComError.notEqual(oXcpt, vbox.ComError.E_UNEXPECTED):
774 reporter.logXcpt();
775 return False;
776 finally:
777 self.oTstDrv.processPendingEvents();
778
779 # Switch
780 if eState == vboxcon.MachineState_Running:
781 return True;
782 if eState == vboxcon.MachineState_Paused:
783 return True;
784 if eState == vboxcon.MachineState_Stuck:
785 return True;
786 if eState == vboxcon.MachineState_Teleporting:
787 return True;
788 if eState == vboxcon.MachineState_LiveSnapshotting:
789 return True;
790 if eState == vboxcon.MachineState_Starting:
791 return True;
792 if eState == vboxcon.MachineState_Saving:
793 return True;
794 if eState == vboxcon.MachineState_Restoring:
795 return True;
796 if eState == vboxcon.MachineState_TeleportingPausedVM:
797 return True;
798 if eState == vboxcon.MachineState_TeleportingIn:
799 return True;
800 if hasattr(vboxcon, 'MachineState_FaultTolerantSyncing'):
801 if eState == vboxcon.MachineState_FaultTolerantSyncing:
802 return True;
803 return False;
804
805 def assertPoweredOff(self):
806 """
807 Asserts that the VM is powered off, reporting an error if not.
808 Returns True if powered off, False + error msg if not.
809 """
810 try:
811 try:
812 eState = self.oVM.state;
813 except Exception:
814 reporter.errorXcpt();
815 return True;
816 finally:
817 self.oTstDrv.processPendingEvents();
818
819 if eState == vboxcon.MachineState_PoweredOff:
820 return True;
821 reporter.error('Expected machine state "PoweredOff", machine is in the "%s" state instead.'
822 % (_nameMachineState(eState),));
823 return False;
824
825 def getMachineStateWithName(self):
826 """
827 Gets the current machine state both as a constant number/whatever and
828 as a human readable string. On error, the constants will be set to
829 None and the string will be the error message.
830 """
831 try:
832 eState = self.oVM.state;
833 except:
834 return (None, '[error getting state: %s]' % (self.oVBoxMgr.xcptToString(),));
835 finally:
836 self.oTstDrv.processPendingEvents();
837 return (eState, _nameMachineState(eState));
838
839 def reportPrematureTermination(self, sPrefix = ''):
840 """
841 Reports a premature virtual machine termination.
842 Returns False to facilitate simpler error paths.
843 """
844
845 reporter.error(sPrefix + 'The virtual machine terminated prematurely!!');
846 (enmState, sStateNm) = self.getMachineStateWithName();
847 reporter.error(sPrefix + 'Machine state: %s' % (sStateNm,));
848
849 if enmState is not None \
850 and enmState == vboxcon.MachineState_Aborted \
851 and self.uPid is not None:
852 #
853 # Look for process crash info.
854 #
855 def addCrashFile(sLogFile, fBinary):
856 """ processCollectCrashInfo callback. """
857 reporter.addLogFile(sLogFile, 'crash/dump/vm' if fBinary else 'crash/report/vm');
858 utils.processCollectCrashInfo(self.uPid, reporter.log, addCrashFile);
859
860 return False;
861
862
863
864 #
865 # ISession / IMachine / ISomethingOrAnother wrappers.
866 #
867
868 def close(self):
869 """
870 Closes the session if it's open and removes it from the
871 vbox.TestDriver.aoRemoteSessions list.
872 Returns success indicator.
873 """
874 fRc = True;
875 if self.o is not None:
876 # Get the pid in case we need to kill the process later on.
877 self.getPid();
878
879 # Try close it.
880 try:
881 if self.fpApiVer < 3.3:
882 self.o.close();
883 else:
884 self.o.unlockMachine();
885 self.o = None;
886 except KeyboardInterrupt:
887 raise;
888 except:
889 # Kludge to ignore VBoxSVC's closing of our session when the
890 # direct session closes / VM process terminates. Fun!
891 try: fIgnore = self.o.state == vboxcon.SessionState_Unlocked;
892 except: fIgnore = False;
893 if fIgnore:
894 self.o = None; # Must prevent a retry during GC.
895 else:
896 reporter.errorXcpt('ISession::unlockMachine failed on %s' % (self.o));
897 fRc = False;
898
899 # Remove it from the remote session list if applicable (not 100% clean).
900 if fRc and self.fRemoteSession:
901 try:
902 if self in self.oTstDrv.aoRemoteSessions:
903 reporter.log2('SessionWrapper::close: Removing myself from oTstDrv.aoRemoteSessions');
904 self.oTstDrv.aoRemoteSessions.remove(self)
905 except:
906 reporter.logXcpt();
907
908 if self.uPid is not None and self.fPidFile:
909 self.oTstDrv.pidFileRemove(self.uPid);
910 self.fPidFile = False;
911
912 # It's only logical to deregister the event handler after the session
913 # is closed. It also avoids circular references between the session
914 # and the listener, which causes trouble with garbage collection.
915 self.deregisterEventHandlerForTask();
916
917 self.oTstDrv.processPendingEvents();
918 return fRc;
919
920 def saveSettings(self, fClose = False):
921 """
922 Saves the settings and optionally closes the session.
923 Returns success indicator.
924 """
925 try:
926 try:
927 self.o.machine.saveSettings();
928 except:
929 reporter.errorXcpt('saveSettings failed on %s' % (self.o));
930 return False;
931 finally:
932 self.oTstDrv.processPendingEvents();
933 if fClose:
934 return self.close();
935 return True;
936
937 def discardSettings(self, fClose = False):
938 """
939 Discards the settings and optionally closes the session.
940 """
941 try:
942 try:
943 self.o.machine.discardSettings();
944 except:
945 reporter.errorXcpt('discardSettings failed on %s' % (self.o));
946 return False;
947 finally:
948 self.oTstDrv.processPendingEvents();
949 if fClose:
950 return self.close();
951 return True;
952
953 def isPlatformArch(self, enmPlatformArch):
954 """
955 Returns if the machine is of the given platform architecture or not.
956 """
957 if not self.o:
958 return False;
959 if self.fpApiVer >= 7.1:
960 return self.o.machine.platform.architecture == enmPlatformArch;
961 return enmPlatformArch == vboxcon.PlatformArchitecture_x86; # VBox < 7.1 only supported x86.
962
963 def isPlatformARM(self):
964 """
965 Returns if the machine is of the ARM platform architecture or not.
966 """
967 if self.fpApiVer >= 7.1:
968 return self.isPlatformArch(vboxcon.PlatformArchitecture_ARM);
969 return False; # For VBox < 7.1 this always is false (x86 only).
970
971 def isPlatformX86(self):
972 """
973 Returns if the machine is of the x86 platform architecture or not.
974 """
975 if self.fpApiVer >= 7.1:
976 return self.isPlatformArch(vboxcon.PlatformArchitecture_x86);
977 return True; # For VBox < 7.1 this always is true (x86 only).
978
979 def enableVirtExX86(self, fEnable):
980 """
981 Enables or disables AMD-V/VT-x. x86 only.
982 Returns True on success and False on failure. Error information is logged.
983
984 Ignored on non-x86 platform architectures.
985 """
986 if not self.isPlatformX86(): return True;
987 # Enable/disable it.
988 fRc = True;
989 try:
990 if self.fpApiVer >= 7.1:
991 self.o.machine.platform.x86.setHWVirtExProperty(vboxcon.HWVirtExPropertyType_Enabled, fEnable);
992 else:
993 self.o.machine.setHWVirtExProperty(vboxcon.HWVirtExPropertyType_Enabled, fEnable);
994 except:
995 reporter.errorXcpt('failed to set HWVirtExPropertyType_Enabled=%s for "%s"' % (fEnable, self.sName));
996 fRc = False;
997 else:
998 reporter.log('set HWVirtExPropertyType_Enabled=%s for "%s"' % (fEnable, self.sName));
999
1000 # Force/unforce it.
1001 if fRc and hasattr(vboxcon, 'HWVirtExPropertyType_Force'):
1002 try:
1003 if self.fpApiVer >= 7.1:
1004 self.o.machine.platform.x86.setHWVirtExProperty(vboxcon.HWVirtExPropertyType_Force, fEnable);
1005 else:
1006 self.o.machine.setHWVirtExProperty(vboxcon.HWVirtExPropertyType_Force, fEnable);
1007 except:
1008 reporter.errorXcpt('failed to set HWVirtExPropertyType_Force=%s for "%s"' % (fEnable, self.sName));
1009 fRc = False;
1010 else:
1011 reporter.log('set HWVirtExPropertyType_Force=%s for "%s"' % (fEnable, self.sName));
1012 else:
1013 reporter.log('Warning! vboxcon has no HWVirtExPropertyType_Force attribute.');
1014 ## @todo Modify CFGM to do the same for old VBox versions?
1015
1016 self.oTstDrv.processPendingEvents();
1017 return fRc;
1018
1019 def enableNestedPagingX86(self, fEnable):
1020 """
1021 Enables or disables nested paging. x86 only.
1022 Returns True on success and False on failure. Error information is logged.
1023
1024 Ignored on non-x86 platform architectures.
1025 """
1026 if not self.isPlatformX86(): return True;
1027 ## @todo Add/remove force CFGM thing, we don't want fallback logic when testing.
1028 fRc = True;
1029 try:
1030 if self.fpApiVer >= 7.1:
1031 self.o.machine.platform.x86.setHWVirtExProperty(vboxcon.HWVirtExPropertyType_NestedPaging, fEnable);
1032 else:
1033 self.o.machine.setHWVirtExProperty(vboxcon.HWVirtExPropertyType_NestedPaging, fEnable);
1034 except:
1035 reporter.errorXcpt('failed to set HWVirtExPropertyType_NestedPaging=%s for "%s"' % (fEnable, self.sName));
1036 fRc = False;
1037 else:
1038 reporter.log('set HWVirtExPropertyType_NestedPaging=%s for "%s"' % (fEnable, self.sName));
1039 self.oTstDrv.processPendingEvents();
1040 return fRc;
1041
1042 def enableLongModeX86(self, fEnable):
1043 """
1044 Enables or disables LongMode. x86 only.
1045 Returns True on success and False on failure. Error information is logged.
1046
1047 Ignored on non-x86 platform architectures.
1048 """
1049 if not self.isPlatformX86(): return True;
1050 # Supported.
1051 if self.fpApiVer < 4.2 or not hasattr(vboxcon, 'HWVirtExPropertyType_LongMode'):
1052 return True;
1053
1054 # Enable/disable it.
1055 fRc = True;
1056 try:
1057 if self.fpApiVer >= 7.1:
1058 self.o.machine.platform.x86.setCPUProperty(vboxcon.CPUPropertyTypeX86_LongMode, fEnable);
1059 else:
1060 self.o.machine.setCPUProperty(vboxcon.CPUPropertyType_LongMode, fEnable);
1061 except:
1062 reporter.errorXcpt('failed to set CPUPropertyType_LongMode=%s for "%s"' % (fEnable, self.sName));
1063 fRc = False;
1064 else:
1065 reporter.log('set CPUPropertyType_LongMode=%s for "%s"' % (fEnable, self.sName));
1066 self.oTstDrv.processPendingEvents();
1067 return fRc;
1068
1069 def enableNestedHwVirtX86(self, fEnable):
1070 """
1071 Enables or disables Nested Hardware-Virtualization. x86 only.
1072 Returns True on success and False on failure. Error information is logged.
1073
1074 Ignored on non-x86 platform architectures.
1075 """
1076 if not self.isPlatformX86(): return True;
1077 # Supported.
1078 if self.fpApiVer < 5.3:
1079 return True;
1080 if self.fpApiVer < 7.1 and not hasattr(vboxcon, 'CPUPropertyType_HWVirt'):
1081 return True;
1082 if self.fpApiVer >= 7.1 and not hasattr(vboxcon, 'CPUPropertyTypeX86_HWVirt'):
1083 return True;
1084
1085 # Enable/disable it.
1086 fRc = True;
1087 try:
1088 if self.fpApiVer >= 7.1:
1089 self.o.machine.platform.x86.setCPUProperty(vboxcon.CPUPropertyTypeX86_HWVirt, fEnable);
1090 else:
1091 self.o.machine.setCPUProperty(vboxcon.CPUPropertyType_HWVirt, fEnable);
1092 except:
1093 reporter.errorXcpt('failed to set CPUPropertyType_HWVirt=%s for "%s"' % (fEnable, self.sName));
1094 fRc = False;
1095 else:
1096 reporter.log('set CPUPropertyType_HWVirt=%s for "%s"' % (fEnable, self.sName));
1097 self.oTstDrv.processPendingEvents();
1098 return fRc;
1099
1100 def enablePaeX86(self, fEnable):
1101 """
1102 Enables or disables PAE. x86 only.
1103 Returns True on success and False on failure. Error information is logged.
1104
1105 Ignored on non-x86 platform architectures.
1106 """
1107 if not self.isPlatformX86(): return True;
1108 fRc = True;
1109 try:
1110 if self.fpApiVer >= 7.1:
1111 self.o.machine.platform.x86.setCPUProperty(vboxcon.CPUPropertyTypeX86_PAE, fEnable);
1112 elif self.fpApiVer >= 3.2: # great, ain't it?
1113 self.o.machine.setCPUProperty(vboxcon.CPUPropertyType_PAE, fEnable);
1114 else:
1115 self.o.machine.setCpuProperty(vboxcon.CpuPropertyType_PAE, fEnable);
1116 except:
1117 reporter.errorXcpt('failed to set CPUPropertyType_PAE=%s for "%s"' % (fEnable, self.sName));
1118 fRc = False;
1119 else:
1120 reporter.log('set CPUPropertyType_PAE=%s for "%s"' % (fEnable, self.sName));
1121 self.oTstDrv.processPendingEvents();
1122 return fRc;
1123
1124 def enableIoApic(self, fEnable):
1125 """
1126 Enables or disables the IO-APIC.
1127 Returns True on success and False on failure. Error information is logged.
1128 """
1129 fRc = True;
1130 try:
1131 if self.fpApiVer >= 7.1:
1132 self.o.machine.firmwareSettings.IOAPICEnabled = fEnable;
1133 else:
1134 self.o.machine.BIOSSettings.IOAPICEnabled = fEnable;
1135 except:
1136 reporter.errorXcpt('failed to set firmwareSettings.IOAPICEnabled=%s for "%s"' % (fEnable, self.sName));
1137 fRc = False;
1138 else:
1139 reporter.log('set firmwareSettings.IOAPICEnabled=%s for "%s"' % (fEnable, self.sName));
1140 self.oTstDrv.processPendingEvents();
1141 return fRc;
1142
1143 def enableHpetX86(self, fEnable):
1144 """
1145 Enables or disables the HPET. x86 only.
1146 Returns True on success and False on failure. Error information is logged.
1147
1148 Ignored on non-x86 platform architectures.
1149 """
1150 if not self.isPlatformX86(): return True;
1151 fRc = True;
1152 try:
1153 if self.fpApiVer >= 7.1:
1154 self.o.machine.platform.x86.HPETEnabled = fEnable;
1155 elif self.fpApiVer >= 4.2:
1156 self.o.machine.HPETEnabled = fEnable;
1157 else:
1158 self.o.machine.hpetEnabled = fEnable;
1159 except:
1160 reporter.errorXcpt('failed to set HpetEnabled=%s for "%s"' % (fEnable, self.sName));
1161 fRc = False;
1162 else:
1163 reporter.log('set HpetEnabled=%s for "%s"' % (fEnable, self.sName));
1164 self.oTstDrv.processPendingEvents();
1165 return fRc;
1166
1167 def enableUsbHid(self, fEnable):
1168 """
1169 Enables or disables the USB HID.
1170 Returns True on success and False on failure. Error information is logged.
1171 """
1172 fRc = True;
1173 try:
1174 if fEnable:
1175 if self.fpApiVer >= 4.3:
1176 cOhciCtls = self.o.machine.getUSBControllerCountByType(vboxcon.USBControllerType_OHCI);
1177 if cOhciCtls == 0:
1178 self.o.machine.addUSBController('OHCI', vboxcon.USBControllerType_OHCI);
1179 else:
1180 self.o.machine.usbController.enabled = True;
1181
1182 if self.fpApiVer >= 4.2:
1183 self.o.machine.pointingHIDType = vboxcon.PointingHIDType_ComboMouse;
1184 self.o.machine.keyboardHIDType = vboxcon.KeyboardHIDType_ComboKeyboard;
1185 else:
1186 self.o.machine.pointingHidType = vboxcon.PointingHidType_ComboMouse;
1187 self.o.machine.keyboardHidType = vboxcon.KeyboardHidType_ComboKeyboard;
1188 else:
1189 if self.fpApiVer >= 4.2:
1190 self.o.machine.pointingHIDType = vboxcon.PointingHIDType_PS2Mouse;
1191 self.o.machine.keyboardHIDType = vboxcon.KeyboardHIDType_PS2Keyboard;
1192 else:
1193 self.o.machine.pointingHidType = vboxcon.PointingHidType_PS2Mouse;
1194 self.o.machine.keyboardHidType = vboxcon.KeyboardHidType_PS2Keyboard;
1195 except:
1196 reporter.errorXcpt('failed to change UsbHid to %s for "%s"' % (fEnable, self.sName));
1197 fRc = False;
1198 else:
1199 reporter.log('changed UsbHid to %s for "%s"' % (fEnable, self.sName));
1200 self.oTstDrv.processPendingEvents();
1201 return fRc;
1202
1203 def enableUsbOhci(self, fEnable):
1204 """
1205 Enables or disables the USB OHCI controller.
1206 Returns True on success and False on failure. Error information is logged.
1207 """
1208 fRc = True;
1209 try:
1210 if fEnable:
1211 if self.fpApiVer >= 4.3:
1212 cOhciCtls = self.o.machine.getUSBControllerCountByType(vboxcon.USBControllerType_OHCI);
1213 if cOhciCtls == 0:
1214 self.o.machine.addUSBController('OHCI', vboxcon.USBControllerType_OHCI);
1215 else:
1216 self.o.machine.usbController.enabled = True;
1217 else:
1218 if self.fpApiVer >= 4.3:
1219 cOhciCtls = self.o.machine.getUSBControllerCountByType(vboxcon.USBControllerType_OHCI);
1220 if cOhciCtls == 1:
1221 self.o.machine.removeUSBController('OHCI');
1222 else:
1223 self.o.machine.usbController.enabled = False;
1224 except:
1225 reporter.errorXcpt('failed to change OHCI to %s for "%s"' % (fEnable, self.sName));
1226 fRc = False;
1227 else:
1228 reporter.log('changed OHCI to %s for "%s"' % (fEnable, self.sName));
1229 self.oTstDrv.processPendingEvents();
1230 return fRc;
1231
1232 def enableUsbEhci(self, fEnable):
1233 """
1234 Enables or disables the USB EHCI controller, enables also OHCI if it is still disabled.
1235 Returns True on success and False on failure. Error information is logged.
1236 """
1237 fRc = True;
1238 try:
1239 if fEnable:
1240 if self.fpApiVer >= 4.3:
1241 cOhciCtls = self.o.machine.getUSBControllerCountByType(vboxcon.USBControllerType_OHCI);
1242 if cOhciCtls == 0:
1243 self.o.machine.addUSBController('OHCI', vboxcon.USBControllerType_OHCI);
1244
1245 cEhciCtls = self.o.machine.getUSBControllerCountByType(vboxcon.USBControllerType_EHCI);
1246 if cEhciCtls == 0:
1247 self.o.machine.addUSBController('EHCI', vboxcon.USBControllerType_EHCI);
1248 else:
1249 self.o.machine.usbController.enabled = True;
1250 self.o.machine.usbController.enabledEHCI = True;
1251 else:
1252 if self.fpApiVer >= 4.3:
1253 cEhciCtls = self.o.machine.getUSBControllerCountByType(vboxcon.USBControllerType_EHCI);
1254 if cEhciCtls == 1:
1255 self.o.machine.removeUSBController('EHCI');
1256 else:
1257 self.o.machine.usbController.enabledEHCI = False;
1258 except:
1259 reporter.errorXcpt('failed to change EHCI to %s for "%s"' % (fEnable, self.sName));
1260 fRc = False;
1261 else:
1262 reporter.log('changed EHCI to %s for "%s"' % (fEnable, self.sName));
1263 self.oTstDrv.processPendingEvents();
1264 return fRc;
1265
1266 def enableUsbXhci(self, fEnable):
1267 """
1268 Enables or disables the USB XHCI controller. Error information is logged.
1269 """
1270 fRc = True;
1271 try:
1272 if fEnable:
1273 cXhciCtls = self.o.machine.getUSBControllerCountByType(vboxcon.USBControllerType_XHCI);
1274 if cXhciCtls == 0:
1275 self.o.machine.addUSBController('XHCI', vboxcon.USBControllerType_XHCI);
1276 else:
1277 cXhciCtls = self.o.machine.getUSBControllerCountByType(vboxcon.USBControllerType_XHCI);
1278 if cXhciCtls == 1:
1279 self.o.machine.removeUSBController('XHCI');
1280 except:
1281 reporter.errorXcpt('failed to change XHCI to %s for "%s"' % (fEnable, self.sName));
1282 fRc = False;
1283 else:
1284 reporter.log('changed XHCI to %s for "%s"' % (fEnable, self.sName));
1285 self.oTstDrv.processPendingEvents();
1286 return fRc;
1287
1288 def setFirmwareType(self, eType):
1289 """
1290 Sets the firmware type.
1291 Returns True on success and False on failure. Error information is logged.
1292 """
1293 fRc = True;
1294 try:
1295 if self.fpApiVer >= 7.1:
1296 self.o.machine.firmwareSettings.firmwareType = eType;
1297 else:
1298 self.o.machine.firmwareType = eType;
1299 except:
1300 reporter.errorXcpt('failed to set firmwareType=%s for "%s"' % (eType, self.sName));
1301 fRc = False;
1302 else:
1303 reporter.log('set firmwareType=%s for "%s"' % (eType, self.sName));
1304 self.oTstDrv.processPendingEvents();
1305 return fRc;
1306
1307 def enableSecureBoot(self, fEnable, sUefiMokPathPrefix = None):
1308 """
1309 Enables or disables Secure Boot. Error information is logged.
1310 """
1311
1312 if self.fpApiVer >= 7.0:
1313
1314 fRc = True;
1315 try:
1316 self.o.machine.nonVolatileStore.initUefiVariableStore(0);
1317
1318 # Enroll necessary keys and signatures in case if Secure Boot needs to be turned ON.
1319 if fEnable:
1320 self.o.machine.nonVolatileStore.uefiVariableStore.enrollDefaultMsSignatures();
1321 self.o.machine.nonVolatileStore.uefiVariableStore.enrollOraclePlatformKey();
1322 if sUefiMokPathPrefix:
1323 if self.oTstDrv.uRevision >= 156564: # Backported IUefiVariableStore::addSignatureToMok() to 7.0.
1324 sFullName = self.oTstDrv.getFullResourceName(sUefiMokPathPrefix) + '.der';
1325 with open(sFullName, "rb") as der_file:
1326 self.o.machine.nonVolatileStore.uefiVariableStore.addSignatureToMok(bytearray(der_file.read()), \
1327 uuid.uuid4().hex, \
1328 vboxcon.SignatureType_X509);
1329 else:
1330 reporter.log('Warning: Enrolling own keys / signatures only available for 7.0 >= r156564. ' \
1331 'Guest Additions installation might fail!');
1332
1333 self.o.machine.nonVolatileStore.uefiVariableStore.secureBootEnabled = fEnable;
1334 except:
1335 reporter.errorXcpt('failed to change Secure Boot to %s for "%s"' % (fEnable, self.sName));
1336 fRc = False;
1337 else:
1338 reporter.log('changed Secure Boot to %s for "%s"' % (fEnable, self.sName));
1339 self.oTstDrv.processPendingEvents();
1340
1341 else:
1342 reporter.log('Secure Boot is only supported for API 7.0 or newer');
1343 fRc = False;
1344
1345 return fRc;
1346
1347 def setChipsetType(self, eType):
1348 """
1349 Sets the chipset type.
1350 Returns True on success and False on failure. Error information is logged.
1351 """
1352 fRc = True;
1353 try:
1354 if self.fpApiVer >= 7.1:
1355 self.o.machine.platform.chipsetType = eType;
1356 else:
1357 self.o.machine.chipsetType = eType;
1358 except:
1359 reporter.errorXcpt('failed to set chipsetType=%s for "%s"' % (eType, self.sName));
1360 fRc = False;
1361 else:
1362 reporter.log('set chipsetType=%s for "%s"' % (eType, self.sName));
1363 self.oTstDrv.processPendingEvents();
1364 return fRc;
1365
1366 def setIommuType(self, eType):
1367 """
1368 Sets the IOMMU type.
1369 Returns True on success and False on failure. Error information is logged.
1370 """
1371 # Supported.
1372 if self.fpApiVer < 6.2 or not hasattr(vboxcon, 'IommuType_Intel') or not hasattr(vboxcon, 'IommuType_AMD'):
1373 return True;
1374 fRc = True;
1375 try:
1376 if self.fpApiVer >= 7.1:
1377 self.o.machine.platform.iommuType = eType;
1378 else:
1379 self.o.machine.iommuType = eType;
1380 except:
1381 reporter.errorXcpt('failed to set iommuType=%s for "%s"' % (eType, self.sName));
1382 fRc = False;
1383 else:
1384 reporter.log('set iommuType=%s for "%s"' % (eType, self.sName));
1385 self.oTstDrv.processPendingEvents();
1386 return fRc;
1387
1388 def setupBootLogo(self, fEnable, cMsLogoDisplay = 0):
1389 """
1390 Sets up the boot logo. fEnable toggles the fade and boot menu
1391 settings as well as the mode.
1392 """
1393 fRc = True;
1394 try:
1395 if self.fpApiVer >= 7.1:
1396 fwSettings = self.o.machine.firmwareSettings;
1397 if fEnable:
1398 fwSettings.bootMenuMode = vboxcon.FirmwareBootMenuMode_Disabled;
1399 else:
1400 fwSettings.bootMenuMode = vboxcon.FirmwareBootMenuMode_MessageAndMenu;
1401 else:
1402 fwSettings = self.o.machine.BIOSSettings;
1403 if fEnable:
1404 fwSettings.bootMenuMode = vboxcon.BIOSBootMenuMode_Disabled;
1405 else:
1406 fwSettings.bootMenuMode = vboxcon.BIOSBootMenuMode_MessageAndMenu;
1407 fwSettings.logoFadeIn = not fEnable;
1408 fwSettings.logoFadeOut = not fEnable;
1409 fwSettings.logoDisplayTime = cMsLogoDisplay;
1410 except:
1411 reporter.errorXcpt('failed to set logoFadeIn/logoFadeOut/bootMenuMode=%s for "%s"' % (fEnable, self.sName));
1412 fRc = False;
1413 else:
1414 reporter.log('set logoFadeIn/logoFadeOut/bootMenuMode=%s for "%s"' % (fEnable, self.sName));
1415 self.oTstDrv.processPendingEvents();
1416 return fRc;
1417
1418 def setupVrdp(self, fEnable, uPort = None):
1419 """
1420 Configures VRDP.
1421 """
1422 fRc = True;
1423 try:
1424 if self.fpApiVer >= 4.0:
1425 self.o.machine.VRDEServer.enabled = fEnable;
1426 else:
1427 self.o.machine.VRDPServer.enabled = fEnable;
1428 except:
1429 reporter.errorXcpt('failed to set VRDEServer::enabled=%s for "%s"' % (fEnable, self.sName));
1430 fRc = False;
1431
1432 if uPort is not None and fRc:
1433 try:
1434 if self.fpApiVer >= 4.0:
1435 self.o.machine.VRDEServer.setVRDEProperty("TCP/Ports", str(uPort));
1436 else:
1437 self.o.machine.VRDPServer.ports = str(uPort);
1438 except:
1439 reporter.errorXcpt('failed to set VRDEServer::ports=%s for "%s"' % (uPort, self.sName));
1440 fRc = False;
1441 if fRc:
1442 reporter.log('set VRDEServer.enabled/ports=%s/%s for "%s"' % (fEnable, uPort, self.sName));
1443 self.oTstDrv.processPendingEvents();
1444 return fRc;
1445
1446 def getNicDriverNameFromType(self, eNicType):
1447 """
1448 Helper that translate the adapter type into a driver name.
1449 """
1450 if eNicType in (vboxcon.NetworkAdapterType_Am79C970A, vboxcon.NetworkAdapterType_Am79C973):
1451 sName = 'pcnet';
1452 elif eNicType in (vboxcon.NetworkAdapterType_I82540EM,
1453 vboxcon.NetworkAdapterType_I82543GC,
1454 vboxcon.NetworkAdapterType_I82545EM):
1455 sName = 'e1000';
1456 elif eNicType == vboxcon.NetworkAdapterType_Virtio:
1457 sName = 'virtio-net';
1458 else:
1459 reporter.error('Unknown adapter type "%s" (VM: "%s")' % (eNicType, self.sName));
1460 sName = 'pcnet';
1461 return sName;
1462
1463 def setupNatForwardingForTxs(self, iNic = 0, iHostPort = 5042):
1464 """
1465 Sets up NAT forwarding for port 5042 if applicable, cleans up if not.
1466 """
1467 try:
1468 oNic = self.o.machine.getNetworkAdapter(iNic);
1469 except:
1470 reporter.errorXcpt('getNetworkAdapter(%s) failed for "%s"' % (iNic, self.sName));
1471 return False;
1472
1473 # Nuke the old setup for all possible adapter types (in case we're
1474 # called after it changed).
1475 for sName in ('pcnet', 'e1000', 'virtio-net'):
1476 for sConfig in ('VBoxInternal/Devices/%s/%u/LUN#0/AttachedDriver/Config' % (sName, iNic), \
1477 'VBoxInternal/Devices/%s/%u/LUN#0/Config' % (sName, iNic)):
1478 try:
1479 self.o.machine.setExtraData('%s/txs/Protocol' % (sConfig), '');
1480 self.o.machine.setExtraData('%s/txs/HostPort' % (sConfig), '');
1481 self.o.machine.setExtraData('%s/txs/GuestPort' % (sConfig), '');
1482 except:
1483 reporter.errorXcpt();
1484
1485 # Set up port forwarding if NAT attachment.
1486 try:
1487 eAttType = oNic.attachmentType;
1488 except:
1489 reporter.errorXcpt('attachmentType on %s failed for "%s"' % (iNic, self.sName));
1490 return False;
1491 if eAttType != vboxcon.NetworkAttachmentType_NAT:
1492 return True;
1493
1494 try:
1495 eNicType = oNic.adapterType;
1496 fTraceEnabled = oNic.traceEnabled;
1497 except:
1498 reporter.errorXcpt('attachmentType/traceEnabled on %s failed for "%s"' % (iNic, self.sName));
1499 return False;
1500
1501 if self.fpApiVer >= 4.1:
1502 try:
1503 if self.fpApiVer >= 4.2:
1504 oNatEngine = oNic.NATEngine;
1505 else:
1506 oNatEngine = oNic.natDriver;
1507 except:
1508 reporter.errorXcpt('Failed to get INATEngine data on "%s"' % (self.sName));
1509 return False;
1510 try: oNatEngine.removeRedirect('txs');
1511 except: pass;
1512 try:
1513 oNatEngine.addRedirect('txs', vboxcon.NATProtocol_TCP, '127.0.0.1', '%s' % (iHostPort), '', '5042');
1514 except:
1515 reporter.errorXcpt('Failed to add a addRedirect redirect on "%s"' % (self.sName));
1516 return False;
1517
1518 else:
1519 sName = self.getNicDriverNameFromType(eNicType);
1520 if fTraceEnabled:
1521 sConfig = 'VBoxInternal/Devices/%s/%u/LUN#0/AttachedDriver/Config' % (sName, iNic)
1522 else:
1523 sConfig = 'VBoxInternal/Devices/%s/%u/LUN#0/Config' % (sName, iNic)
1524
1525 try:
1526 self.o.machine.setExtraData('%s/txs/Protocol' % (sConfig), 'TCP');
1527 self.o.machine.setExtraData('%s/txs/HostPort' % (sConfig), '%s' % (iHostPort));
1528 self.o.machine.setExtraData('%s/txs/GuestPort' % (sConfig), '5042');
1529 except:
1530 reporter.errorXcpt('Failed to set NAT extra data on "%s"' % (self.sName));
1531 return False;
1532 return True;
1533
1534 def setNicType(self, eType, iNic = 0):
1535 """
1536 Sets the NIC type of the specified NIC.
1537 Returns True on success and False on failure. Error information is logged.
1538 """
1539 try:
1540 try:
1541 oNic = self.o.machine.getNetworkAdapter(iNic);
1542 except:
1543 reporter.errorXcpt('getNetworkAdapter(%s) failed for "%s"' % (iNic, self.sName));
1544 return False;
1545 try:
1546 oNic.adapterType = eType;
1547 except:
1548 reporter.errorXcpt('failed to set NIC type on slot %s to %s for VM "%s"' % (iNic, eType, self.sName));
1549 return False;
1550 finally:
1551 self.oTstDrv.processPendingEvents();
1552
1553 if not self.setupNatForwardingForTxs(iNic):
1554 return False;
1555 reporter.log('set NIC type on slot %s to %s for VM "%s"' % (iNic, eType, self.sName));
1556 return True;
1557
1558 def setNicTraceEnabled(self, fTraceEnabled, sTraceFile, iNic = 0):
1559 """
1560 Sets the NIC trace enabled flag and file path.
1561 Returns True on success and False on failure. Error information is logged.
1562 """
1563 try:
1564 try:
1565 oNic = self.o.machine.getNetworkAdapter(iNic);
1566 except:
1567 reporter.errorXcpt('getNetworkAdapter(%s) failed for "%s"' % (iNic, self.sName));
1568 return False;
1569 try:
1570 oNic.traceEnabled = fTraceEnabled;
1571 oNic.traceFile = sTraceFile;
1572 except:
1573 reporter.errorXcpt('failed to set NIC trace flag on slot %s to %s for VM "%s"' \
1574 % (iNic, fTraceEnabled, self.sName));
1575 return False;
1576 finally:
1577 self.oTstDrv.processPendingEvents();
1578
1579 if not self.setupNatForwardingForTxs(iNic):
1580 return False;
1581 reporter.log('set NIC trace on slot %s to "%s" (path "%s") for VM "%s"' %
1582 (iNic, fTraceEnabled, sTraceFile, self.sName));
1583 return True;
1584
1585 def getDefaultNicName(self, eAttachmentType):
1586 """
1587 Return the default network / interface name for the NIC attachment type.
1588 """
1589 sRetName = '';
1590 if eAttachmentType == vboxcon.NetworkAttachmentType_Bridged:
1591 if self.oTstDrv.sDefBridgedNic is not None:
1592 sRetName = self.oTstDrv.sDefBridgedNic;
1593 else:
1594 sRetName = 'eth0';
1595 try:
1596 aoHostNics = self.oVBoxMgr.getArray(self.oVBox.host, 'networkInterfaces');
1597 for oHostNic in aoHostNics:
1598 if oHostNic.interfaceType == vboxcon.HostNetworkInterfaceType_Bridged \
1599 and oHostNic.status == vboxcon.HostNetworkInterfaceStatus_Up:
1600 sRetName = oHostNic.name;
1601 break;
1602 except:
1603 reporter.errorXcpt();
1604
1605 elif eAttachmentType == vboxcon.NetworkAttachmentType_HostOnly:
1606 try:
1607 aoHostNics = self.oVBoxMgr.getArray(self.oVBox.host, 'networkInterfaces');
1608 for oHostNic in aoHostNics:
1609 if oHostNic.interfaceType == vboxcon.HostNetworkInterfaceType_HostOnly:
1610 if oHostNic.status == vboxcon.HostNetworkInterfaceStatus_Up:
1611 sRetName = oHostNic.name;
1612 break;
1613 if sRetName == '':
1614 sRetName = oHostNic.name;
1615 except:
1616 reporter.errorXcpt();
1617 if sRetName == '':
1618 # Create a new host-only interface.
1619 reporter.log("Creating host only NIC ...");
1620 try:
1621 (oIProgress, oIHostOnly) = self.oVBox.host.createHostOnlyNetworkInterface();
1622 oProgress = ProgressWrapper(oIProgress, self.oVBoxMgr, self.oTstDrv, 'Create host only NIC');
1623 oProgress.wait();
1624 if oProgress.logResult() is False:
1625 return '';
1626 sRetName = oIHostOnly.name;
1627 except:
1628 reporter.errorXcpt();
1629 return '';
1630 reporter.log("Created host only NIC: '%s'" % (sRetName,));
1631
1632 elif self.fpApiVer >= 7.0 and eAttachmentType == vboxcon.NetworkAttachmentType_HostOnlyNetwork:
1633 aoHostNetworks = self.oVBoxMgr.getArray(self.oVBox, 'hostOnlyNetworks');
1634 if aoHostNetworks:
1635 sRetName = aoHostNetworks[0].networkName;
1636 else:
1637 try:
1638 oHostOnlyNet = self.oVBox.createHostOnlyNetwork('Host-only Test Network');
1639 oHostOnlyNet.lowerIP = '192.168.56.1';
1640 oHostOnlyNet.upperIP = '192.168.56.199';
1641 oHostOnlyNet.networkMask = '255.255.255.0';
1642 sRetName = oHostOnlyNet.networkName;
1643 except:
1644 reporter.errorXcpt();
1645 return '';
1646
1647 elif eAttachmentType == vboxcon.NetworkAttachmentType_Internal:
1648 sRetName = 'VBoxTest';
1649
1650 elif eAttachmentType == vboxcon.NetworkAttachmentType_NAT:
1651 sRetName = '';
1652
1653 else: ## @todo Support NetworkAttachmentType_NATNetwork
1654 reporter.error('eAttachmentType=%s is not known' % (eAttachmentType));
1655 return sRetName;
1656
1657 def setNicAttachment(self, eAttachmentType, sName = None, iNic = 0):
1658 """
1659 Sets the attachment type of the specified NIC.
1660 Returns True on success and False on failure. Error information is logged.
1661 """
1662 try:
1663 oNic = self.o.machine.getNetworkAdapter(iNic);
1664 except:
1665 reporter.errorXcpt('getNetworkAdapter(%s) failed for "%s"' % (iNic, self.sName));
1666 return False;
1667
1668 try:
1669 if eAttachmentType is not None:
1670 try:
1671 if self.fpApiVer >= 4.1:
1672 oNic.attachmentType = eAttachmentType;
1673 else:
1674 if eAttachmentType == vboxcon.NetworkAttachmentType_NAT:
1675 oNic.attachToNAT();
1676 elif eAttachmentType == vboxcon.NetworkAttachmentType_Bridged:
1677 oNic.attachToBridgedInterface();
1678 elif eAttachmentType == vboxcon.NetworkAttachmentType_Internal:
1679 oNic.attachToInternalNetwork();
1680 elif eAttachmentType == vboxcon.NetworkAttachmentType_HostOnly:
1681 oNic.attachToHostOnlyInterface();
1682 else:
1683 raise base.GenError("eAttachmentType=%s is invalid" % (eAttachmentType));
1684 except:
1685 reporter.errorXcpt('failed to set the attachment type on slot %s to %s for VM "%s"' \
1686 % (iNic, eAttachmentType, self.sName));
1687 return False;
1688 else:
1689 try:
1690 eAttachmentType = oNic.attachmentType;
1691 except:
1692 reporter.errorXcpt('failed to get the attachment type on slot %s for VM "%s"' % (iNic, self.sName));
1693 return False;
1694 finally:
1695 self.oTstDrv.processPendingEvents();
1696
1697 if sName is not None:
1698 # Resolve the special 'default' name.
1699 if sName == 'default':
1700 sName = self.getDefaultNicName(eAttachmentType);
1701
1702 # The name translate to different attributes depending on the
1703 # attachment type.
1704 try:
1705 if eAttachmentType == vboxcon.NetworkAttachmentType_Bridged:
1706 ## @todo check this out on windows, may have to do a
1707 # translation of the name there or smth IIRC.
1708 try:
1709 if self.fpApiVer >= 4.1:
1710 oNic.bridgedInterface = sName;
1711 else:
1712 oNic.hostInterface = sName;
1713 except:
1714 reporter.errorXcpt('failed to set the hostInterface property on slot %s to "%s" for VM "%s"'
1715 % (iNic, sName, self.sName,));
1716 return False;
1717 elif eAttachmentType == vboxcon.NetworkAttachmentType_HostOnly:
1718 try:
1719 if self.fpApiVer >= 4.1:
1720 oNic.hostOnlyInterface = sName;
1721 else:
1722 oNic.hostInterface = sName;
1723 except:
1724 reporter.errorXcpt('failed to set the internalNetwork property on slot %s to "%s" for VM "%s"'
1725 % (iNic, sName, self.sName,));
1726 return False;
1727 elif self.fpApiVer >= 7.0 and eAttachmentType == vboxcon.NetworkAttachmentType_HostOnlyNetwork:
1728 try:
1729 oNic.hostOnlyNetwork = sName;
1730 except:
1731 reporter.errorXcpt('failed to set the hostOnlyNetwork property on slot %s to "%s" for VM "%s"'
1732 % (iNic, sName, self.sName,));
1733 return False;
1734 elif eAttachmentType == vboxcon.NetworkAttachmentType_Internal:
1735 try:
1736 oNic.internalNetwork = sName;
1737 except:
1738 reporter.errorXcpt('failed to set the internalNetwork property on slot %s to "%s" for VM "%s"'
1739 % (iNic, sName, self.sName,));
1740 return False;
1741 elif eAttachmentType == vboxcon.NetworkAttachmentType_NAT:
1742 try:
1743 oNic.NATNetwork = sName;
1744 except:
1745 reporter.errorXcpt('failed to set the NATNetwork property on slot %s to "%s" for VM "%s"'
1746 % (iNic, sName, self.sName,));
1747 return False;
1748 finally:
1749 self.oTstDrv.processPendingEvents();
1750
1751 if not self.setupNatForwardingForTxs(iNic):
1752 return False;
1753 reporter.log('set NIC attachment type on slot %s to %s for VM "%s"' % (iNic, eAttachmentType, self.sName));
1754 return True;
1755
1756 def setNicLocalhostReachable(self, fReachable, iNic = 0):
1757 """
1758 Sets whether the specified NIC can reach the host or not.
1759 Only affects (enabled) NICs configured to NAT at the moment.
1760
1761 Returns True on success and False on failure. Error information is logged.
1762 """
1763 try:
1764 oNic = self.o.machine.getNetworkAdapter(iNic);
1765 except:
1766 return reporter.errorXcpt('getNetworkAdapter(%s) failed for "%s"' % (iNic, self.sName,));
1767
1768 try:
1769 if not oNic.enabled: # NIC not enabled? Nothing to do here.
1770 return True;
1771 except:
1772 return reporter.errorXcpt('NIC enabled status (%s) failed for "%s"' % (iNic, self.sName,));
1773
1774 reporter.log('Setting "LocalhostReachable" for network adapter in slot %d to %s' % (iNic, fReachable));
1775
1776 try:
1777 oNatEngine = oNic.NATEngine;
1778 except:
1779 return reporter.errorXcpt('Getting NIC NAT engine (%s) failed for "%s"' % (iNic, self.sName,));
1780
1781 try:
1782 if hasattr(oNatEngine, "localhostReachable"):
1783 oNatEngine.localhostReachable = fReachable;
1784 else:
1785 oNatEngine.LocalhostReachable = fReachable;
1786 except:
1787 return reporter.errorXcpt('LocalhostReachable (%s) failed for "%s"' % (iNic, self.sName,));
1788
1789 return True;
1790
1791 def setNicMacAddress(self, sMacAddr, iNic = 0):
1792 """
1793 Sets the MAC address of the specified NIC.
1794
1795 The sMacAddr parameter is a string supplying the tail end of the MAC
1796 address, missing quads are supplied from a constant byte (2), the IPv4
1797 address of the host, and the NIC number.
1798
1799 Returns True on success and False on failure. Error information is logged.
1800 """
1801
1802 # Resolve missing MAC address prefix by feeding in the host IP address bytes.
1803 cchMacAddr = len(sMacAddr);
1804 if 0 < cchMacAddr < 12:
1805 sHostIP = netutils.getPrimaryHostIp();
1806 abHostIP = socket.inet_aton(sHostIP);
1807 if sys.version_info[0] < 3:
1808 abHostIP = (ord(abHostIP[0]), ord(abHostIP[1]), ord(abHostIP[2]), ord(abHostIP[3]));
1809
1810 if abHostIP[0] == 127 \
1811 or (abHostIP[0] == 169 and abHostIP[1] == 254) \
1812 or (abHostIP[0] == 192 and abHostIP[1] == 168 and abHostIP[2] == 56):
1813 return reporter.error('host IP for "%s" is %s, most likely not unique.' % (netutils.getHostnameFqdn(), sHostIP,));
1814
1815 sDefaultMac = '%02X%02X%02X%02X%02X%02X' % (0x02, abHostIP[0], abHostIP[1], abHostIP[2], abHostIP[3], iNic);
1816 sMacAddr = sDefaultMac[0:(12 - cchMacAddr)] + sMacAddr;
1817
1818 # Get the NIC object and try set it address.
1819 try:
1820 oNic = self.o.machine.getNetworkAdapter(iNic);
1821 except:
1822 return reporter.errorXcpt('getNetworkAdapter(%s) failed for "%s"' % (iNic, self.sName,));
1823
1824 try:
1825 oNic.MACAddress = sMacAddr;
1826 except:
1827 return reporter.errorXcpt('failed to set the MAC address on slot %s to "%s" for VM "%s"'
1828 % (iNic, sMacAddr, self.sName));
1829
1830 reporter.log('set MAC address on slot %s to %s for VM "%s"' % (iNic, sMacAddr, self.sName,));
1831 return True;
1832
1833 def setRamSize(self, cMB):
1834 """
1835 Set the RAM size of the VM.
1836 Returns True on success and False on failure. Error information is logged.
1837 """
1838 fRc = True;
1839 try:
1840 self.o.machine.memorySize = cMB;
1841 except:
1842 reporter.errorXcpt('failed to set the RAM size of "%s" to %s' % (self.sName, cMB));
1843 fRc = False;
1844 else:
1845 reporter.log('set the RAM size of "%s" to %s' % (self.sName, cMB));
1846 self.oTstDrv.processPendingEvents();
1847 return fRc;
1848
1849 def setLargePagesX86(self, fUseLargePages):
1850 """
1851 Configures whether the VM should use large pages or not. x86 only.
1852 Returns True on success and False on failure. Error information is logged.
1853
1854 Ignored on non-x86 platform architectures.
1855 """
1856 if not self.isPlatformX86(): return True;
1857 fRc = True;
1858 try:
1859 if self.fpApiVer >= 7.1:
1860 self.o.machine.platform.x86.setHWVirtExProperty(vboxcon.HWVirtExPropertyType_LargePages, fUseLargePages);
1861 else:
1862 self.o.machine.setHWVirtExProperty(vboxcon.HWVirtExPropertyType_LargePages, fUseLargePages);
1863 except:
1864 reporter.errorXcpt('failed to set large pages of "%s" to %s' % (self.sName, fUseLargePages));
1865 fRc = False;
1866 else:
1867 reporter.log('set the large pages of "%s" to %s' % (self.sName, fUseLargePages));
1868 self.oTstDrv.processPendingEvents();
1869 return fRc;
1870
1871 def setVRamSize(self, cMB):
1872 """
1873 Set the RAM size of the VM.
1874 Returns True on success and False on failure. Error information is logged.
1875 """
1876 fRc = True;
1877 try:
1878 if self.fpApiVer >= 6.1 and hasattr(self.o.machine, 'graphicsAdapter'):
1879 self.o.machine.graphicsAdapter.VRAMSize = cMB;
1880 else:
1881 self.o.machine.VRAMSize = cMB;
1882 except:
1883 reporter.errorXcpt('failed to set the VRAM size of "%s" to %s' % (self.sName, cMB));
1884 fRc = False;
1885 else:
1886 reporter.log('set the VRAM size of "%s" to %s' % (self.sName, cMB));
1887 self.oTstDrv.processPendingEvents();
1888 return fRc;
1889
1890 def setVideoControllerType(self, eControllerType):
1891 """
1892 Set the video controller type of the VM.
1893 Returns True on success and False on failure. Error information is logged.
1894 """
1895 fRc = True;
1896 try:
1897 if self.fpApiVer >= 6.1 and hasattr(self.o.machine, 'graphicsAdapter'):
1898 self.o.machine.graphicsAdapter.graphicsControllerType = eControllerType;
1899 else:
1900 self.o.machine.graphicsControllerType = eControllerType;
1901 except:
1902 reporter.errorXcpt('failed to set the video controller type of "%s" to %s' % (self.sName, eControllerType));
1903 fRc = False;
1904 else:
1905 reporter.log('set the video controller type of "%s" to %s' % (self.sName, eControllerType));
1906 self.oTstDrv.processPendingEvents();
1907 return fRc;
1908
1909 def setAccelerate3DEnabled(self, fEnabled):
1910 """
1911 Set the video controller type of the VM.
1912 Returns True on success and False on failure. Error information is logged.
1913 """
1914 fRc = True;
1915 try:
1916 if self.fpApiVer >= 6.1 and hasattr(self.o.machine, 'graphicsAdapter'):
1917 if self.fpApiVer >= 7.1 and hasattr(self.o.machine.graphicsAdapter, 'isFeatureEnabled'):
1918 self.o.machine.graphicsAdapter.setFeatureEnabled(vboxcon.GraphicsFeature_Acceleration3D, fEnabled);
1919 else:
1920 self.o.machine.graphicsAdapter.accelerate3DEnabled = fEnabled;
1921 else:
1922 self.o.machine.accelerate3DEnabled = fEnabled;
1923 except:
1924 reporter.errorXcpt('failed to set the accelerate3DEnabled of "%s" to %s' % (self.sName, fEnabled));
1925 fRc = False;
1926 else:
1927 reporter.log('set the accelerate3DEnabled of "%s" to %s' % (self.sName, fEnabled));
1928 self.oTstDrv.processPendingEvents();
1929 return fRc;
1930
1931 def setCpuCount(self, cCpus):
1932 """
1933 Set the number of CPUs.
1934 Returns True on success and False on failure. Error information is logged.
1935 """
1936 fRc = True;
1937 try:
1938 self.o.machine.CPUCount = cCpus;
1939 except:
1940 reporter.errorXcpt('failed to set the CPU count of "%s" to %s' % (self.sName, cCpus));
1941 fRc = False;
1942 else:
1943 reporter.log('set the CPU count of "%s" to %s' % (self.sName, cCpus));
1944 self.oTstDrv.processPendingEvents();
1945 return fRc;
1946
1947 def getCpuCount(self):
1948 """
1949 Returns the number of CPUs.
1950 Returns the number of CPUs on success and 0 on failure. Error information is logged.
1951 """
1952 cCpus = 0;
1953 try:
1954 cCpus = self.o.machine.CPUCount;
1955 except:
1956 reporter.errorXcpt('failed to get the CPU count of "%s"' % (self.sName,));
1957
1958 self.oTstDrv.processPendingEvents();
1959 return cCpus;
1960
1961 def ensureControllerAttached(self, sController):
1962 """
1963 Makes sure the specified controller is attached to the VM, attaching it
1964 if necessary.
1965 """
1966 try:
1967 try:
1968 self.o.machine.getStorageControllerByName(sController);
1969 except:
1970 (eBus, eType) = _ControllerNameToBusAndType(sController);
1971 try:
1972 oCtl = self.o.machine.addStorageController(sController, eBus);
1973 except:
1974 reporter.errorXcpt('addStorageController("%s",%s) failed on "%s"' % (sController, eBus, self.sName) );
1975 return False;
1976 try:
1977 oCtl.controllerType = eType;
1978 reporter.log('added storage controller "%s" (bus %s, type %s) to %s'
1979 % (sController, eBus, eType, self.sName));
1980 except:
1981 reporter.errorXcpt('controllerType = %s on ("%s" / %s) failed on "%s"'
1982 % (eType, sController, eBus, self.sName) );
1983 return False;
1984 finally:
1985 self.oTstDrv.processPendingEvents();
1986 return True;
1987
1988 def setStorageControllerPortCount(self, sController, iPortCount):
1989 """
1990 Set maximum ports count for storage controller
1991 """
1992 try:
1993 oCtl = self.o.machine.getStorageControllerByName(sController)
1994 oCtl.portCount = iPortCount
1995 self.oTstDrv.processPendingEvents()
1996 reporter.log('set controller "%s" port count to value %d' % (sController, iPortCount))
1997 return True
1998 except:
1999 reporter.log('unable to set storage controller "%s" ports count to %d' % (sController, iPortCount))
2000
2001 return False
2002
2003 def setStorageControllerHostIoCache(self, sController, fUseHostIoCache):
2004 """
2005 Set maximum ports count for storage controller
2006 """
2007 try:
2008 oCtl = self.o.machine.getStorageControllerByName(sController);
2009 oCtl.useHostIOCache = fUseHostIoCache;
2010 self.oTstDrv.processPendingEvents();
2011 reporter.log('set controller "%s" host I/O cache setting to %r' % (sController, fUseHostIoCache));
2012 return True;
2013 except:
2014 reporter.log('unable to set storage controller "%s" host I/O cache setting to %r' % (sController, fUseHostIoCache));
2015
2016 return False;
2017
2018 def setBootOrder(self, iPosition, eType):
2019 """
2020 Set guest boot order type
2021 @param iPosition boot order position
2022 @param eType device type (vboxcon.DeviceType_HardDisk,
2023 vboxcon.DeviceType_DVD, vboxcon.DeviceType_Floppy)
2024 """
2025 try:
2026 self.o.machine.setBootOrder(iPosition, eType)
2027 except:
2028 return reporter.errorXcpt('Unable to set boot order.')
2029
2030 reporter.log('Set boot order [%d] for device %s' % (iPosition, str(eType)))
2031 self.oTstDrv.processPendingEvents();
2032
2033 return True
2034
2035 def setStorageControllerType(self, eType, sController = "IDE Controller"):
2036 """
2037 Similar to ensureControllerAttached, except it will change the type.
2038 """
2039 try:
2040 oCtl = self.o.machine.getStorageControllerByName(sController);
2041 except:
2042 (eBus, _) = _ControllerNameToBusAndType(sController);
2043 try:
2044 oCtl = self.o.machine.addStorageController(sController, eBus);
2045 reporter.log('added storage controller "%s" (bus %s) to %s' % (sController, eBus, self.sName));
2046 except:
2047 reporter.errorXcpt('addStorageController("%s",%s) failed on "%s"' % (sController, eBus, self.sName) );
2048 return False;
2049 try:
2050 oCtl.controllerType = eType;
2051 except:
2052 reporter.errorXcpt('failed to set controller type of "%s" on "%s" to %s' % (sController, self.sName, eType) );
2053 return False;
2054 reporter.log('set controller type of "%s" on "%s" to %s' % (sController, self.sName, eType) );
2055 self.oTstDrv.processPendingEvents();
2056 return True;
2057
2058 def attachDvd(self, sImage = None, sController = "IDE Controller", iPort = 1, iDevice = 0):
2059 """
2060 Attaches a DVD drive to a VM, optionally with an ISO inserted.
2061 Returns True on success and False on failure. Error information is logged.
2062 """
2063 # Input validation.
2064 if sImage is not None and not self.oTstDrv.isResourceFile(sImage)\
2065 and not os.path.isabs(sImage): ## fixme - testsuite unzip ++
2066 reporter.fatal('"%s" is not in the resource set' % (sImage));
2067 return None;
2068
2069 if not self.ensureControllerAttached(sController):
2070 return False;
2071
2072 # Find/register the image if specified.
2073 oImage = None;
2074 sImageUuid = "";
2075 if sImage is not None:
2076 sFullName = self.oTstDrv.getFullResourceName(sImage)
2077 try:
2078 oImage = self.oVBox.findDVDImage(sFullName);
2079 except:
2080 try:
2081 if self.fpApiVer >= 4.1:
2082 oImage = self.oVBox.openMedium(sFullName, vboxcon.DeviceType_DVD, vboxcon.AccessMode_ReadOnly, False);
2083 elif self.fpApiVer >= 4.0:
2084 oImage = self.oVBox.openMedium(sFullName, vboxcon.DeviceType_DVD, vboxcon.AccessMode_ReadOnly);
2085 else:
2086 oImage = self.oVBox.openDVDImage(sFullName, "");
2087 except vbox.ComException as oXcpt:
2088 if oXcpt.errno != -1:
2089 reporter.errorXcpt('failed to open DVD image "%s" xxx' % (sFullName));
2090 else:
2091 reporter.errorXcpt('failed to open DVD image "%s" yyy' % (sFullName));
2092 return False;
2093 except:
2094 reporter.errorXcpt('failed to open DVD image "%s"' % (sFullName));
2095 return False;
2096 try:
2097 sImageUuid = oImage.id;
2098 except:
2099 reporter.errorXcpt('failed to get the UUID of "%s"' % (sFullName));
2100 return False;
2101
2102 # Attach the DVD.
2103 fRc = True;
2104 try:
2105 if self.fpApiVer >= 4.0:
2106 self.o.machine.attachDevice(sController, iPort, iDevice, vboxcon.DeviceType_DVD, oImage);
2107 else:
2108 self.o.machine.attachDevice(sController, iPort, iDevice, vboxcon.DeviceType_DVD, sImageUuid);
2109 except:
2110 reporter.errorXcpt('attachDevice("%s",%s,%s,HardDisk,"%s") failed on "%s"' \
2111 % (sController, iPort, iDevice, sImageUuid, self.sName) );
2112 fRc = False;
2113 else:
2114 reporter.log('attached DVD to %s, image="%s"' % (self.sName, sImage));
2115 self.oTstDrv.processPendingEvents();
2116 return fRc;
2117
2118 def attachHd(self, sHd, sController = "IDE Controller", iPort = 0, iDevice = 0, fImmutable = True, fForceResource = True):
2119 """
2120 Attaches a HD to a VM.
2121 Returns True on success and False on failure. Error information is logged.
2122 """
2123 # Input validation.
2124 if fForceResource and not self.oTstDrv.isResourceFile(sHd):
2125 reporter.fatal('"%s" is not in the resource set' % (sHd,));
2126 return None;
2127
2128 if not self.ensureControllerAttached(sController):
2129 return False;
2130
2131 # Find the HD, registering it if necessary (as immutable).
2132 if fForceResource:
2133 sFullName = self.oTstDrv.getFullResourceName(sHd);
2134 else:
2135 sFullName = sHd;
2136 try:
2137 oHd = self.oVBox.findHardDisk(sFullName);
2138 except:
2139 try:
2140 if self.fpApiVer >= 4.1:
2141 oHd = self.oVBox.openMedium(sFullName, vboxcon.DeviceType_HardDisk, vboxcon.AccessMode_ReadOnly, False);
2142 elif self.fpApiVer >= 4.0:
2143 oHd = self.oVBox.openMedium(sFullName, vboxcon.DeviceType_HardDisk, vboxcon.AccessMode_ReadOnly);
2144 else:
2145 oHd = self.oVBox.openHardDisk(sFullName, vboxcon.AccessMode_ReadOnly, False, "", False, "");
2146 except:
2147 reporter.errorXcpt('failed to open hd "%s"' % (sFullName));
2148 return False;
2149 try:
2150 if fImmutable:
2151 oHd.type = vboxcon.MediumType_Immutable;
2152 else:
2153 oHd.type = vboxcon.MediumType_Normal;
2154 except:
2155 if fImmutable:
2156 reporter.errorXcpt('failed to set hd "%s" immutable' % (sHd));
2157 else:
2158 reporter.errorXcpt('failed to set hd "%s" normal' % (sHd));
2159 return False;
2160
2161 # Attach it.
2162 fRc = True;
2163 try:
2164 if self.fpApiVer >= 4.0:
2165 self.o.machine.attachDevice(sController, iPort, iDevice, vboxcon.DeviceType_HardDisk, oHd);
2166 else:
2167 self.o.machine.attachDevice(sController, iPort, iDevice, vboxcon.DeviceType_HardDisk, oHd.id);
2168 except:
2169 reporter.errorXcpt('attachDevice("%s",%s,%s,HardDisk,"%s") failed on "%s"' \
2170 % (sController, iPort, iDevice, oHd.id, self.sName) );
2171 fRc = False;
2172 else:
2173 reporter.log('attached "%s" to %s' % (sHd, self.sName));
2174 self.oTstDrv.processPendingEvents();
2175 return fRc;
2176
2177 def createBaseHd(self, sHd, sFmt = "VDI", cb = 10*1024*1024*1024, cMsTimeout = 60000, tMediumVariant = None):
2178 """
2179 Creates a base HD.
2180 Returns Medium object on success and None on failure. Error information is logged.
2181 """
2182 if tMediumVariant is None:
2183 tMediumVariant = (vboxcon.MediumVariant_Standard, );
2184
2185 try:
2186 if self.fpApiVer >= 5.0:
2187 oHd = self.oVBox.createMedium(sFmt, sHd, vboxcon.AccessMode_ReadWrite, vboxcon.DeviceType_HardDisk);
2188 else:
2189 oHd = self.oVBox.createHardDisk(sFmt, sHd);
2190 oProgressXpcom = oHd.createBaseStorage(cb, tMediumVariant);
2191 oProgress = ProgressWrapper(oProgressXpcom, self.oVBoxMgr, self.oTstDrv, 'create base disk %s' % (sHd));
2192 oProgress.wait(cMsTimeout);
2193 oProgress.logResult();
2194 except:
2195 reporter.errorXcpt('failed to create base hd "%s"' % (sHd));
2196 oHd = None
2197
2198 return oHd;
2199
2200 def createDiffHd(self, oParentHd, sHd, sFmt = "VDI"):
2201 """
2202 Creates a differencing HD.
2203 Returns Medium object on success and None on failure. Error information is logged.
2204 """
2205 # Detect the proper format if requested
2206 if sFmt is None:
2207 try:
2208 oHdFmt = oParentHd.mediumFormat;
2209 lstCaps = self.oVBoxMgr.getArray(oHdFmt, 'capabilities');
2210 if vboxcon.MediumFormatCapabilities_Differencing in lstCaps:
2211 sFmt = oHdFmt.id;
2212 else:
2213 sFmt = 'VDI';
2214 except:
2215 reporter.errorXcpt('failed to get preferred diff format for "%s"' % (sHd));
2216 return None;
2217 try:
2218 if self.fpApiVer >= 5.0:
2219 oHd = self.oVBox.createMedium(sFmt, sHd, vboxcon.AccessMode_ReadWrite, vboxcon.DeviceType_HardDisk);
2220 else:
2221 oHd = self.oVBox.createHardDisk(sFmt, sHd);
2222 oProgressXpcom = oParentHd.createDiffStorage(oHd, (vboxcon.MediumVariant_Standard, ))
2223 oProgress = ProgressWrapper(oProgressXpcom, self.oVBoxMgr, self.oTstDrv, 'create diff disk %s' % (sHd));
2224 oProgress.wait();
2225 oProgress.logResult();
2226 except:
2227 reporter.errorXcpt('failed to create diff hd "%s"' % (sHd));
2228 oHd = None
2229
2230 return oHd;
2231
2232 def createAndAttachHd(self, sHd, sFmt = "VDI", sController = "IDE Controller", cb = 10*1024*1024*1024, # pylint: disable=too-many-arguments
2233 iPort = 0, iDevice = 0, fImmutable = True, cMsTimeout = 60000, tMediumVariant = None):
2234 """
2235 Creates and attaches a HD to a VM.
2236 Returns True on success and False on failure. Error information is logged.
2237 """
2238 if not self.ensureControllerAttached(sController):
2239 return False;
2240
2241 oHd = self.createBaseHd(sHd, sFmt, cb, cMsTimeout, tMediumVariant);
2242 if oHd is None:
2243 return False;
2244
2245 fRc = True;
2246 try:
2247 if fImmutable:
2248 oHd.type = vboxcon.MediumType_Immutable;
2249 else:
2250 oHd.type = vboxcon.MediumType_Normal;
2251 except:
2252 if fImmutable:
2253 reporter.errorXcpt('failed to set hd "%s" immutable' % (sHd));
2254 else:
2255 reporter.errorXcpt('failed to set hd "%s" normal' % (sHd));
2256 fRc = False;
2257
2258 # Attach it.
2259 if fRc is True:
2260 try:
2261 if self.fpApiVer >= 4.0:
2262 self.o.machine.attachDevice(sController, iPort, iDevice, vboxcon.DeviceType_HardDisk, oHd);
2263 else:
2264 self.o.machine.attachDevice(sController, iPort, iDevice, vboxcon.DeviceType_HardDisk, oHd.id);
2265 except:
2266 reporter.errorXcpt('attachDevice("%s",%s,%s,HardDisk,"%s") failed on "%s"' \
2267 % (sController, iPort, iDevice, oHd.id, self.sName) );
2268 fRc = False;
2269 else:
2270 reporter.log('attached "%s" to %s' % (sHd, self.sName));
2271
2272 # Delete disk in case of an error
2273 if fRc is False:
2274 try:
2275 oProgressCom = oHd.deleteStorage();
2276 except:
2277 reporter.errorXcpt('deleteStorage() for disk %s failed' % (sHd,));
2278 else:
2279 oProgress = ProgressWrapper(oProgressCom, self.oVBoxMgr, self.oTstDrv, 'delete disk %s' % (sHd));
2280 oProgress.wait();
2281 oProgress.logResult();
2282
2283 self.oTstDrv.processPendingEvents();
2284 return fRc;
2285
2286 def detachHd(self, sController = "IDE Controller", iPort = 0, iDevice = 0):
2287 """
2288 Detaches a HD, if attached, and returns a reference to it (IMedium).
2289
2290 In order to delete the detached medium, the caller must first save
2291 the changes made in this session.
2292
2293 Returns (fRc, oHd), where oHd is None unless fRc is True, and fRc is
2294 your standard success indicator. Error information is logged.
2295 """
2296
2297 # What's attached?
2298 try:
2299 oHd = self.o.machine.getMedium(sController, iPort, iDevice);
2300 except:
2301 if self.oVBoxMgr.xcptIsOurXcptKind() \
2302 and self.oVBoxMgr.xcptIsEqual(None, self.oVBoxMgr.constants.VBOX_E_OBJECT_NOT_FOUND):
2303 reporter.log('No HD attached (to %s %s:%s)' % (sController, iPort, iDevice));
2304 return (True, None);
2305 return (reporter.errorXcpt('Error getting media at port %s, device %s, on %s.'
2306 % (iPort, iDevice, sController)), None);
2307 # Detach it.
2308 try:
2309 self.o.machine.detachDevice(sController, iPort, iDevice);
2310 except:
2311 return (reporter.errorXcpt('detachDevice("%s",%s,%s) failed on "%s"' \
2312 % (sController, iPort, iDevice, self.sName) ), None);
2313 reporter.log('detached HD ("%s",%s,%s) from %s' % (sController, iPort, iDevice, self.sName));
2314 return (True, oHd);
2315
2316 def attachFloppy(self, sFloppy, sController = "Floppy Controller", iPort = 0, iDevice = 0):
2317 """
2318 Attaches a floppy image to a VM.
2319 Returns True on success and False on failure. Error information is logged.
2320 """
2321 # Input validation.
2322 ## @todo Fix this wrt to bootsector-xxx.img from the validationkit.zip.
2323 ##if not self.oTstDrv.isResourceFile(sFloppy):
2324 ## reporter.fatal('"%s" is not in the resource set' % (sFloppy));
2325 ## return None;
2326
2327 if not self.ensureControllerAttached(sController):
2328 return False;
2329
2330 # Find the floppy image, registering it if necessary (as immutable).
2331 sFullName = self.oTstDrv.getFullResourceName(sFloppy);
2332 try:
2333 oFloppy = self.oVBox.findFloppyImage(sFullName);
2334 except:
2335 try:
2336 if self.fpApiVer >= 4.1:
2337 oFloppy = self.oVBox.openMedium(sFullName, vboxcon.DeviceType_Floppy, vboxcon.AccessMode_ReadOnly, False);
2338 elif self.fpApiVer >= 4.0:
2339 oFloppy = self.oVBox.openMedium(sFullName, vboxcon.DeviceType_Floppy, vboxcon.AccessMode_ReadOnly);
2340 else:
2341 oFloppy = self.oVBox.openFloppyImage(sFullName, "");
2342 except:
2343 reporter.errorXcpt('failed to open floppy "%s"' % (sFullName));
2344 return False;
2345 ## @todo the following works but causes trouble below (asserts in main).
2346 #try:
2347 # oFloppy.type = vboxcon.MediumType_Immutable;
2348 #except:
2349 # reporter.errorXcpt('failed to make floppy "%s" immutable' % (sFullName));
2350 # return False;
2351
2352 # Attach it.
2353 fRc = True;
2354 try:
2355 if self.fpApiVer >= 4.0:
2356 self.o.machine.attachDevice(sController, iPort, iDevice, vboxcon.DeviceType_Floppy, oFloppy);
2357 else:
2358 self.o.machine.attachDevice(sController, iPort, iDevice, vboxcon.DeviceType_Floppy, oFloppy.id);
2359 except:
2360 reporter.errorXcpt('attachDevice("%s",%s,%s,Floppy,"%s") failed on "%s"' \
2361 % (sController, iPort, iDevice, oFloppy.id, self.sName) );
2362 fRc = False;
2363 else:
2364 reporter.log('attached "%s" to %s' % (sFloppy, self.sName));
2365 self.oTstDrv.processPendingEvents();
2366 return fRc;
2367
2368 def setupNic(self, sType, sXXX):
2369 """
2370 Sets up a NIC to a VM.
2371 Returns True on success and False on failure. Error information is logged.
2372 """
2373 if sType == "PCNet": enmType = vboxcon.NetworkAdapterType_Am79C973;
2374 elif sType == "PCNetOld": enmType = vboxcon.NetworkAdapterType_Am79C970A;
2375 elif sType == "E1000": enmType = vboxcon.NetworkAdapterType_I82545EM; # MT Server
2376 elif sType == "E1000Desk": enmType = vboxcon.NetworkAdapterType_I82540EM; # MT Desktop
2377 elif sType == "E1000Srv2": enmType = vboxcon.NetworkAdapterType_I82543GC; # T Server
2378 elif sType == "Virtio": enmType = vboxcon.NetworkAdapterType_Virtio;
2379 else:
2380 reporter.error('Invalid NIC type: "%s" (sXXX=%s)' % (sType, sXXX));
2381 return False;
2382 ## @todo Implement me!
2383 if enmType is not None: pass
2384 return True;
2385
2386 def setupAudio(self, eAudioControllerType, fEnable = True, fEnableIn = False, fEnableOut = True, eAudioDriverType = None):
2387 """
2388 Sets up audio.
2389
2390 :param eAudioControllerType: The audio controller type (vboxcon.AudioControllerType_XXX).
2391 :param fEnable: Whether to enable or disable the audio controller (default enable).
2392 :param fEnableIn: Whether to enable or disable audio input (default disable).
2393 :param fEnableOut: Whether to enable or disable audio output (default enable).
2394 :param eAudioDriverType: The audio driver type (vboxcon.AudioDriverType_XXX), picks something suitable
2395 if None is passed (default).
2396 """
2397 try:
2398 if self.fpApiVer >= 7.0:
2399 oAdapter = self.o.machine.audioSettings.adapter;
2400 else:
2401 oAdapter = self.o.machine.audioAdapter;
2402 except: return reporter.errorXcpt('Failed to get the audio adapter.');
2403
2404 try: oAdapter.audioController = eAudioControllerType;
2405 except: return reporter.errorXcpt('Failed to set the audio controller to %s.' % (eAudioControllerType,));
2406
2407 if eAudioDriverType is None:
2408 if self.fpApiVer >= 7.1:
2409 eAudioDriverType = vboxcon.AudioDriverType_Default;
2410 else:
2411 sHost = utils.getHostOs()
2412 if sHost == 'darwin': eAudioDriverType = vboxcon.AudioDriverType_CoreAudio;
2413 elif sHost == 'win': eAudioDriverType = vboxcon.AudioDriverType_DirectSound;
2414 elif sHost == 'linux': eAudioDriverType = vboxcon.AudioDriverType_Pulse;
2415 elif sHost == 'solaris': eAudioDriverType = vboxcon.AudioDriverType_OSS;
2416 else:
2417 reporter.error('PORTME: Do not know which audio driver to pick for: %s!' % (sHost,));
2418 eAudioDriverType = vboxcon.AudioDriverType_Null;
2419
2420 try: oAdapter.audioDriver = eAudioDriverType;
2421 except: return reporter.errorXcpt('Failed to set the audio driver to %s.' % (eAudioDriverType,))
2422
2423 try: oAdapter.enabled = fEnable;
2424 except: return reporter.errorXcpt('Failed to set the "enabled" property to %s.' % (fEnable,));
2425
2426 try: oAdapter.enabledIn = fEnableIn;
2427 except: return reporter.errorXcpt('Failed to set the "enabledIn" property to %s.' % (fEnable,));
2428
2429 try: oAdapter.enabledOut = fEnableOut;
2430 except: return reporter.errorXcpt('Failed to set the "enabledOut" property to %s.' % (fEnable,));
2431
2432 reporter.log('set audio controller type to %d, driver to %d, and enabled to %s (input is %s, output is %s)'
2433 % (eAudioControllerType, eAudioDriverType, fEnable, fEnableIn, fEnableOut,));
2434 self.oTstDrv.processPendingEvents();
2435 return True;
2436
2437 def setupPreferredConfig(self): # pylint: disable=too-many-locals
2438 """
2439 Configures the VM according to the preferences of the guest type.
2440 """
2441 try:
2442 sOsTypeId = self.o.machine.OSTypeId;
2443 except:
2444 reporter.errorXcpt('failed to obtain the OSTypeId for "%s"' % (self.sName));
2445 return False;
2446
2447 try:
2448 oOsType = self.oVBox.getGuestOSType(sOsTypeId);
2449 except:
2450 reporter.errorXcpt('getGuestOSType("%s") failed for "%s"' % (sOsTypeId, self.sName));
2451 return False;
2452
2453 # get the attributes.
2454 try:
2455 #sFamilyId = oOsType.familyId;
2456 #f64Bit = oOsType.is64Bit;
2457 fIoApic = oOsType.recommendedIOAPIC;
2458 fVirtEx = oOsType.recommendedVirtEx;
2459 cMBRam = oOsType.recommendedRAM;
2460 cMBVRam = oOsType.recommendedVRAM;
2461 #cMBHdd = oOsType.recommendedHDD;
2462 eNicType = oOsType.adapterType;
2463 if self.fpApiVer >= 3.2:
2464 if self.fpApiVer >= 4.2:
2465 fPae = oOsType.recommendedPAE;
2466 fUsbHid = oOsType.recommendedUSBHID;
2467 fHpet = oOsType.recommendedHPET;
2468 eStorCtlType = oOsType.recommendedHDStorageController;
2469 else:
2470 fPae = oOsType.recommendedPae;
2471 fUsbHid = oOsType.recommendedUsbHid;
2472 fHpet = oOsType.recommendedHpet;
2473 eStorCtlType = oOsType.recommendedHdStorageController;
2474 eFirmwareType = oOsType.recommendedFirmware;
2475 else:
2476 fPae = False;
2477 fUsbHid = False;
2478 fHpet = False;
2479 eFirmwareType = -1;
2480 eStorCtlType = vboxcon.StorageControllerType_PIIX4;
2481 if self.fpApiVer >= 4.0:
2482 eAudioCtlType = oOsType.recommendedAudioController;
2483 except:
2484 reporter.errorXcpt('exception reading IGuestOSType(%s) attribute' % (sOsTypeId));
2485 self.oTstDrv.processPendingEvents();
2486 return False;
2487 self.oTstDrv.processPendingEvents();
2488
2489 # Do the setting. Continue applying settings on error in case the
2490 # caller ignores the return code
2491 fRc = True;
2492 if not self.enableIoApic(fIoApic): fRc = False;
2493 if not self.enableVirtExX86(fVirtEx): fRc = False;
2494 if not self.enablePaeX86(fPae): fRc = False;
2495 if not self.setRamSize(cMBRam): fRc = False;
2496 if not self.setVRamSize(cMBVRam): fRc = False;
2497 if not self.setNicType(eNicType, 0): fRc = False;
2498 if self.fpApiVer >= 3.2:
2499 if not self.setFirmwareType(eFirmwareType): fRc = False;
2500 if not self.enableUsbHid(fUsbHid): fRc = False;
2501 if not self.enableHpetX86(fHpet): fRc = False;
2502 if eStorCtlType in (vboxcon.StorageControllerType_PIIX3,
2503 vboxcon.StorageControllerType_PIIX4,
2504 vboxcon.StorageControllerType_ICH6,):
2505 if not self.setStorageControllerType(eStorCtlType, "IDE Controller"):
2506 fRc = False;
2507 if self.fpApiVer >= 4.0:
2508 if not self.setupAudio(eAudioCtlType): fRc = False;
2509
2510 return fRc;
2511
2512 def addUsbDeviceFilter(self, sName, sVendorId = None, sProductId = None, sRevision = None, # pylint: disable=too-many-arguments
2513 sManufacturer = None, sProduct = None, sSerialNumber = None,
2514 sPort = None, sRemote = None):
2515 """
2516 Creates a USB device filter and inserts it into the VM.
2517 Returns True on success.
2518 Returns False on failure (logged).
2519 """
2520 fRc = True;
2521
2522 try:
2523 oUsbDevFilter = self.o.machine.USBDeviceFilters.createDeviceFilter(sName);
2524 oUsbDevFilter.active = True;
2525 if sVendorId is not None:
2526 oUsbDevFilter.vendorId = sVendorId;
2527 if sProductId is not None:
2528 oUsbDevFilter.productId = sProductId;
2529 if sRevision is not None:
2530 oUsbDevFilter.revision = sRevision;
2531 if sManufacturer is not None:
2532 oUsbDevFilter.manufacturer = sManufacturer;
2533 if sProduct is not None:
2534 oUsbDevFilter.product = sProduct;
2535 if sSerialNumber is not None:
2536 oUsbDevFilter.serialnumber = sSerialNumber;
2537 if sPort is not None:
2538 oUsbDevFilter.port = sPort;
2539 if sRemote is not None:
2540 oUsbDevFilter.remote = sRemote;
2541 try:
2542 self.o.machine.USBDeviceFilters.insertDeviceFilter(0, oUsbDevFilter);
2543 except:
2544 reporter.errorXcpt('insertDeviceFilter(%s) failed on "%s"' \
2545 % (0, self.sName) );
2546 fRc = False;
2547 else:
2548 reporter.log('inserted USB device filter "%s" to %s' % (sName, self.sName));
2549 except:
2550 reporter.errorXcpt('createDeviceFilter("%s") failed on "%s"' \
2551 % (sName, self.sName) );
2552 fRc = False;
2553 return fRc;
2554
2555 def getGuestPropertyValue(self, sName):
2556 """
2557 Gets a guest property value.
2558 Returns the value on success, None on failure (logged).
2559 """
2560 try:
2561 sValue = self.o.machine.getGuestPropertyValue(sName);
2562 except:
2563 reporter.errorXcpt('IMachine::getGuestPropertyValue("%s") failed' % (sName));
2564 return None;
2565 return sValue;
2566
2567 def setGuestPropertyValue(self, sName, sValue):
2568 """
2569 Sets a guest property value.
2570 Returns the True on success, False on failure (logged).
2571 """
2572 try:
2573 self.o.machine.setGuestPropertyValue(sName, sValue);
2574 except:
2575 reporter.errorXcpt('IMachine::setGuestPropertyValue("%s","%s") failed' % (sName, sValue));
2576 return False;
2577 return True;
2578
2579 def delGuestPropertyValue(self, sName):
2580 """
2581 Deletes a guest property value.
2582 Returns the True on success, False on failure (logged).
2583 """
2584 try:
2585 oMachine = self.o.machine;
2586 if self.fpApiVer >= 4.2:
2587 oMachine.deleteGuestProperty(sName);
2588 else:
2589 oMachine.setGuestPropertyValue(sName, '');
2590 except:
2591 reporter.errorXcpt('Unable to delete guest property "%s"' % (sName,));
2592 return False;
2593 return True;
2594
2595 def setExtraData(self, sKey, sValue):
2596 """
2597 Sets extra data.
2598 Returns the True on success, False on failure (logged).
2599 """
2600 try:
2601 self.o.machine.setExtraData(sKey, sValue);
2602 except:
2603 reporter.errorXcpt('IMachine::setExtraData("%s","%s") failed' % (sKey, sValue));
2604 return False;
2605 return True;
2606
2607 def getExtraData(self, sKey):
2608 """
2609 Gets extra data.
2610 Returns value on success, None on failure.
2611 """
2612 try:
2613 sValue = self.o.machine.getExtraData(sKey)
2614 except:
2615 reporter.errorXcpt('IMachine::getExtraData("%s") failed' % (sKey,))
2616 return None
2617 return sValue
2618
2619 def setupTeleporter(self, fEnabled=True, uPort = 6500, sAddress = '', sPassword = ''):
2620 """
2621 Sets up the teleporter for the VM.
2622 Returns True on success, False on failure (logged).
2623 """
2624 try:
2625 self.o.machine.teleporterAddress = sAddress;
2626 self.o.machine.teleporterPort = uPort;
2627 self.o.machine.teleporterPassword = sPassword;
2628 self.o.machine.teleporterEnabled = fEnabled;
2629 except:
2630 reporter.errorXcpt('setupTeleporter(%s, %s, %s, %s)' % (fEnabled, sPassword, uPort, sAddress));
2631 return False;
2632 return True;
2633
2634 def enableTeleporter(self, fEnable=True):
2635 """
2636 Enables or disables the teleporter of the VM.
2637 Returns True on success, False on failure (logged).
2638 """
2639 try:
2640 self.o.machine.teleporterEnabled = fEnable;
2641 except:
2642 reporter.errorXcpt('IMachine::teleporterEnabled=%s failed' % (fEnable));
2643 return False;
2644 return True;
2645
2646 def teleport(self, sHostname = 'localhost', uPort = 6500, sPassword = 'password', cMsMaxDowntime = 250):
2647 """
2648 Wrapper around the IConsole::teleport() method.
2649 Returns a progress object on success, None on failure (logged).
2650 """
2651 reporter.log2('"%s"::teleport(%s,%s,%s,%s)...' % (self.sName, sHostname, uPort, sPassword, cMsMaxDowntime));
2652 try:
2653 oProgress = self.o.console.teleport(sHostname, uPort, sPassword, cMsMaxDowntime)
2654 except:
2655 reporter.errorXcpt('IConsole::teleport(%s,%s,%s,%s) failed' % (sHostname, uPort, sPassword, cMsMaxDowntime));
2656 return None;
2657 return ProgressWrapper(oProgress, self.oVBoxMgr, self.oTstDrv, 'teleport %s' % (self.sName,));
2658
2659 def getOsType(self):
2660 """
2661 Gets the IGuestOSType interface for the machine.
2662
2663 return IGuestOSType interface on success, None + errorXcpt on failure.
2664 No exceptions raised.
2665 """
2666 try:
2667 sOsTypeId = self.o.machine.OSTypeId;
2668 except:
2669 reporter.errorXcpt('failed to obtain the OSTypeId for "%s"' % (self.sName));
2670 return None;
2671
2672 try:
2673 oOsType = self.oVBox.getGuestOSType(sOsTypeId);
2674 except:
2675 reporter.errorXcpt('getGuestOSType("%s") failed for "%s"' % (sOsTypeId, self.sName));
2676 return None;
2677
2678 return oOsType;
2679
2680 def setOsType(self, sNewTypeId):
2681 """
2682 Changes the OS type.
2683
2684 returns True on success, False + errorXcpt on failure.
2685 No exceptions raised.
2686 """
2687 try:
2688 self.o.machine.OSTypeId = sNewTypeId;
2689 except:
2690 reporter.errorXcpt('failed to set the OSTypeId for "%s" to "%s"' % (self.sName, sNewTypeId));
2691 return False;
2692 return True;
2693
2694
2695 def setParavirtProvider(self, iProvider):
2696 """
2697 Sets a paravirtualisation provider.
2698 Returns the True on success, False on failure (logged).
2699 """
2700 try:
2701 self.o.machine.paravirtProvider = iProvider
2702 except:
2703 reporter.errorXcpt('Unable to set paravirtualisation provider "%s"' % (iProvider,))
2704 return False;
2705 return True;
2706
2707
2708 def setupSerialToRawFile(self, iSerialPort, sRawFile):
2709 """
2710 Enables the given serial port (zero based) and redirects it to sRawFile.
2711 Returns the True on success, False on failure (logged).
2712 """
2713 try:
2714 oPort = self.o.machine.getSerialPort(iSerialPort);
2715 except:
2716 fRc = reporter.errorXcpt('failed to get serial port #%u' % (iSerialPort,));
2717 else:
2718 try:
2719 oPort.path = sRawFile;
2720 except:
2721 fRc = reporter.errorXcpt('failed to set the "path" property on serial port #%u to "%s"'
2722 % (iSerialPort, sRawFile));
2723 else:
2724 try:
2725 oPort.hostMode = vboxcon.PortMode_RawFile;
2726 except:
2727 fRc = reporter.errorXcpt('failed to set the "hostMode" property on serial port #%u to PortMode_RawFile'
2728 % (iSerialPort,));
2729 else:
2730 try:
2731 oPort.enabled = True;
2732 except:
2733 fRc = reporter.errorXcpt('failed to set the "enable" property on serial port #%u to True'
2734 % (iSerialPort,));
2735 else:
2736 reporter.log('set SerialPort[%s].enabled/hostMode/path=True/RawFile/%s' % (iSerialPort, sRawFile,));
2737 fRc = True;
2738 self.oTstDrv.processPendingEvents();
2739 return fRc;
2740
2741
2742 def enableSerialPort(self, iSerialPort):
2743 """
2744 Enables the given serial port setting the initial port mode to disconnected.
2745 """
2746 try:
2747 oPort = self.o.machine.getSerialPort(iSerialPort);
2748 except:
2749 fRc = reporter.errorXcpt('failed to get serial port #%u' % (iSerialPort,));
2750 else:
2751 try:
2752 oPort.hostMode = vboxcon.PortMode_Disconnected;
2753 except:
2754 fRc = reporter.errorXcpt('failed to set the "hostMode" property on serial port #%u to PortMode_Disconnected'
2755 % (iSerialPort,));
2756 else:
2757 try:
2758 oPort.enabled = True;
2759 except:
2760 fRc = reporter.errorXcpt('failed to set the "enable" property on serial port #%u to True'
2761 % (iSerialPort,));
2762 else:
2763 reporter.log('set SerialPort[%s].enabled/hostMode/=True/Disconnected' % (iSerialPort,));
2764 fRc = True;
2765 self.oTstDrv.processPendingEvents();
2766 return fRc;
2767
2768
2769 def changeSerialPortAttachment(self, iSerialPort, ePortMode, sPath, fServer):
2770 """
2771 Changes the attachment of the given serial port to the attachment config given.
2772 """
2773 try:
2774 oPort = self.o.machine.getSerialPort(iSerialPort);
2775 except:
2776 fRc = reporter.errorXcpt('failed to get serial port #%u' % (iSerialPort,));
2777 else:
2778 try:
2779 # Change port mode to disconnected first so changes get picked up by a potentially running VM.
2780 oPort.hostMode = vboxcon.PortMode_Disconnected;
2781 except:
2782 fRc = reporter.errorXcpt('failed to set the "hostMode" property on serial port #%u to PortMode_Disconnected'
2783 % (iSerialPort,));
2784 else:
2785 try:
2786 oPort.path = sPath;
2787 oPort.server = fServer;
2788 oPort.hostMode = ePortMode;
2789 except:
2790 fRc = reporter.errorXcpt('failed to configure the serial port');
2791 else:
2792 reporter.log('set SerialPort[%s].hostMode/path/server=%s/%s/%s'
2793 % (iSerialPort, ePortMode, sPath, fServer));
2794 fRc = True;
2795 self.oTstDrv.processPendingEvents();
2796 return fRc;
2797
2798 def setExecutionEngine(self, iVmExecEngine):
2799 """
2800 Sets a VM execution engine.
2801 Returns the True on success, False on failure (logged).
2802 """
2803 try:
2804 self.o.machine.VMExecutionEngine = iVmExecEngine;
2805 except:
2806 reporter.errorXcpt('Unable to set VM execution engine "%s"' % (iVmExecEngine,))
2807 return False;
2808 return True;
2809
2810 #
2811 # IConsole wrappers.
2812 #
2813
2814 def powerOff(self, fFudgeOnFailure = True):
2815 """
2816 Powers off the VM.
2817
2818 Returns True on success.
2819 Returns False on IConsole::powerDown() failure.
2820 Returns None if the progress object returns failure.
2821 """
2822 #
2823 # Deregister event handler before we power off the VM, otherwise we're
2824 # racing for VM process termination and cause misleading spurious
2825 # error messages in the event handling code, because the event objects
2826 # disappear.
2827 #
2828 # Note! Doing this before powerDown to try prevent numerous smoketest
2829 # timeouts on XPCOM hosts.
2830 #
2831 self.deregisterEventHandlerForTask();
2832
2833
2834 # Try power if off.
2835 try:
2836 oProgress = self.o.console.powerDown();
2837 except:
2838 reporter.logXcpt('IConsole::powerDown failed on %s' % (self.sName));
2839 if fFudgeOnFailure:
2840 self.oTstDrv.waitOnDirectSessionClose(self.oVM, 5000); # fudge
2841 self.waitForTask(1000); # fudge
2842 return False;
2843
2844 # Wait on power off operation to complete.
2845 rc = self.oTstDrv.waitOnProgress(oProgress);
2846 if rc < 0:
2847 self.close();
2848 if fFudgeOnFailure:
2849 vbox.reportError(oProgress, 'powerDown for "%s" failed' % (self.sName));
2850 self.oTstDrv.waitOnDirectSessionClose(self.oVM, 5000); # fudge
2851 return None;
2852
2853 # Wait for the VM to really power off or we'll fail to open a new session to it.
2854 self.oTstDrv.waitOnDirectSessionClose(self.oVM, 5000); # fudge
2855 return self.waitForTask(30 * 1000); # fudge
2856
2857 def saveState(self, fPause = True):
2858 """
2859 Saves state of the VM.
2860
2861 Returns True on success.
2862 Returns False on IConsole::saveState() failure.
2863 Returns None if the progress object returns Failure.
2864 """
2865
2866 if fPause is True \
2867 and self.oVM.state is vboxcon.MachineState_Running:
2868 self.o.console.pause();
2869 if self.oVM.state is not vboxcon.MachineState_Paused:
2870 reporter.error('pause for "%s" failed' % (self.sName));
2871 # Try saving state.
2872 try:
2873 if self.fpApiVer >= 5.0:
2874 oProgress = self.o.machine.saveState()
2875 else:
2876 oProgress = self.o.console.saveState()
2877 except:
2878 reporter.logXcpt('IMachine::saveState failed on %s' % (self.sName));
2879 return False;
2880
2881 # Wait for saving state operation to complete.
2882 rc = self.oTstDrv.waitOnProgress(oProgress);
2883 if rc < 0:
2884 self.close();
2885 return None;
2886
2887 # Wait for the VM to really terminate or we'll fail to open a new session to it.
2888 self.oTstDrv.waitOnDirectSessionClose(self.oVM, 5000); # fudge
2889 return self.waitForTask(30 * 1000); # fudge
2890
2891 def discardSavedState(self, fRemove = True):
2892 """
2893 Discards saved state of the VM.
2894
2895 Returns True on success.
2896 Returns False on IConsole::discardSaveState() failure.
2897 """
2898
2899 try:
2900 if self.fpApiVer >= 5.0:
2901 self.o.machine.discardSavedState(fRemove)
2902 else:
2903 self.o.console.discardSavedState(fRemove)
2904 except:
2905 reporter.logXcpt('IMachine::discardSavedState failed on %s' % (self.sName))
2906 return False
2907 return True
2908
2909 def restoreSnapshot(self, oSnapshot, fFudgeOnFailure = True):
2910 """
2911 Restores the given snapshot.
2912
2913 Returns True on success.
2914 Returns False on IMachine::restoreSnapshot() failure.
2915 Returns None if the progress object returns failure.
2916 """
2917 try:
2918 if self.fpApiVer >= 5.0:
2919 oProgress = self.o.machine.restoreSnapshot(oSnapshot);
2920 else:
2921 oProgress = self.o.console.restoreSnapshot(oSnapshot);
2922 except:
2923 reporter.logXcpt('IMachine::restoreSnapshot failed on %s' % (self.sName));
2924 if fFudgeOnFailure:
2925 self.oTstDrv.waitOnDirectSessionClose(self.oVM, 5000); # fudge
2926 self.waitForTask(1000); # fudge
2927 return False;
2928
2929 rc = self.oTstDrv.waitOnProgress(oProgress);
2930 if rc < 0:
2931 self.close();
2932 if fFudgeOnFailure:
2933 vbox.reportError(oProgress, 'restoreSnapshot for "%s" failed' % (self.sName));
2934 return None;
2935
2936 return self.waitForTask(30 * 1000);
2937
2938 def deleteSnapshot(self, oSnapshot, fFudgeOnFailure = True, cMsTimeout = 30 * 1000):
2939 """
2940 Deletes the given snapshot merging the diff image into the base.
2941
2942 Returns True on success.
2943 Returns False on IMachine::deleteSnapshot() failure.
2944 """
2945 try:
2946 if self.fpApiVer >= 5.0:
2947 oProgressCom = self.o.machine.deleteSnapshot(oSnapshot);
2948 else:
2949 oProgressCom = self.o.console.deleteSnapshot(oSnapshot);
2950 oProgress = ProgressWrapper(oProgressCom, self.oVBoxMgr, self.oTstDrv, 'Delete Snapshot %s' % (oSnapshot));
2951 oProgress.wait(cMsTimeout);
2952 oProgress.logResult();
2953 except:
2954 reporter.logXcpt('IMachine::deleteSnapshot failed on %s' % (self.sName));
2955 if fFudgeOnFailure:
2956 self.oTstDrv.waitOnDirectSessionClose(self.oVM, 5000); # fudge
2957 self.waitForTask(1000); # fudge
2958 return False;
2959
2960 return True;
2961
2962 def takeSnapshot(self, sName, sDescription = '', fPause = True, fFudgeOnFailure = True, cMsTimeout = 30 * 1000):
2963 """
2964 Takes a snapshot with the given name
2965
2966 Returns True on success.
2967 Returns False on IMachine::takeSnapshot() or VM state change failure.
2968 """
2969 try:
2970 if fPause is True \
2971 and self.oVM.state is vboxcon.MachineState_Running:
2972 self.o.console.pause();
2973 if self.fpApiVer >= 5.0:
2974 (oProgressCom, _) = self.o.machine.takeSnapshot(sName, sDescription, True);
2975 else:
2976 oProgressCom = self.o.console.takeSnapshot(sName, sDescription);
2977 oProgress = ProgressWrapper(oProgressCom, self.oVBoxMgr, self.oTstDrv, 'Take Snapshot %s' % (sName));
2978 oProgress.wait(cMsTimeout);
2979 oProgress.logResult();
2980 except:
2981 reporter.logXcpt('IMachine::takeSnapshot failed on %s' % (self.sName));
2982 if fFudgeOnFailure:
2983 self.oTstDrv.waitOnDirectSessionClose(self.oVM, 5000); # fudge
2984 self.waitForTask(1000); # fudge
2985 return False;
2986
2987 if fPause is True \
2988 and self.oVM.state is vboxcon.MachineState_Paused:
2989 self.o.console.resume();
2990
2991 return True;
2992
2993 def findSnapshot(self, sName):
2994 """
2995 Returns the snapshot object with the given name
2996
2997 Returns snapshot object on success.
2998 Returns None if there is no snapshot with the given name.
2999 """
3000 return self.oVM.findSnapshot(sName);
3001
3002 def takeScreenshot(self, sFilename, iScreenId=0):
3003 """
3004 Take screenshot from the given display and save it to specified file.
3005
3006 Returns True on success
3007 Returns False on failure.
3008 """
3009 try:
3010 if self.fpApiVer >= 5.0:
3011 iWidth, iHeight, _, _, _, _ = self.o.console.display.getScreenResolution(iScreenId)
3012 aPngData = self.o.console.display.takeScreenShotToArray(iScreenId, iWidth, iHeight,
3013 vboxcon.BitmapFormat_PNG)
3014 else:
3015 iWidth, iHeight, _, _, _ = self.o.console.display.getScreenResolution(iScreenId)
3016 aPngData = self.o.console.display.takeScreenShotPNGToArray(iScreenId, iWidth, iHeight)
3017 except:
3018 reporter.logXcpt("Unable to take screenshot")
3019 return False
3020
3021 with open(sFilename, 'wb') as oFile: # pylint: disable=unspecified-encoding
3022 oFile.write(aPngData)
3023
3024 return True
3025
3026 def attachUsbDevice(self, sUuid, sCaptureFilename = None):
3027 """
3028 Attach given USB device UUID to the VM.
3029
3030 Returns True on success
3031 Returns False on failure.
3032 """
3033 fRc = True;
3034 try:
3035 if sCaptureFilename is None:
3036 self.o.console.attachUSBDevice(sUuid, '');
3037 else:
3038 self.o.console.attachUSBDevice(sUuid, sCaptureFilename);
3039 except:
3040 reporter.logXcpt('Unable to attach USB device %s' % (sUuid,));
3041 fRc = False;
3042
3043 return fRc;
3044
3045 def detachUsbDevice(self, sUuid):
3046 """
3047 Detach given USB device UUID from the VM.
3048
3049 Returns True on success
3050 Returns False on failure.
3051 """
3052 fRc = True;
3053 try:
3054 _ = self.o.console.detachUSBDevice(sUuid);
3055 except:
3056 reporter.logXcpt('Unable to detach USB device %s' % (sUuid,));
3057 fRc = False;
3058
3059 return fRc;
3060
3061
3062 #
3063 # IMachineDebugger wrappers.
3064 #
3065
3066 def queryOsKernelLog(self):
3067 """
3068 Tries to get the OS kernel log using the VM debugger interface.
3069
3070 Returns string containing the kernel log on success.
3071 Returns None on failure.
3072 """
3073 sOsKernelLog = None;
3074 try:
3075 self.o.console.debugger.loadPlugIn('all');
3076 except:
3077 reporter.logXcpt('Unable to load debugger plugins');
3078 else:
3079 try:
3080 sOsDetected = self.o.console.debugger.detectOS();
3081 except:
3082 reporter.logXcpt('Failed to detect the guest OS');
3083 else:
3084 try:
3085 sOsKernelLog = self.o.console.debugger.queryOSKernelLog(0);
3086 except:
3087 reporter.logXcpt('Unable to get the guest OS (%s) kernel log' % (sOsDetected,));
3088 return sOsKernelLog;
3089
3090 def queryDbgInfo(self, sItem, sArg = '', sDefault = None):
3091 """
3092 Simple wrapper around IMachineDebugger::info.
3093
3094 Returns string on success, sDefault on failure (logged).
3095 """
3096 try:
3097 return self.o.console.debugger.info(sItem, sArg);
3098 except:
3099 reporter.logXcpt('Unable to query "%s" with arg "%s"' % (sItem, sArg,));
3100 return sDefault;
3101
3102 def queryDbgInfoVgaText(self, sArg = 'all'):
3103 """
3104 Tries to get the 'info vgatext' output, provided we're in next mode.
3105
3106 Returns string containing text on success.
3107 Returns None on failure or not text mode.
3108 """
3109 sVgaText = None;
3110 try:
3111 sVgaText = self.o.console.debugger.info('vgatext', sArg);
3112 if sVgaText.startswith('Not in text mode!'):
3113 sVgaText = None;
3114 except:
3115 reporter.logXcpt('Unable to query vgatext with arg "%s"' % (sArg,));
3116 return sVgaText;
3117
3118 def queryDbgGuestStack(self, iCpu = 0):
3119 """
3120 Returns the guest stack for the given VCPU.
3121
3122 Returns string containing the guest stack for the selected VCPU on success.
3123 Returns None on failure.
3124 """
3125
3126 #
3127 # Load all plugins first and try to detect the OS so we can
3128 # get nicer stack traces.
3129 #
3130 try:
3131 self.o.console.debugger.loadPlugIn('all');
3132 except:
3133 reporter.logXcpt('Unable to load debugger plugins');
3134 else:
3135 try:
3136 sOsDetected = self.o.console.debugger.detectOS();
3137 _ = sOsDetected;
3138 except:
3139 reporter.logXcpt('Failed to detect the guest OS');
3140
3141 sGuestStack = None;
3142 try:
3143 sGuestStack = self.o.console.debugger.dumpGuestStack(iCpu);
3144 except:
3145 reporter.logXcpt('Unable to query guest stack for CPU %s' % (iCpu, ));
3146
3147 return sGuestStack;
3148
3149
3150 #
3151 # Other methods.
3152 #
3153
3154 def getPrimaryIp(self):
3155 """
3156 Tries to obtain the primary IP address of the guest via the guest
3157 properties.
3158
3159 Returns IP address on success.
3160 Returns empty string on failure.
3161 """
3162 sIpAddr = self.getGuestPropertyValue('/VirtualBox/GuestInfo/Net/0/V4/IP');
3163 if vbox.isIpAddrValid(sIpAddr):
3164 return sIpAddr;
3165 return '';
3166
3167 def getPid(self):
3168 """
3169 Gets the process ID for the direct session unless it's ourselves.
3170 """
3171 if self.uPid is None and self.o is not None and self.fRemoteSession:
3172 try:
3173 if self.fpApiVer >= 4.2:
3174 uPid = self.o.machine.sessionPID;
3175 else:
3176 uPid = self.o.machine.sessionPid;
3177 if uPid != os.getpid() and uPid != 0xffffffff:
3178 self.uPid = uPid;
3179 except Exception as oXcpt:
3180 if vbox.ComError.equal(oXcpt, vbox.ComError.E_UNEXPECTED):
3181 try:
3182 if self.fpApiVer >= 4.2:
3183 uPid = self.oVM.sessionPID;
3184 else:
3185 uPid = self.oVM.sessionPid;
3186 if uPid != os.getpid() and uPid != 0xffffffff:
3187 self.uPid = uPid;
3188 except:
3189 reporter.log2Xcpt();
3190 else:
3191 reporter.log2Xcpt();
3192 if self.uPid is not None:
3193 reporter.log2('getPid: %u' % (self.uPid,));
3194 self.fPidFile = self.oTstDrv.pidFileAdd(self.uPid, 'vm_%s' % (self.sName,), # Set-uid-to-root is similar to SUDO.
3195 fSudo = True);
3196 return self.uPid;
3197
3198 def addLogsToReport(self, cReleaseLogs = 1):
3199 """
3200 Retrieves and adds the release and debug logs to the test report.
3201 """
3202 fRc = True;
3203
3204 # Add each of the requested release logs to the report.
3205 for iLog in range(0, cReleaseLogs):
3206 try:
3207 if self.fpApiVer >= 3.2:
3208 sLogFile = self.oVM.queryLogFilename(iLog);
3209 elif iLog > 0:
3210 sLogFile = '%s/VBox.log' % (self.oVM.logFolder,);
3211 else:
3212 sLogFile = '%s/VBox.log.%u' % (self.oVM.logFolder, iLog);
3213 except:
3214 reporter.logXcpt('iLog=%s' % (iLog,));
3215 fRc = False;
3216 else:
3217 if sLogFile is not None and sLogFile != '': # the None bit is for a 3.2.0 bug.
3218 reporter.addLogFile(sLogFile, 'log/release/vm', '%s #%u' % (self.sName, iLog),
3219 sAltName = '%s-%s' % (self.sName, os.path.basename(sLogFile),));
3220
3221 # Now for the hardened windows startup log.
3222 try:
3223 sLogFile = os.path.join(self.oVM.logFolder, 'VBoxHardening.log');
3224 except:
3225 reporter.logXcpt();
3226 fRc = False;
3227 else:
3228 if os.path.isfile(sLogFile):
3229 reporter.addLogFile(sLogFile, 'log/release/vm', '%s hardening log' % (self.sName, ),
3230 sAltName = '%s-%s' % (self.sName, os.path.basename(sLogFile),));
3231
3232 # Now for the debug log.
3233 if self.sLogFile is not None and os.path.isfile(self.sLogFile):
3234 reporter.addLogFile(self.sLogFile, 'log/debug/vm', '%s debug' % (self.sName, ),
3235 sAltName = '%s-%s' % (self.sName, os.path.basename(self.sLogFile),));
3236
3237 return fRc;
3238
3239 def registerDerivedEventHandler(self, oSubClass, dArgs = None, fMustSucceed = True):
3240 """
3241 Create an instance of the given ConsoleEventHandlerBase sub-class and
3242 register it.
3243
3244 The new instance is returned on success. None is returned on error.
3245 """
3246
3247 # We need a console object.
3248 try:
3249 oConsole = self.o.console;
3250 except Exception as oXcpt:
3251 if fMustSucceed or vbox.ComError.notEqual(oXcpt, vbox.ComError.E_UNEXPECTED):
3252 reporter.errorXcpt('Failed to get ISession::console for "%s"' % (self.sName, ));
3253 return None;
3254
3255 # Add the base class arguments.
3256 dArgsCopy = dArgs.copy() if dArgs is not None else {};
3257 dArgsCopy['oSession'] = self;
3258 dArgsCopy['oConsole'] = oConsole;
3259 sLogSuffix = 'on %s' % (self.sName,)
3260 return oSubClass.registerDerivedEventHandler(self.oVBoxMgr, self.fpApiVer, oSubClass, dArgsCopy,
3261 oConsole, 'IConsole', 'IConsoleCallback',
3262 fMustSucceed = fMustSucceed, sLogSuffix = sLogSuffix);
3263
3264 def enableVmmDevTestingPart(self, fEnabled, fEnableMMIO = False):
3265 """
3266 Enables the testing part of the VMMDev.
3267
3268 Returns True on success and False on failure. Error information is logged.
3269 """
3270 fRc = True;
3271 try:
3272 self.o.machine.setExtraData('VBoxInternal/Devices/VMMDev/0/Config/TestingEnabled',
3273 '1' if fEnabled else '');
3274 self.o.machine.setExtraData('VBoxInternal/Devices/VMMDev/0/Config/TestingMMIO',
3275 '1' if fEnableMMIO and fEnabled else '');
3276 except:
3277 reporter.errorXcpt('VM name "%s", fEnabled=%s' % (self.sName, fEnabled));
3278 fRc = False;
3279 else:
3280 reporter.log('set VMMDevTesting=%s for "%s"' % (fEnabled, self.sName));
3281 self.oTstDrv.processPendingEvents();
3282 return fRc;
3283
3284 #
3285 # Test eXecution Service methods.
3286 #
3287
3288 def txsConnectViaTcp(self, cMsTimeout = 10*60000, sIpAddr = None, fNatForwardingForTxs = False):
3289 """
3290 Connects to the TXS using TCP/IP as transport. If no IP or MAC is
3291 addresses are specified, we'll get the IP from the guest additions.
3292
3293 Returns a TxsConnectTask object on success, None + log on failure.
3294 """
3295 # If the VM is configured with a NAT interface, connect to local host.
3296 fReversedSetup = False;
3297 fUseNatForTxs = False;
3298 sMacAddr = None;
3299 oIDhcpServer = None;
3300 if sIpAddr is None:
3301 try:
3302 oNic = self.oVM.getNetworkAdapter(0);
3303 enmAttachmentType = oNic.attachmentType;
3304 if enmAttachmentType == vboxcon.NetworkAttachmentType_NAT:
3305 fUseNatForTxs = True;
3306 elif enmAttachmentType == vboxcon.NetworkAttachmentType_HostOnly and not sIpAddr:
3307 # Get the MAC address and find the DHCP server.
3308 sMacAddr = oNic.MACAddress;
3309 sHostOnlyNIC = oNic.hostOnlyInterface;
3310 oIHostOnlyIf = self.oVBox.host.findHostNetworkInterfaceByName(sHostOnlyNIC);
3311 sHostOnlyNet = oIHostOnlyIf.networkName;
3312 oIDhcpServer = self.oVBox.findDHCPServerByNetworkName(sHostOnlyNet);
3313 except:
3314 reporter.errorXcpt();
3315 return None;
3316
3317 if fUseNatForTxs:
3318 fReversedSetup = not fNatForwardingForTxs;
3319 sIpAddr = '127.0.0.1';
3320
3321 # Kick off the task.
3322 try:
3323 oTask = TxsConnectTask(self, cMsTimeout, sIpAddr, sMacAddr, oIDhcpServer, fReversedSetup,
3324 fnProcessEvents = self.oTstDrv.processPendingEvents);
3325 except:
3326 reporter.errorXcpt();
3327 oTask = None;
3328 return oTask;
3329
3330 def txsTryConnectViaTcp(self, cMsTimeout, sHostname, fReversed = False):
3331 """
3332 Attempts to connect to a TXS instance.
3333
3334 Returns True if a connection was established, False if not (only grave
3335 failures are logged as errors).
3336
3337 Note! The timeout is more of a guideline...
3338 """
3339
3340 if sHostname is None or sHostname.strip() == '':
3341 raise base.GenError('Empty sHostname is not implemented yet');
3342
3343 oTxsSession = txsclient.tryOpenTcpSession(cMsTimeout, sHostname, fReversedSetup = fReversed,
3344 cMsIdleFudge = cMsTimeout // 2,
3345 fnProcessEvents = self.oTstDrv.processPendingEvents);
3346 if oTxsSession is None:
3347 return False;
3348
3349 # Wait for the connect task to time out.
3350 self.oTstDrv.addTask(oTxsSession);
3351 self.oTstDrv.processPendingEvents();
3352 oRc = self.oTstDrv.waitForTasks(cMsTimeout);
3353 self.oTstDrv.removeTask(oTxsSession);
3354 if oRc != oTxsSession:
3355 if oRc is not None:
3356 reporter.log('oRc=%s, expected %s' % (oRc, oTxsSession));
3357 self.oTstDrv.processPendingEvents();
3358 oTxsSession.cancelTask(); # this is synchronous
3359 return False;
3360
3361 # Check the status.
3362 reporter.log2('TxsSession is ready, isSuccess() -> %s.' % (oTxsSession.isSuccess(),));
3363 if not oTxsSession.isSuccess():
3364 return False;
3365
3366 reporter.log2('Disconnecting from TXS...');
3367 return oTxsSession.syncDisconnect();
3368
3369
3370
3371class TxsConnectTask(TdTaskBase):
3372 """
3373 Class that takes care of connecting to a VM.
3374 """
3375
3376 class TxsConnectTaskVBoxCallback(vbox.VirtualBoxEventHandlerBase):
3377 """ Class for looking for IPv4 address changes on interface 0."""
3378 def __init__(self, dArgs):
3379 vbox.VirtualBoxEventHandlerBase.__init__(self, dArgs);
3380 self.oParentTask = dArgs['oParentTask'];
3381 self.sMachineId = dArgs['sMachineId'];
3382
3383 def onGuestPropertyChange(self, sMachineId, sName, sValue, sFlags, fWasDeleted):
3384 """Look for IP address."""
3385 reporter.log2('onGuestPropertyChange(,%s,%s,%s,%s,%s)' % (sMachineId, sName, sValue, sFlags, fWasDeleted));
3386 if sMachineId == self.sMachineId \
3387 and sName == '/VirtualBox/GuestInfo/Net/0/V4/IP':
3388 oParentTask = self.oParentTask;
3389 if oParentTask:
3390 oParentTask._setIp(sValue); # pylint: disable=protected-access
3391
3392
3393 def __init__(self, oSession, cMsTimeout, sIpAddr, sMacAddr, oIDhcpServer, fReversedSetup, fnProcessEvents = None):
3394 TdTaskBase.__init__(self, utils.getCallerName(), fnProcessEvents = fnProcessEvents);
3395 self.cMsTimeout = cMsTimeout;
3396 self.fnProcessEvents = fnProcessEvents;
3397 self.sIpAddr = None;
3398 self.sNextIpAddr = None;
3399 self.sMacAddr = sMacAddr;
3400 self.oIDhcpServer = oIDhcpServer;
3401 self.fReversedSetup = fReversedSetup;
3402 self.oVBoxEventHandler = None;
3403 self.oTxsSession = None;
3404
3405 # Check that the input makes sense:
3406 if (sMacAddr is None) != (oIDhcpServer is None) \
3407 or (sMacAddr and fReversedSetup) \
3408 or (sMacAddr and sIpAddr):
3409 reporter.error('TxsConnectTask sMacAddr=%s oIDhcpServer=%s sIpAddr=%s fReversedSetup=%s'
3410 % (sMacAddr, oIDhcpServer, sIpAddr, fReversedSetup,));
3411 raise base.GenError();
3412
3413 reporter.log2('TxsConnectTask: sIpAddr=%s fReversedSetup=%s' % (sIpAddr, fReversedSetup))
3414 if fReversedSetup is True:
3415 self._openTcpSession(sIpAddr, fReversedSetup = True);
3416 elif sIpAddr is not None and sIpAddr.strip() != '':
3417 self._openTcpSession(sIpAddr, cMsIdleFudge = 5000);
3418 else:
3419 #
3420 # If we've got no IP address, register callbacks that listens for
3421 # the primary network adaptor of the VM to set a IPv4 guest prop.
3422 # Note! The order in which things are done here is kind of important.
3423 #
3424
3425 # 0. The caller zaps the property before starting the VM.
3426 #try:
3427 # oSession.delGuestPropertyValue('/VirtualBox/GuestInfo/Net/0/V4/IP');
3428 #except:
3429 # reporter.logXcpt();
3430
3431 # 1. Register the callback / event listener object.
3432 dArgs = {'oParentTask':self, 'sMachineId':oSession.o.machine.id};
3433 self.oVBoxEventHandler = oSession.oVBox.registerDerivedEventHandler(self.TxsConnectTaskVBoxCallback, dArgs);
3434
3435 # 2. Query the guest properties.
3436 try:
3437 sIpAddr = oSession.getGuestPropertyValue('/VirtualBox/GuestInfo/Net/0/V4/IP');
3438 except:
3439 reporter.errorXcpt('IMachine::getGuestPropertyValue("/VirtualBox/GuestInfo/Net/0/V4/IP") failed');
3440 self._deregisterEventHandler();
3441 raise;
3442 if sIpAddr is not None:
3443 self._setIp(sIpAddr);
3444
3445 #
3446 # If the network adapter of the VM is host-only we can talk poll IDHCPServer
3447 # for the guest IP, allowing us to detect it for VMs without guest additions.
3448 # This will when we're polled.
3449 #
3450 if sMacAddr is not None:
3451 assert self.oIDhcpServer is not None;
3452
3453
3454 # end __init__
3455
3456 def __del__(self):
3457 """ Make sure we deregister the callback. """
3458 self._deregisterEventHandler();
3459 return TdTaskBase.__del__(self);
3460
3461 def toString(self):
3462 return '<%s cMsTimeout=%s, sIpAddr=%s, sNextIpAddr=%s, sMacAddr=%s, fReversedSetup=%s,' \
3463 ' oTxsSession=%s oVBoxEventHandler=%s>' \
3464 % (TdTaskBase.toString(self), self.cMsTimeout, self.sIpAddr, self.sNextIpAddr, self.sMacAddr, self.fReversedSetup,
3465 self.oTxsSession, self.oVBoxEventHandler);
3466
3467 def _deregisterEventHandler(self):
3468 """Deregisters the event handler."""
3469 fRc = True;
3470 oVBoxEventHandler = self.oVBoxEventHandler;
3471 if oVBoxEventHandler is not None:
3472 self.oVBoxEventHandler = None;
3473 fRc = oVBoxEventHandler.unregister();
3474 oVBoxEventHandler.oParentTask = None; # Try avoid cylic deps.
3475 return fRc;
3476
3477 def _setIp(self, sIpAddr, fInitCall = False):
3478 """Called when we get an IP. Will create a TXS session and signal the task."""
3479 sIpAddr = sIpAddr.strip();
3480
3481 if sIpAddr is not None \
3482 and sIpAddr != '':
3483 if vbox.isIpAddrValid(sIpAddr) or fInitCall:
3484 try:
3485 for s in sIpAddr.split('.'):
3486 i = int(s);
3487 if str(i) != s:
3488 raise Exception();
3489 except:
3490 reporter.fatalXcpt();
3491 else:
3492 reporter.log('TxsConnectTask: opening session to ip "%s"' % (sIpAddr));
3493 self._openTcpSession(sIpAddr, cMsIdleFudge = 5000);
3494 return None;
3495
3496 reporter.log('TxsConnectTask: Ignoring Bad ip "%s"' % (sIpAddr));
3497 else:
3498 reporter.log2('TxsConnectTask: Ignoring empty ip "%s"' % (sIpAddr));
3499 return None;
3500
3501 def _openTcpSession(self, sIpAddr, uPort = None, fReversedSetup = False, cMsIdleFudge = 0):
3502 """
3503 Calls txsclient.openTcpSession and switches our task to reflect the
3504 state of the subtask.
3505 """
3506 self.oCv.acquire();
3507 if self.oTxsSession is None:
3508 reporter.log2('_openTcpSession: sIpAddr=%s, uPort=%d, fReversedSetup=%s' %
3509 (sIpAddr, uPort if uPort is not None else 0, fReversedSetup));
3510 self.sIpAddr = sIpAddr;
3511 self.oTxsSession = txsclient.openTcpSession(self.cMsTimeout, sIpAddr, uPort, fReversedSetup,
3512 cMsIdleFudge, fnProcessEvents = self.fnProcessEvents);
3513 self.oTxsSession.setTaskOwner(self);
3514 else:
3515 self.sNextIpAddr = sIpAddr;
3516 reporter.log2('_openTcpSession: sNextIpAddr=%s' % (sIpAddr,));
3517 self.oCv.release();
3518 return None;
3519
3520 def notifyAboutReadyTask(self, oTxsSession):
3521 """
3522 Called by the TXS session task when it's done.
3523
3524 We'll signal the task completed or retry depending on the result.
3525 """
3526
3527 self.oCv.acquire();
3528
3529 # Disassociate ourselves with the session (avoid cyclic ref)
3530 oTxsSession.setTaskOwner(None);
3531 fSuccess = oTxsSession.isSuccess();
3532 if self.oTxsSession is not None:
3533 if not fSuccess:
3534 self.oTxsSession = None;
3535 if fSuccess and self.fReversedSetup:
3536 self.sIpAddr = oTxsSession.oTransport.sHostname;
3537 else:
3538 fSuccess = False;
3539
3540 # Signal done, or retry?
3541 fDeregister = False;
3542 if fSuccess \
3543 or self.fReversedSetup \
3544 or self.getAgeAsMs() >= self.cMsTimeout:
3545 self.signalTaskLocked();
3546 fDeregister = True;
3547 else:
3548 sIpAddr = self.sNextIpAddr if self.sNextIpAddr is not None else self.sIpAddr;
3549 self._openTcpSession(sIpAddr, cMsIdleFudge = 5000);
3550
3551 self.oCv.release();
3552
3553 # If we're done, deregister the callback (w/o owning lock). It will
3554 if fDeregister:
3555 self._deregisterEventHandler();
3556 return True;
3557
3558 def _pollDhcpServer(self):
3559 """
3560 Polls the DHCP server by MAC address in host-only setups.
3561 """
3562
3563 if self.sIpAddr:
3564 return False;
3565
3566 if self.oIDhcpServer is None or not self.sMacAddr:
3567 return False;
3568
3569 try:
3570 (sIpAddr, sState, secIssued, secExpire) = self.oIDhcpServer.findLeaseByMAC(self.sMacAddr, 0);
3571 except:
3572 reporter.log4Xcpt('sMacAddr=%s' % (self.sMacAddr,));
3573 return False;
3574
3575 secNow = utils.secondsSinceUnixEpoch();
3576 reporter.log2('dhcp poll: secNow=%s secExpire=%s secIssued=%s sState=%s sIpAddr=%s'
3577 % (secNow, secExpire, secIssued, sState, sIpAddr,));
3578 if secNow > secExpire or sState != 'acked' or not sIpAddr:
3579 return False;
3580
3581 reporter.log('dhcp poll: sIpAddr=%s secExpire=%s (%s TTL) secIssued=%s (%s ago)'
3582 % (sIpAddr, secExpire, secExpire - secNow, secIssued, secNow - secIssued,));
3583 self._setIp(sIpAddr);
3584 return True;
3585
3586 #
3587 # Task methods
3588 #
3589
3590 def pollTask(self, fLocked = False):
3591 """
3592 Overridden pollTask method.
3593 """
3594 self._pollDhcpServer();
3595 return TdTaskBase.pollTask(self, fLocked);
3596
3597 #
3598 # Public methods
3599 #
3600
3601 def getResult(self):
3602 """
3603 Returns the connected TXS session object on success.
3604 Returns None on failure or if the task has not yet completed.
3605 """
3606 self.oCv.acquire();
3607 oTxsSession = self.oTxsSession;
3608 self.oCv.release();
3609
3610 if oTxsSession is not None and not oTxsSession.isSuccess():
3611 oTxsSession = None;
3612 return oTxsSession;
3613
3614 def cancelTask(self):
3615 """ Cancels the task. """
3616 self._deregisterEventHandler(); # (make sure to avoid cyclic fun)
3617 self.oCv.acquire();
3618 if not self.fSignalled:
3619 oTxsSession = self.oTxsSession;
3620 if oTxsSession is not None:
3621 self.oCv.release();
3622 oTxsSession.setTaskOwner(None);
3623 oTxsSession.cancelTask();
3624 oTxsSession.waitForTask(1000);
3625 self.oCv.acquire();
3626 self.signalTaskLocked();
3627 self.oCv.release();
3628 return True;
3629
3630
3631
3632class AdditionsStatusTask(TdTaskBase):
3633 """
3634 Class that takes care of waiting till the guest additions are in a given state.
3635 """
3636
3637 class AdditionsStatusTaskCallback(vbox.EventHandlerBase):
3638 """ Class for looking for IPv4 address changes on interface 0."""
3639 def __init__(self, dArgs):
3640 self.oParentTask = dArgs['oParentTask'];
3641 vbox.EventHandlerBase.__init__(self, dArgs, self.oParentTask.oSession.fpApiVer,
3642 'AdditionsStatusTaskCallback/%s' % (self.oParentTask.oSession.sName,));
3643
3644 def handleEvent(self, oEvt):
3645 try:
3646 enmType = oEvt.type;
3647 except:
3648 reporter.errorXcpt();
3649 else:
3650 reporter.log2('AdditionsStatusTaskCallback:handleEvent: enmType=%s' % (enmType,));
3651 if enmType == vboxcon.VBoxEventType_OnGuestAdditionsStatusChanged:
3652 oParentTask = self.oParentTask;
3653 if oParentTask:
3654 oParentTask.pollTask();
3655
3656 # end
3657
3658
3659 def __init__(self, oSession, oIGuest, cMsTimeout = 120000, aenmWaitForRunLevels = None, aenmWaitForActive = None,
3660 aenmWaitForInactive = None):
3661 """
3662 aenmWaitForRunLevels - List of run level values to wait for (success if one matches).
3663 aenmWaitForActive - List facilities (type values) that must be active.
3664 aenmWaitForInactive - List facilities (type values) that must be inactive.
3665
3666 The default is to wait for AdditionsRunLevelType_Userland if all three lists
3667 are unspecified or empty.
3668 """
3669 TdTaskBase.__init__(self, utils.getCallerName());
3670 self.oSession = oSession # type: vboxwrappers.SessionWrapper
3671 self.oIGuest = oIGuest;
3672 self.cMsTimeout = cMsTimeout;
3673 self.fSucceeded = False;
3674 self.oVBoxEventHandler = None;
3675 self.aenmWaitForRunLevels = aenmWaitForRunLevels if aenmWaitForRunLevels else [];
3676 self.aenmWaitForActive = aenmWaitForActive if aenmWaitForActive else [];
3677 self.aenmWaitForInactive = aenmWaitForInactive if aenmWaitForInactive else [];
3678
3679 # Provide a sensible default if nothing is given.
3680 if not self.aenmWaitForRunLevels and not self.aenmWaitForActive and not self.aenmWaitForInactive:
3681 self.aenmWaitForRunLevels = [vboxcon.AdditionsRunLevelType_Userland,];
3682
3683 # Register the event handler on hosts which has it:
3684 if oSession.fpApiVer >= 6.1 or hasattr(vboxcon, 'VBoxEventType_OnGuestAdditionsStatusChanged'):
3685 aenmEvents = (vboxcon.VBoxEventType_OnGuestAdditionsStatusChanged,);
3686 dArgs = {
3687 'oParentTask': self,
3688 };
3689 self.oVBoxEventHandler = vbox.EventHandlerBase.registerDerivedEventHandler(oSession.oVBoxMgr,
3690 oSession.fpApiVer,
3691 self.AdditionsStatusTaskCallback,
3692 dArgs,
3693 oIGuest,
3694 'IGuest',
3695 'AdditionsStatusTaskCallback',
3696 aenmEvents = aenmEvents);
3697 reporter.log2('AdditionsStatusTask: %s' % (self.toString(), ));
3698
3699 def __del__(self):
3700 """ Make sure we deregister the callback. """
3701 self._deregisterEventHandler();
3702 self.oIGuest = None;
3703 return TdTaskBase.__del__(self);
3704
3705 def toString(self):
3706 return '<%s cMsTimeout=%s, fSucceeded=%s, aenmWaitForRunLevels=%s, aenmWaitForActive=%s, aenmWaitForInactive=%s, ' \
3707 'oVBoxEventHandler=%s>' \
3708 % (TdTaskBase.toString(self), self.cMsTimeout, self.fSucceeded, self.aenmWaitForRunLevels, self.aenmWaitForActive,
3709 self.aenmWaitForInactive, self.oVBoxEventHandler,);
3710
3711 def _deregisterEventHandler(self):
3712 """Deregisters the event handler."""
3713 fRc = True;
3714 oVBoxEventHandler = self.oVBoxEventHandler;
3715 if oVBoxEventHandler is not None:
3716 self.oVBoxEventHandler = None;
3717 fRc = oVBoxEventHandler.unregister();
3718 oVBoxEventHandler.oParentTask = None; # Try avoid cylic deps.
3719 return fRc;
3720
3721 def _poll(self):
3722 """
3723 Internal worker for pollTask() that returns the new signalled state.
3724 """
3725
3726 #
3727 # Check if any of the runlevels we wait for have been reached:
3728 #
3729 if self.aenmWaitForRunLevels:
3730 try:
3731 enmRunLevel = self.oIGuest.additionsRunLevel;
3732 except:
3733 reporter.errorXcpt();
3734 return True;
3735 if enmRunLevel not in self.aenmWaitForRunLevels:
3736 reporter.log6('AdditionsStatusTask/poll: enmRunLevel=%s not in %s' % (enmRunLevel, self.aenmWaitForRunLevels,));
3737 return False;
3738 reporter.log2('AdditionsStatusTask/poll: enmRunLevel=%s matched %s!' % (enmRunLevel, self.aenmWaitForRunLevels,));
3739
3740
3741 #
3742 # Check for the facilities that must all be active.
3743 #
3744 for enmFacility in self.aenmWaitForActive:
3745 try:
3746 (enmStatus, _) = self.oIGuest.getFacilityStatus(enmFacility);
3747 except:
3748 reporter.errorXcpt('enmFacility=%s' % (enmFacility,));
3749 return True;
3750 if enmStatus != vboxcon.AdditionsFacilityStatus_Active:
3751 reporter.log2('AdditionsStatusTask/poll: enmFacility=%s not active: %s' % (enmFacility, enmStatus,));
3752 return False;
3753
3754 #
3755 # Check for the facilities that must all be inactive or terminated.
3756 #
3757 for enmFacility in self.aenmWaitForInactive:
3758 try:
3759 (enmStatus, _) = self.oIGuest.getFacilityStatus(enmFacility);
3760 except:
3761 reporter.errorXcpt('enmFacility=%s' % (enmFacility,));
3762 return True;
3763 if enmStatus not in (vboxcon.AdditionsFacilityStatus_Inactive,
3764 vboxcon.AdditionsFacilityStatus_Terminated):
3765 reporter.log2('AdditionsStatusTask/poll: enmFacility=%s not inactive: %s' % (enmFacility, enmStatus,));
3766 return False;
3767
3768
3769 reporter.log('AdditionsStatusTask: Poll succeeded, signalling...');
3770 self.fSucceeded = True;
3771 return True;
3772
3773
3774 #
3775 # Task methods
3776 #
3777
3778 def pollTask(self, fLocked = False):
3779 """
3780 Overridden pollTask method.
3781 """
3782 if not fLocked:
3783 self.lockTask();
3784
3785 fDeregister = False;
3786 fRc = self.fSignalled;
3787 if not fRc:
3788 fRc = self._poll();
3789 if fRc or self.getAgeAsMs() >= self.cMsTimeout:
3790 self.signalTaskLocked();
3791 fDeregister = True;
3792
3793 if not fLocked:
3794 self.unlockTask();
3795
3796 # If we're done, deregister the event callback (w/o owning lock).
3797 if fDeregister:
3798 self._deregisterEventHandler();
3799 return fRc;
3800
3801 def getResult(self):
3802 """
3803 Returns true if the we succeeded.
3804 Returns false if not. If the task is signalled already, then we
3805 encountered a problem while polling.
3806 """
3807 return self.fSucceeded;
3808
3809 def cancelTask(self):
3810 """
3811 Cancels the task.
3812 Just to actively disengage the event handler.
3813 """
3814 self._deregisterEventHandler();
3815 return True;
Note: See TracBrowser for help on using the repository browser.

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