VirtualBox

source: vbox/trunk/src/VBox/Main/testcase/tstAPI.cpp@ 16734

Last change on this file since 16734 was 16734, checked in by vboxsync, 16 years ago

Correct some bitrot: #include <iprt/thread.h> for RTThreadSleep().

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 55.8 KB
Line 
1/** @file
2 *
3 * tstAPI - test program for our COM/XPCOM interface
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22#include <stdio.h>
23#include <stdlib.h>
24
25#include <VBox/com/com.h>
26#include <VBox/com/string.h>
27#include <VBox/com/array.h>
28#include <VBox/com/Guid.h>
29#include <VBox/com/ErrorInfo.h>
30#include <VBox/com/errorprint_legacy.h>
31#include <VBox/com/EventQueue.h>
32
33#include <VBox/com/VirtualBox.h>
34
35using namespace com;
36
37#define LOG_ENABLED
38#define LOG_GROUP LOG_GROUP_MAIN
39#define LOG_INSTANCE NULL
40#include <VBox/log.h>
41
42#include <iprt/initterm.h>
43#include <iprt/path.h>
44#include <iprt/param.h>
45#include <iprt/stream.h>
46#include <iprt/thread.h>
47
48#define printf RTPrintf
49
50
51// forward declarations
52///////////////////////////////////////////////////////////////////////////////
53
54static Bstr getObjectName(ComPtr<IVirtualBox> aVirtualBox,
55 ComPtr<IUnknown> aObject);
56static void queryMetrics (ComPtr<IVirtualBox> aVirtualBox,
57 ComPtr <IPerformanceCollector> collector,
58 ComSafeArrayIn (IUnknown *, objects));
59static void listAffectedMetrics(ComPtr<IVirtualBox> aVirtualBox,
60 ComSafeArrayIn(IPerformanceMetric*, aMetrics));
61
62// funcs
63///////////////////////////////////////////////////////////////////////////////
64
65HRESULT readAndChangeMachineSettings (IMachine *machine, IMachine *readonlyMachine = 0)
66{
67 HRESULT rc = S_OK;
68
69 Bstr name;
70 printf ("Getting machine name...\n");
71 CHECK_RC_RET (machine->COMGETTER(Name) (name.asOutParam()));
72 printf ("Name: {%ls}\n", name.raw());
73
74 printf("Getting machine GUID...\n");
75 Guid guid;
76 CHECK_RC (machine->COMGETTER(Id) (guid.asOutParam()));
77 if (SUCCEEDED (rc) && !guid.isEmpty()) {
78 printf ("Guid::toString(): {%s}\n", (const char *) guid.toString());
79 } else {
80 printf ("WARNING: there's no GUID!");
81 }
82
83 ULONG memorySize;
84 printf ("Getting memory size...\n");
85 CHECK_RC_RET (machine->COMGETTER(MemorySize) (&memorySize));
86 printf ("Memory size: %d\n", memorySize);
87
88 MachineState_T machineState;
89 printf ("Getting machine state...\n");
90 CHECK_RC_RET (machine->COMGETTER(State) (&machineState));
91 printf ("Machine state: %d\n", machineState);
92
93 BOOL modified;
94 printf ("Are any settings modified?...\n");
95 CHECK_RC (machine->COMGETTER(SettingsModified) (&modified));
96 if (SUCCEEDED (rc))
97 printf ("%s\n", modified ? "yes" : "no");
98
99 ULONG memorySizeBig = memorySize * 10;
100 printf("Changing memory size to %d...\n", memorySizeBig);
101 CHECK_RC (machine->COMSETTER(MemorySize) (memorySizeBig));
102
103 if (SUCCEEDED (rc))
104 {
105 printf ("Are any settings modified now?...\n");
106 CHECK_RC_RET (machine->COMGETTER(SettingsModified) (&modified));
107 printf ("%s\n", modified ? "yes" : "no");
108 ASSERT_RET (modified, 0);
109
110 ULONG memorySizeGot;
111 printf ("Getting memory size again...\n");
112 CHECK_RC_RET (machine->COMGETTER(MemorySize) (&memorySizeGot));
113 printf ("Memory size: %d\n", memorySizeGot);
114 ASSERT_RET (memorySizeGot == memorySizeBig, 0);
115
116 if (readonlyMachine)
117 {
118 printf ("Getting memory size of the counterpart readonly machine...\n");
119 ULONG memorySizeRO;
120 readonlyMachine->COMGETTER(MemorySize) (&memorySizeRO);
121 printf ("Memory size: %d\n", memorySizeRO);
122 ASSERT_RET (memorySizeRO != memorySizeGot, 0);
123 }
124
125 printf ("Discarding recent changes...\n");
126 CHECK_RC_RET (machine->DiscardSettings());
127 printf ("Are any settings modified after discarding?...\n");
128 CHECK_RC_RET (machine->COMGETTER(SettingsModified) (&modified));
129 printf ("%s\n", modified ? "yes" : "no");
130 ASSERT_RET (!modified, 0);
131
132 printf ("Getting memory size once more...\n");
133 CHECK_RC_RET (machine->COMGETTER(MemorySize) (&memorySizeGot));
134 printf ("Memory size: %d\n", memorySizeGot);
135 ASSERT_RET (memorySizeGot == memorySize, 0);
136
137 memorySize = memorySize > 128 ? memorySize / 2 : memorySize * 2;
138 printf("Changing memory size to %d...\n", memorySize);
139 CHECK_RC_RET (machine->COMSETTER(MemorySize) (memorySize));
140 }
141
142 Bstr desc;
143 printf ("Getting description...\n");
144 CHECK_ERROR_RET (machine, COMGETTER(Description) (desc.asOutParam()), rc);
145 printf ("Description is: \"%ls\"\n", desc.raw());
146
147 desc = L"This is an exemplary description (changed).";
148 printf ("Setting description to \"%ls\"...\n", desc.raw());
149 CHECK_ERROR_RET (machine, COMSETTER(Description) (desc), rc);
150
151 printf ("Saving machine settings...\n");
152 CHECK_RC (machine->SaveSettings());
153 if (SUCCEEDED (rc))
154 {
155 printf ("Are any settings modified after saving?...\n");
156 CHECK_RC_RET (machine->COMGETTER(SettingsModified) (&modified));
157 printf ("%s\n", modified ? "yes" : "no");
158 ASSERT_RET (!modified, 0);
159
160 if (readonlyMachine) {
161 printf ("Getting memory size of the counterpart readonly machine...\n");
162 ULONG memorySizeRO;
163 readonlyMachine->COMGETTER(MemorySize) (&memorySizeRO);
164 printf ("Memory size: %d\n", memorySizeRO);
165 ASSERT_RET (memorySizeRO == memorySize, 0);
166 }
167 }
168
169 Bstr extraDataKey = L"Blafasel";
170 Bstr extraData;
171 printf ("Getting extra data key {%ls}...\n", extraDataKey.raw());
172 CHECK_RC_RET (machine->GetExtraData (extraDataKey, extraData.asOutParam()));
173 if (!extraData.isEmpty()) {
174 printf ("Extra data value: {%ls}\n", extraData.raw());
175 } else {
176 if (extraData.isNull())
177 printf ("No extra data exists\n");
178 else
179 printf ("Extra data is empty\n");
180 }
181
182 if (extraData.isEmpty())
183 extraData = L"Das ist die Berliner Luft, Luft, Luft...";
184 else
185 extraData.setNull();
186 printf (
187 "Setting extra data key {%ls} to {%ls}...\n",
188 extraDataKey.raw(), extraData.raw()
189 );
190 CHECK_RC (machine->SetExtraData (extraDataKey, extraData));
191
192 if (SUCCEEDED (rc)) {
193 printf ("Getting extra data key {%ls} again...\n", extraDataKey.raw());
194 CHECK_RC_RET (machine->GetExtraData (extraDataKey, extraData.asOutParam()));
195 if (!extraData.isEmpty()) {
196 printf ("Extra data value: {%ls}\n", extraData.raw());
197 } else {
198 if (extraData.isNull())
199 printf ("No extra data exists\n");
200 else
201 printf ("Extra data is empty\n");
202 }
203 }
204
205 return rc;
206}
207
208// main
209///////////////////////////////////////////////////////////////////////////////
210
211int main(int argc, char *argv[])
212{
213 /*
214 * Initialize the VBox runtime without loading
215 * the support driver.
216 */
217 RTR3Init();
218
219 HRESULT rc;
220
221 {
222 char homeDir [RTPATH_MAX];
223 GetVBoxUserHomeDirectory (homeDir, sizeof (homeDir));
224 printf ("VirtualBox Home Directory = '%s'\n", homeDir);
225 }
226
227 printf ("Initializing COM...\n");
228
229 CHECK_RC_RET (com::Initialize());
230
231 do
232 {
233 // scopes all the stuff till shutdown
234 ////////////////////////////////////////////////////////////////////////////
235
236 ComPtr <IVirtualBox> virtualBox;
237 ComPtr <ISession> session;
238
239#if 0
240 // Utf8Str test
241 ////////////////////////////////////////////////////////////////////////////
242
243 Utf8Str nullUtf8Str;
244 printf ("nullUtf8Str='%s'\n", nullUtf8Str.raw());
245
246 Utf8Str simpleUtf8Str = "simpleUtf8Str";
247 printf ("simpleUtf8Str='%s'\n", simpleUtf8Str.raw());
248
249 Utf8Str utf8StrFmt = Utf8StrFmt ("[0=%d]%s[1=%d]",
250 0, "utf8StrFmt", 1);
251 printf ("utf8StrFmt='%s'\n", utf8StrFmt.raw());
252
253#endif
254
255 printf ("Creating VirtualBox object...\n");
256 CHECK_RC (virtualBox.createLocalObject (CLSID_VirtualBox));
257 if (FAILED (rc))
258 {
259 CHECK_ERROR_NOCALL();
260 break;
261 }
262
263 printf ("Creating Session object...\n");
264 CHECK_RC (session.createInprocObject (CLSID_Session));
265 if (FAILED (rc))
266 {
267 CHECK_ERROR_NOCALL();
268 break;
269 }
270
271#if 0
272 // IUnknown identity test
273 ////////////////////////////////////////////////////////////////////////////
274 {
275 {
276 ComPtr <IVirtualBox> virtualBox2;
277
278 printf ("Creating one more VirtualBox object...\n");
279 CHECK_RC (virtualBox2.createLocalObject (CLSID_VirtualBox));
280 if (FAILED (rc))
281 {
282 CHECK_ERROR_NOCALL();
283 break;
284 }
285
286 printf ("IVirtualBox(virtualBox)=%p IVirtualBox(virtualBox2)=%p\n",
287 (IVirtualBox *) virtualBox, (IVirtualBox *) virtualBox2);
288 Assert ((IVirtualBox *) virtualBox == (IVirtualBox *) virtualBox2);
289
290 ComPtr <IUnknown> unk (virtualBox);
291 ComPtr <IUnknown> unk2;
292 unk2 = virtualBox2;
293
294 printf ("IUnknown(virtualBox)=%p IUnknown(virtualBox2)=%p\n",
295 (IUnknown *) unk, (IUnknown *) unk2);
296 Assert ((IUnknown *) unk == (IUnknown *) unk2);
297
298 ComPtr <IVirtualBox> vb = unk;
299 ComPtr <IVirtualBox> vb2 = unk;
300
301 printf ("IVirtualBox(IUnknown(virtualBox))=%p IVirtualBox(IUnknown(virtualBox2))=%p\n",
302 (IVirtualBox *) vb, (IVirtualBox *) vb2);
303 Assert ((IVirtualBox *) vb == (IVirtualBox *) vb2);
304 }
305
306 {
307 ComPtr <IHost> host;
308 CHECK_ERROR_BREAK (virtualBox, COMGETTER(Host)(host.asOutParam()));
309 printf (" IHost(host)=%p\n", (IHost *) host);
310 ComPtr <IUnknown> unk = host;
311 printf (" IUnknown(host)=%p\n", (IUnknown *) unk);
312 ComPtr <IHost> host_copy = unk;
313 printf (" IHost(host_copy)=%p\n", (IHost *) host_copy);
314 ComPtr <IUnknown> unk_copy = host_copy;
315 printf (" IUnknown(host_copy)=%p\n", (IUnknown *) unk_copy);
316 Assert ((IUnknown *) unk == (IUnknown *) unk_copy);
317
318 /* query IUnknown on IUnknown */
319 ComPtr <IUnknown> unk_copy_copy;
320 unk_copy.queryInterfaceTo (unk_copy_copy.asOutParam());
321 printf (" IUnknown(unk_copy)=%p\n", (IUnknown *) unk_copy_copy);
322 Assert ((IUnknown *) unk_copy == (IUnknown *) unk_copy_copy);
323 /* query IUnknown on IUnknown in the opposite direction */
324 unk_copy_copy.queryInterfaceTo (unk_copy.asOutParam());
325 printf (" IUnknown(unk_copy_copy)=%p\n", (IUnknown *) unk_copy);
326 Assert ((IUnknown *) unk_copy == (IUnknown *) unk_copy_copy);
327
328 /* query IUnknown again after releasing all previous IUnknown instances
329 * but keeping IHost -- it should remain the same (Identity Rule) */
330 IUnknown *oldUnk = unk;
331 unk.setNull();
332 unk_copy.setNull();
333 unk_copy_copy.setNull();
334 unk = host;
335 printf (" IUnknown(host)=%p\n", (IUnknown *) unk);
336 Assert (oldUnk == (IUnknown *) unk);
337 }
338
339// printf ("Will be now released (press Enter)...");
340// getchar();
341 }
342#endif
343
344 // create the event queue
345 // (here it is necessary only to process remaining XPCOM/IPC events
346 // after the session is closed)
347 EventQueue eventQ;
348
349#if 0
350 // the simplest COM API test
351 ////////////////////////////////////////////////////////////////////////////
352 {
353 Bstr version;
354 CHECK_ERROR_BREAK (virtualBox, COMGETTER(Version) (version.asOutParam()));
355 printf ("VirtualBox version = %ls\n", version.raw());
356 }
357#endif
358
359#if 0
360 // Array test
361 ////////////////////////////////////////////////////////////////////////////
362 {
363 printf ("Calling IVirtualBox::Machines...\n");
364
365 com::SafeIfaceArray <IMachine> machines;
366 CHECK_ERROR_BREAK (virtualBox,
367 COMGETTER(Machines2) (ComSafeArrayAsOutParam (machines)));
368
369 printf ("%u machines registered (machines.isNull()=%d).\n",
370 machines.size(), machines.isNull());
371
372 for (size_t i = 0; i < machines.size(); ++ i)
373 {
374 Bstr name;
375 CHECK_ERROR_BREAK (machines [i], COMGETTER(Name) (name.asOutParam()));
376 printf ("machines[%u]='%s'\n", i, Utf8Str (name).raw());
377 }
378
379#if 0
380 {
381 printf ("Testing [out] arrays...\n");
382 com::SafeGUIDArray uuids;
383 CHECK_ERROR_BREAK (virtualBox,
384 COMGETTER(Uuids) (ComSafeArrayAsOutParam (uuids)));
385
386 for (size_t i = 0; i < uuids.size(); ++ i)
387 printf ("uuids[%u]=%Vuuid\n", i, &uuids [i]);
388 }
389
390 {
391 printf ("Testing [in] arrays...\n");
392 com::SafeGUIDArray uuids (5);
393 for (size_t i = 0; i < uuids.size(); ++ i)
394 {
395 Guid id;
396 id.create();
397 uuids [i] = id;
398 printf ("uuids[%u]=%Vuuid\n", i, &uuids [i]);
399 }
400
401 CHECK_ERROR_BREAK (virtualBox,
402 SetUuids (ComSafeArrayAsInParam (uuids)));
403 }
404#endif
405
406 }
407#endif
408
409#if 0
410 // some outdated stuff
411 ////////////////////////////////////////////////////////////////////////////
412
413 printf("Getting IHost interface...\n");
414 IHost *host;
415 rc = virtualBox->GetHost(&host);
416 if (SUCCEEDED(rc))
417 {
418 IHostDVDDriveCollection *dvdColl;
419 rc = host->GetHostDVDDrives(&dvdColl);
420 if (SUCCEEDED(rc))
421 {
422 IHostDVDDrive *dvdDrive = NULL;
423 dvdColl->GetNextHostDVDDrive(dvdDrive, &dvdDrive);
424 while (dvdDrive)
425 {
426 BSTR driveName;
427 char *driveNameUtf8;
428 dvdDrive->GetDriveName(&driveName);
429 RTUtf16ToUtf8((PCRTUTF16)driveName, &driveNameUtf8);
430 printf("Host DVD drive name: %s\n", driveNameUtf8);
431 RTStrFree(driveNameUtf8);
432 SysFreeString(driveName);
433 IHostDVDDrive *dvdDriveTemp = dvdDrive;
434 dvdColl->GetNextHostDVDDrive(dvdDriveTemp, &dvdDrive);
435 dvdDriveTemp->Release();
436 }
437 dvdColl->Release();
438 } else
439 {
440 printf("Could not get host DVD drive collection\n");
441 }
442
443 IHostFloppyDriveCollection *floppyColl;
444 rc = host->GetHostFloppyDrives(&floppyColl);
445 if (SUCCEEDED(rc))
446 {
447 IHostFloppyDrive *floppyDrive = NULL;
448 floppyColl->GetNextHostFloppyDrive(floppyDrive, &floppyDrive);
449 while (floppyDrive)
450 {
451 BSTR driveName;
452 char *driveNameUtf8;
453 floppyDrive->GetDriveName(&driveName);
454 RTUtf16ToUtf8((PCRTUTF16)driveName, &driveNameUtf8);
455 printf("Host floppy drive name: %s\n", driveNameUtf8);
456 RTStrFree(driveNameUtf8);
457 SysFreeString(driveName);
458 IHostFloppyDrive *floppyDriveTemp = floppyDrive;
459 floppyColl->GetNextHostFloppyDrive(floppyDriveTemp, &floppyDrive);
460 floppyDriveTemp->Release();
461 }
462 floppyColl->Release();
463 } else
464 {
465 printf("Could not get host floppy drive collection\n");
466 }
467 host->Release();
468 } else
469 {
470 printf("Call failed\n");
471 }
472 printf ("\n");
473#endif
474
475#if 0
476 // IVirtualBoxErrorInfo test
477 ////////////////////////////////////////////////////////////////////////////
478 {
479 // RPC calls
480
481 // call a method that will definitely fail
482 Guid uuid;
483 ComPtr <IHardDisk> hardDisk;
484 rc = virtualBox->GetHardDisk(uuid, hardDisk.asOutParam());
485 printf ("virtualBox->GetHardDisk(null-uuid)=%08X\n", rc);
486
487// {
488// com::ErrorInfo info (virtualBox);
489// PRINT_ERROR_INFO (info);
490// }
491
492 // call a method that will definitely succeed
493 Bstr version;
494 rc = virtualBox->COMGETTER(Version) (version.asOutParam());
495 printf ("virtualBox->COMGETTER(Version)=%08X\n", rc);
496
497 {
498 com::ErrorInfo info (virtualBox);
499 PRINT_ERROR_INFO (info);
500 }
501
502 // Local calls
503
504 // call a method that will definitely fail
505 ComPtr <IMachine> machine;
506 rc = session->COMGETTER(Machine)(machine.asOutParam());
507 printf ("session->COMGETTER(Machine)=%08X\n", rc);
508
509// {
510// com::ErrorInfo info (virtualBox);
511// PRINT_ERROR_INFO (info);
512// }
513
514 // call a method that will definitely succeed
515 SessionState_T state;
516 rc = session->COMGETTER(State) (&state);
517 printf ("session->COMGETTER(State)=%08X\n", rc);
518
519 {
520 com::ErrorInfo info (virtualBox);
521 PRINT_ERROR_INFO (info);
522 }
523 }
524#endif
525
526#if 0
527 // register the existing hard disk image
528 ///////////////////////////////////////////////////////////////////////////
529 do
530 {
531 ComPtr <IHardDisk> hd;
532 Bstr src = L"E:\\develop\\innotek\\images\\NewHardDisk.vdi";
533 printf ("Opening the existing hard disk '%ls'...\n", src.raw());
534 CHECK_ERROR_BREAK (virtualBox, OpenHardDisk (src, hd.asOutParam()));
535 printf ("Enter to continue...\n");
536 getchar();
537 printf ("Registering the existing hard disk '%ls'...\n", src.raw());
538 CHECK_ERROR_BREAK (virtualBox, RegisterHardDisk (hd));
539 printf ("Enter to continue...\n");
540 getchar();
541 }
542 while (FALSE);
543 printf ("\n");
544#endif
545
546#if 0
547 // find and unregister the existing hard disk image
548 ///////////////////////////////////////////////////////////////////////////
549 do
550 {
551 ComPtr <IVirtualDiskImage> vdi;
552 Bstr src = L"CreatorTest.vdi";
553 printf ("Unregistering the hard disk '%ls'...\n", src.raw());
554 CHECK_ERROR_BREAK (virtualBox, FindVirtualDiskImage (src, vdi.asOutParam()));
555 ComPtr <IHardDisk> hd = vdi;
556 Guid id;
557 CHECK_ERROR_BREAK (hd, COMGETTER(Id) (id.asOutParam()));
558 CHECK_ERROR_BREAK (virtualBox, UnregisterHardDisk (id, hd.asOutParam()));
559 }
560 while (FALSE);
561 printf ("\n");
562#endif
563
564#if 0
565 // clone the registered hard disk
566 ///////////////////////////////////////////////////////////////////////////
567 do
568 {
569#if defined RT_OS_LINUX
570 Bstr src = L"/mnt/hugaida/common/develop/innotek/images/freedos-linux.vdi";
571#else
572 Bstr src = L"E:/develop/innotek/images/freedos.vdi";
573#endif
574 Bstr dst = L"./clone.vdi";
575 RTPrintf ("Cloning '%ls' to '%ls'...\n", src.raw(), dst.raw());
576 ComPtr <IVirtualDiskImage> vdi;
577 CHECK_ERROR_BREAK (virtualBox, FindVirtualDiskImage (src, vdi.asOutParam()));
578 ComPtr <IHardDisk> hd = vdi;
579 ComPtr <IProgress> progress;
580 CHECK_ERROR_BREAK (hd, CloneToImage (dst, vdi.asOutParam(), progress.asOutParam()));
581 RTPrintf ("Waiting for completion...\n");
582 CHECK_ERROR_BREAK (progress, WaitForCompletion (-1));
583 ProgressErrorInfo ei (progress);
584 if (FAILED (ei.getResultCode()))
585 {
586 PRINT_ERROR_INFO (ei);
587 }
588 else
589 {
590 vdi->COMGETTER(FilePath) (dst.asOutParam());
591 RTPrintf ("Actual clone path is '%ls'\n", dst.raw());
592 }
593 }
594 while (FALSE);
595 printf ("\n");
596#endif
597
598#if 0
599 // find a registered hard disk by location and get properties
600 ///////////////////////////////////////////////////////////////////////////
601 do
602 {
603 ComPtr <IHardDisk2> hd;
604 static const wchar_t *Names[] =
605 {
606#ifndef RT_OS_LINUX
607 L"freedos.vdi",
608 L"MS-DOS.vmdk",
609 L"iscsi",
610 L"some/path/and/disk.vdi",
611#else
612 L"xp.vdi",
613 L"Xp.vDI",
614#endif
615 };
616
617 printf ("\n");
618
619 for (size_t i = 0; i < RT_ELEMENTS (Names); ++ i)
620 {
621 Bstr src = Names [i];
622 printf ("Searching for hard disk '%ls'...\n", src.raw());
623 rc = virtualBox->FindHardDisk2 (src, hd.asOutParam());
624 if (SUCCEEDED (rc))
625 {
626 Guid id;
627 Bstr location;
628 CHECK_ERROR_BREAK (hd, COMGETTER(Id) (id.asOutParam()));
629 CHECK_ERROR_BREAK (hd, COMGETTER(Location) (location.asOutParam()));
630 printf ("Found, UUID={%Vuuid}, location='%ls'.\n",
631 id.raw(), location.raw());
632
633 com::SafeArray <BSTR> names;
634 com::SafeArray <BSTR> values;
635
636 CHECK_ERROR_BREAK (hd, GetProperties (NULL,
637 ComSafeArrayAsOutParam (names),
638 ComSafeArrayAsOutParam (values)));
639
640 printf ("Properties:\n");
641 for (size_t i = 0; i < names.size(); ++ i)
642 printf (" %ls = %ls\n", names [i], values [i]);
643
644 if (names.size() == 0)
645 printf (" <none>\n");
646
647#if 0
648 Bstr name ("TargetAddress");
649 Bstr value = Utf8StrFmt ("lalala (%llu)", RTTimeMilliTS());
650
651 printf ("Settings property %ls to %ls...\n", name.raw(), value.raw());
652 CHECK_ERROR (hd, SetProperty (name, value));
653#endif
654 }
655 else
656 {
657 com::ErrorInfo info (virtualBox);
658 PRINT_ERROR_INFO (info);
659 }
660 printf ("\n");
661 }
662 }
663 while (FALSE);
664 printf ("\n");
665#endif
666
667#if 0
668 // access the machine in read-only mode
669 ///////////////////////////////////////////////////////////////////////////
670 do
671 {
672 ComPtr <IMachine> machine;
673 Bstr name = argc > 1 ? argv [1] : "dos";
674 printf ("Getting a machine object named '%ls'...\n", name.raw());
675 CHECK_ERROR_BREAK (virtualBox, FindMachine (name, machine.asOutParam()));
676 printf ("Accessing the machine in read-only mode:\n");
677 readAndChangeMachineSettings (machine);
678#if 0
679 if (argc != 2)
680 {
681 printf ("Error: a string has to be supplied!\n");
682 }
683 else
684 {
685 Bstr secureLabel = argv[1];
686 machine->COMSETTER(ExtraData)(L"VBoxSDL/SecureLabel", secureLabel);
687 }
688#endif
689 }
690 while (0);
691 printf ("\n");
692#endif
693
694#if 0
695 // create a new machine (w/o registering it)
696 ///////////////////////////////////////////////////////////////////////////
697 do
698 {
699 ComPtr <IMachine> machine;
700#if defined (RT_OS_LINUX)
701 Bstr baseDir = L"/tmp/vbox";
702#else
703 Bstr baseDir = L"C:\\vbox";
704#endif
705 Bstr name = L"machina";
706
707 printf ("Creating a new machine object (base dir '%ls', name '%ls')...\n",
708 baseDir.raw(), name.raw());
709 CHECK_ERROR_BREAK (virtualBox, CreateMachine (baseDir, name,
710 machine.asOutParam()));
711
712 printf ("Getting name...\n");
713 CHECK_ERROR_BREAK (machine, COMGETTER(Name) (name.asOutParam()));
714 printf ("Name: {%ls}\n", name.raw());
715
716 BOOL modified = FALSE;
717 printf ("Are any settings modified?...\n");
718 CHECK_ERROR_BREAK (machine, COMGETTER(SettingsModified) (&modified));
719 printf ("%s\n", modified ? "yes" : "no");
720
721 ASSERT_BREAK (modified == TRUE);
722
723 name = L"Kakaya prekrasnaya virtual'naya mashina!";
724 printf ("Setting new name ({%ls})...\n", name.raw());
725 CHECK_ERROR_BREAK (machine, COMSETTER(Name) (name));
726
727 printf ("Setting memory size to 111...\n");
728 CHECK_ERROR_BREAK (machine, COMSETTER(MemorySize) (111));
729
730 Bstr desc = L"This is an exemplary description.";
731 printf ("Setting description to \"%ls\"...\n", desc.raw());
732 CHECK_ERROR_BREAK (machine, COMSETTER(Description) (desc));
733
734 ComPtr <IGuestOSType> guestOSType;
735 Bstr type = L"os2warp45";
736 CHECK_ERROR_BREAK (virtualBox, GetGuestOSType (type, guestOSType.asOutParam()));
737
738 printf ("Saving new machine settings...\n");
739 CHECK_ERROR_BREAK (machine, SaveSettings());
740
741 printf ("Accessing the newly created machine:\n");
742 readAndChangeMachineSettings (machine);
743 }
744 while (FALSE);
745 printf ("\n");
746#endif
747
748#if 0
749 // enumerate host DVD drives
750 ///////////////////////////////////////////////////////////////////////////
751 do
752 {
753 ComPtr <IHost> host;
754 CHECK_RC_BREAK (virtualBox->COMGETTER(Host) (host.asOutParam()));
755
756 {
757 ComPtr <IHostDVDDriveCollection> coll;
758 CHECK_RC_BREAK (host->COMGETTER(DVDDrives) (coll.asOutParam()));
759 ComPtr <IHostDVDDriveEnumerator> enumerator;
760 CHECK_RC_BREAK (coll->Enumerate (enumerator.asOutParam()));
761 BOOL hasmore;
762 while (SUCCEEDED (enumerator->HasMore (&hasmore)) && hasmore)
763 {
764 ComPtr <IHostDVDDrive> drive;
765 CHECK_RC_BREAK (enumerator->GetNext (drive.asOutParam()));
766 Bstr name;
767 CHECK_RC_BREAK (drive->COMGETTER(Name) (name.asOutParam()));
768 printf ("Host DVD drive: name={%ls}\n", name.raw());
769 }
770 CHECK_RC_BREAK (rc);
771
772 ComPtr <IHostDVDDrive> drive;
773 CHECK_ERROR (enumerator, GetNext (drive.asOutParam()));
774 CHECK_ERROR (coll, GetItemAt (1000, drive.asOutParam()));
775 CHECK_ERROR (coll, FindByName (Bstr ("R:"), drive.asOutParam()));
776 if (SUCCEEDED (rc))
777 {
778 Bstr name;
779 CHECK_RC_BREAK (drive->COMGETTER(Name) (name.asOutParam()));
780 printf ("Found by name: name={%ls}\n", name.raw());
781 }
782 }
783 }
784 while (FALSE);
785 printf ("\n");
786#endif
787
788#if 0
789 // check for available hd backends
790 ///////////////////////////////////////////////////////////////////////////
791 {
792 RTPrintf("Supported hard disk backends: --------------------------\n");
793 ComPtr<ISystemProperties> systemProperties;
794 CHECK_ERROR_BREAK (virtualBox,
795 COMGETTER(SystemProperties) (systemProperties.asOutParam()));
796 com::SafeIfaceArray <IHardDiskFormat> hardDiskFormats;
797 CHECK_ERROR_BREAK (systemProperties,
798 COMGETTER(HardDiskFormats) (ComSafeArrayAsOutParam (hardDiskFormats)));
799
800 for (size_t i = 0; i < hardDiskFormats.size(); ++ i)
801 {
802 /* General information */
803 Bstr id;
804 CHECK_ERROR_BREAK (hardDiskFormats [i],
805 COMGETTER(Id) (id.asOutParam()));
806
807 Bstr description;
808 CHECK_ERROR_BREAK (hardDiskFormats [i],
809 COMGETTER(Id) (description.asOutParam()));
810
811 ULONG caps;
812 CHECK_ERROR_BREAK (hardDiskFormats [i],
813 COMGETTER(Capabilities) (&caps));
814
815 RTPrintf("Backend %u: id='%ls' description='%ls' capabilities=%#06x extensions='",
816 i, id.raw(), description.raw(), caps);
817
818 /* File extensions */
819 com::SafeArray <BSTR> fileExtensions;
820 CHECK_ERROR_BREAK (hardDiskFormats [i],
821 COMGETTER(FileExtensions) (ComSafeArrayAsOutParam (fileExtensions)));
822 for (size_t a = 0; a < fileExtensions.size(); ++ a)
823 {
824 RTPrintf ("%ls", Bstr (fileExtensions [a]).raw());
825 if (a != fileExtensions.size()-1)
826 RTPrintf (",");
827 }
828 RTPrintf ("'");
829
830 /* Configuration keys */
831 com::SafeArray <BSTR> propertyNames;
832 com::SafeArray <BSTR> propertyDescriptions;
833 com::SafeArray <ULONG> propertyTypes;
834 com::SafeArray <ULONG> propertyFlags;
835 com::SafeArray <BSTR> propertyDefaults;
836 CHECK_ERROR_BREAK (hardDiskFormats [i],
837 DescribeProperties (ComSafeArrayAsOutParam (propertyNames),
838 ComSafeArrayAsOutParam (propertyDescriptions),
839 ComSafeArrayAsOutParam (propertyTypes),
840 ComSafeArrayAsOutParam (propertyFlags),
841 ComSafeArrayAsOutParam (propertyDefaults)));
842
843 RTPrintf (" config=(");
844 if (propertyNames.size() > 0)
845 {
846 for (size_t a = 0; a < propertyNames.size(); ++ a)
847 {
848 RTPrintf ("key='%ls' desc='%ls' type=", Bstr (propertyNames [a]).raw(), Bstr (propertyDescriptions [a]).raw());
849 switch (propertyTypes [a])
850 {
851 case DataType_Int32Type: RTPrintf ("int"); break;
852 case DataType_Int8Type: RTPrintf ("byte"); break;
853 case DataType_StringType: RTPrintf ("string"); break;
854 }
855 RTPrintf (" flags=%#04x", propertyFlags [a]);
856 RTPrintf (" default='%ls'", Bstr (propertyDefaults [a]).raw());
857 if (a != propertyNames.size()-1)
858 RTPrintf (",");
859 }
860 }
861 RTPrintf (")\n");
862 }
863 RTPrintf("-------------------------------------------------------\n");
864 }
865#endif
866
867#if 0
868 // enumerate hard disks & dvd images
869 ///////////////////////////////////////////////////////////////////////////
870 do
871 {
872 {
873 com::SafeIfaceArray <IHardDisk2> disks;
874 CHECK_ERROR_BREAK (virtualBox,
875 COMGETTER(HardDisks2) (ComSafeArrayAsOutParam (disks)));
876
877 printf ("%u base hard disks registered (disks.isNull()=%d).\n",
878 disks.size(), disks.isNull());
879
880 for (size_t i = 0; i < disks.size(); ++ i)
881 {
882 Bstr loc;
883 CHECK_ERROR_BREAK (disks [i], COMGETTER(Location) (loc.asOutParam()));
884 Guid id;
885 CHECK_ERROR_BREAK (disks [i], COMGETTER(Id) (id.asOutParam()));
886 MediaState_T state;
887 CHECK_ERROR_BREAK (disks [i], COMGETTER(State) (&state));
888 Bstr format;
889 CHECK_ERROR_BREAK (disks [i], COMGETTER(Format) (format.asOutParam()));
890
891 printf (" disks[%u]: '%ls'\n"
892 " UUID: {%Vuuid}\n"
893 " State: %s\n"
894 " Format: %ls\n",
895 i, loc.raw(), id.raw(),
896 state == MediaState_NotCreated ? "Not Created" :
897 state == MediaState_Created ? "Created" :
898 state == MediaState_Inaccessible ? "Inaccessible" :
899 state == MediaState_LockedRead ? "Locked Read" :
900 state == MediaState_LockedWrite ? "Locked Write" :
901 "???",
902 format.raw());
903
904 if (state == MediaState_Inaccessible)
905 {
906 Bstr error;
907 CHECK_ERROR_BREAK (disks [i],
908 COMGETTER(LastAccessError)(error.asOutParam()));
909 printf (" Access Error: %ls\n", error.raw());
910 }
911
912 /* get usage */
913
914 printf (" Used by VMs:\n");
915
916 com::SafeGUIDArray ids;
917 CHECK_ERROR_BREAK (disks [i],
918 COMGETTER(MachineIds) (ComSafeArrayAsOutParam (ids)));
919 if (ids.size() == 0)
920 {
921 printf (" <not used>\n");
922 }
923 else
924 {
925 for (size_t j = 0; j < ids.size(); ++ j)
926 {
927 printf (" {%Vuuid}\n", &ids [j]);
928 }
929 }
930 }
931 }
932 {
933 com::SafeIfaceArray <IDVDImage2> images;
934 CHECK_ERROR_BREAK (virtualBox,
935 COMGETTER(DVDImages) (ComSafeArrayAsOutParam (images)));
936
937 printf ("%u DVD images registered (images.isNull()=%d).\n",
938 images.size(), images.isNull());
939
940 for (size_t i = 0; i < images.size(); ++ i)
941 {
942 Bstr loc;
943 CHECK_ERROR_BREAK (images [i], COMGETTER(Location) (loc.asOutParam()));
944 Guid id;
945 CHECK_ERROR_BREAK (images [i], COMGETTER(Id) (id.asOutParam()));
946 MediaState_T state;
947 CHECK_ERROR_BREAK (images [i], COMGETTER(State) (&state));
948
949 printf (" images[%u]: '%ls'\n"
950 " UUID: {%Vuuid}\n"
951 " State: %s\n",
952 i, loc.raw(), id.raw(),
953 state == MediaState_NotCreated ? "Not Created" :
954 state == MediaState_Created ? "Created" :
955 state == MediaState_Inaccessible ? "Inaccessible" :
956 state == MediaState_LockedRead ? "Locked Read" :
957 state == MediaState_LockedWrite ? "Locked Write" :
958 "???");
959
960 if (state == MediaState_Inaccessible)
961 {
962 Bstr error;
963 CHECK_ERROR_BREAK (images [i],
964 COMGETTER(LastAccessError)(error.asOutParam()));
965 printf (" Access Error: %ls\n", error.raw());
966 }
967
968 /* get usage */
969
970 printf (" Used by VMs:\n");
971
972 com::SafeGUIDArray ids;
973 CHECK_ERROR_BREAK (images [i],
974 COMGETTER(MachineIds) (ComSafeArrayAsOutParam (ids)));
975 if (ids.size() == 0)
976 {
977 printf (" <not used>\n");
978 }
979 else
980 {
981 for (size_t j = 0; j < ids.size(); ++ j)
982 {
983 printf (" {%Vuuid}\n", &ids [j]);
984 }
985 }
986 }
987 }
988 }
989 while (FALSE);
990 printf ("\n");
991#endif
992
993#if 0
994 // open a (direct) session
995 ///////////////////////////////////////////////////////////////////////////
996 do
997 {
998 ComPtr <IMachine> machine;
999 Bstr name = argc > 1 ? argv [1] : "dos";
1000 printf ("Getting a machine object named '%ls'...\n", name.raw());
1001 CHECK_ERROR_BREAK (virtualBox, FindMachine (name, machine.asOutParam()));
1002 Guid guid;
1003 CHECK_RC_BREAK (machine->COMGETTER(Id) (guid.asOutParam()));
1004 printf ("Opening a session for this machine...\n");
1005 CHECK_RC_BREAK (virtualBox->OpenSession (session, guid));
1006#if 1
1007 ComPtr <IMachine> sessionMachine;
1008 printf ("Getting sessioned machine object...\n");
1009 CHECK_RC_BREAK (session->COMGETTER(Machine) (sessionMachine.asOutParam()));
1010 printf ("Accessing the machine within the session:\n");
1011 readAndChangeMachineSettings (sessionMachine, machine);
1012#if 0
1013 printf ("\n");
1014 printf ("Enabling the VRDP server (must succeed even if the VM is saved):\n");
1015 ComPtr <IVRDPServer> vrdp;
1016 CHECK_ERROR_BREAK (sessionMachine, COMGETTER(VRDPServer) (vrdp.asOutParam()));
1017 if (FAILED (vrdp->COMSETTER(Enabled) (TRUE)))
1018 {
1019 PRINT_ERROR_INFO (com::ErrorInfo (vrdp));
1020 }
1021 else
1022 {
1023 BOOL enabled = FALSE;
1024 CHECK_ERROR_BREAK (vrdp, COMGETTER(Enabled) (&enabled));
1025 printf ("VRDP server is %s\n", enabled ? "enabled" : "disabled");
1026 }
1027#endif
1028#endif
1029#if 0
1030 ComPtr <IConsole> console;
1031 printf ("Getting the console object...\n");
1032 CHECK_RC_BREAK (session->COMGETTER(Console) (console.asOutParam()));
1033 printf ("Discarding the current machine state...\n");
1034 ComPtr <IProgress> progress;
1035 CHECK_ERROR_BREAK (console, DiscardCurrentState (progress.asOutParam()));
1036 printf ("Waiting for completion...\n");
1037 CHECK_ERROR_BREAK (progress, WaitForCompletion (-1));
1038 ProgressErrorInfo ei (progress);
1039 if (FAILED (ei.getResultCode()))
1040 {
1041 PRINT_ERROR_INFO (ei);
1042
1043 ComPtr <IUnknown> initiator;
1044 CHECK_ERROR_BREAK (progress, COMGETTER(Initiator) (initiator.asOutParam()));
1045
1046 printf ("initiator(unk) = %p\n", (IUnknown *) initiator);
1047 printf ("console(unk) = %p\n", (IUnknown *) ComPtr <IUnknown> ((IConsole *) console));
1048 printf ("console = %p\n", (IConsole *) console);
1049 }
1050#endif
1051 printf("Press enter to close session...");
1052 getchar();
1053 session->Close();
1054 }
1055 while (FALSE);
1056 printf ("\n");
1057#endif
1058
1059#if 0
1060 // open a remote session
1061 ///////////////////////////////////////////////////////////////////////////
1062 do
1063 {
1064 ComPtr <IMachine> machine;
1065 Bstr name = L"dos";
1066 printf ("Getting a machine object named '%ls'...\n", name.raw());
1067 CHECK_RC_BREAK (virtualBox->FindMachine (name, machine.asOutParam()));
1068 Guid guid;
1069 CHECK_RC_BREAK (machine->COMGETTER(Id) (guid.asOutParam()));
1070 printf ("Opening a remote session for this machine...\n");
1071 ComPtr <IProgress> progress;
1072 CHECK_RC_BREAK (virtualBox->OpenRemoteSession (session, guid, Bstr("gui"),
1073 NULL, progress.asOutParam()));
1074 printf ("Waiting for the session to open...\n");
1075 CHECK_RC_BREAK (progress->WaitForCompletion (-1));
1076 ComPtr <IMachine> sessionMachine;
1077 printf ("Getting sessioned machine object...\n");
1078 CHECK_RC_BREAK (session->COMGETTER(Machine) (sessionMachine.asOutParam()));
1079 ComPtr <IConsole> console;
1080 printf ("Getting console object...\n");
1081 CHECK_RC_BREAK (session->COMGETTER(Console) (console.asOutParam()));
1082 printf ("Press enter to pause the VM execution in the remote session...");
1083 getchar();
1084 CHECK_RC (console->Pause());
1085 printf ("Press enter to close this session...");
1086 getchar();
1087 session->Close();
1088 }
1089 while (FALSE);
1090 printf ("\n");
1091#endif
1092
1093#if 0
1094 // open an existing remote session
1095 ///////////////////////////////////////////////////////////////////////////
1096 do
1097 {
1098 ComPtr <IMachine> machine;
1099 Bstr name = "dos";
1100 printf ("Getting a machine object named '%ls'...\n", name.raw());
1101 CHECK_RC_BREAK (virtualBox->FindMachine (name, machine.asOutParam()));
1102 Guid guid;
1103 CHECK_RC_BREAK (machine->COMGETTER(Id) (guid.asOutParam()));
1104 printf ("Opening an existing remote session for this machine...\n");
1105 CHECK_RC_BREAK (virtualBox->OpenExistingSession (session, guid));
1106 ComPtr <IMachine> sessionMachine;
1107 printf ("Getting sessioned machine object...\n");
1108 CHECK_RC_BREAK (session->COMGETTER(Machine) (sessionMachine.asOutParam()));
1109
1110#if 0
1111 Bstr extraDataKey = "VBoxSDL/SecureLabel";
1112 Bstr extraData = "Das kommt jetzt noch viel krasser vom total konkreten API!";
1113 CHECK_RC (sessionMachine->SetExtraData (extraDataKey, extraData));
1114#endif
1115#if 0
1116 ComPtr <IConsole> console;
1117 printf ("Getting console object...\n");
1118 CHECK_RC_BREAK (session->COMGETTER(Console) (console.asOutParam()));
1119 printf ("Press enter to pause the VM execution in the remote session...");
1120 getchar();
1121 CHECK_RC (console->Pause());
1122 printf ("Press enter to close this session...");
1123 getchar();
1124#endif
1125 session->Close();
1126 }
1127 while (FALSE);
1128 printf ("\n");
1129#endif
1130
1131#if 0
1132 do {
1133 // Get host
1134 ComPtr <IHost> host;
1135 CHECK_ERROR_BREAK (virtualBox, COMGETTER(Host) (host.asOutParam()));
1136
1137 ULONG uMemSize, uMemAvail;
1138 CHECK_ERROR_BREAK (host, COMGETTER(MemorySize) (&uMemSize));
1139 printf("Total memory (MB): %u\n", uMemSize);
1140 CHECK_ERROR_BREAK (host, COMGETTER(MemoryAvailable) (&uMemAvail));
1141 printf("Free memory (MB): %u\n", uMemAvail);
1142 } while (0);
1143#endif
1144
1145#if 0
1146 do {
1147 // Get host
1148 ComPtr <IHost> host;
1149 CHECK_ERROR_BREAK (virtualBox, COMGETTER(Host) (host.asOutParam()));
1150
1151 com::SafeIfaceArray <IHostNetworkInterface> hostNetworkInterfaces;
1152 CHECK_ERROR_BREAK(host,
1153 COMGETTER(NetworkInterfaces) (ComSafeArrayAsOutParam (hostNetworkInterfaces)));
1154 if (hostNetworkInterfaces.size() > 0)
1155 {
1156 ComPtr<IHostNetworkInterface> networkInterface = hostNetworkInterfaces[0];
1157 Bstr interfaceName;
1158 networkInterface->COMGETTER(Name)(interfaceName.asOutParam());
1159 printf("Found %d network interfaces, testing with %lS...\n", hostNetworkInterfaces.size(), interfaceName.raw());
1160 Guid interfaceGuid;
1161 networkInterface->COMGETTER(Id)(interfaceGuid.asOutParam());
1162 // Find the interface by its name
1163 networkInterface.setNull();
1164 CHECK_ERROR_BREAK(host,
1165 FindHostNetworkInterfaceByName (interfaceName, networkInterface.asOutParam()));
1166 Guid interfaceGuid2;
1167 networkInterface->COMGETTER(Id)(interfaceGuid2.asOutParam());
1168 if (interfaceGuid2 != interfaceGuid)
1169 printf("Failed to retrieve an interface by name %lS.\n", interfaceName.raw());
1170 // Find the interface by its guid
1171 networkInterface.setNull();
1172 CHECK_ERROR_BREAK(host,
1173 FindHostNetworkInterfaceById (interfaceGuid, networkInterface.asOutParam()));
1174 Bstr interfaceName2;
1175 networkInterface->COMGETTER(Name)(interfaceName2.asOutParam());
1176 if (interfaceName != interfaceName2)
1177 printf("Failed to retrieve an interface by GUID %lS.\n", Bstr(interfaceGuid.toString()).raw());
1178 }
1179 else
1180 {
1181 printf("No network interfaces found!\n");
1182 }
1183 } while (0);
1184#endif
1185
1186#if 0 && defined (VBOX_WITH_RESOURCE_USAGE_API)
1187 do {
1188 // Get collector
1189 ComPtr <IPerformanceCollector> collector;
1190 CHECK_ERROR_BREAK (virtualBox,
1191 COMGETTER(PerformanceCollector) (collector.asOutParam()));
1192
1193
1194 // Fill base metrics array
1195 Bstr baseMetricNames[] = { L"CPU/Load,RAM/Usage" };
1196 com::SafeArray<BSTR> baseMetrics (1);
1197 baseMetricNames[0].cloneTo (&baseMetrics [0]);
1198
1199 // Get host
1200 ComPtr <IHost> host;
1201 CHECK_ERROR_BREAK (virtualBox, COMGETTER(Host) (host.asOutParam()));
1202
1203 // Get machine
1204 ComPtr <IMachine> machine;
1205 Bstr name = argc > 1 ? argv [1] : "dsl";
1206 Bstr sessionType = argc > 2 ? argv [2] : "vrdp";
1207 printf ("Getting a machine object named '%ls'...\n", name.raw());
1208 CHECK_RC_BREAK (virtualBox->FindMachine (name, machine.asOutParam()));
1209
1210 // Open session
1211 Guid guid;
1212 CHECK_RC_BREAK (machine->COMGETTER(Id) (guid.asOutParam()));
1213 printf ("Opening a remote session for this machine...\n");
1214 ComPtr <IProgress> progress;
1215 CHECK_RC_BREAK (virtualBox->OpenRemoteSession (session, guid, sessionType,
1216 NULL, progress.asOutParam()));
1217 printf ("Waiting for the session to open...\n");
1218 CHECK_RC_BREAK (progress->WaitForCompletion (-1));
1219 ComPtr <IMachine> sessionMachine;
1220 printf ("Getting sessioned machine object...\n");
1221 CHECK_RC_BREAK (session->COMGETTER(Machine) (sessionMachine.asOutParam()));
1222
1223 // Setup base metrics
1224 // Note that one needs to set up metrics after a session is open for a machine.
1225 com::SafeIfaceArray<IPerformanceMetric> affectedMetrics;
1226 com::SafeIfaceArray<IUnknown> objects(2);
1227 host.queryInterfaceTo(&objects[0]);
1228 machine.queryInterfaceTo(&objects[1]);
1229 CHECK_ERROR_BREAK (collector, SetupMetrics(ComSafeArrayAsInParam(baseMetrics),
1230 ComSafeArrayAsInParam(objects), 1u, 10u,
1231 ComSafeArrayAsOutParam(affectedMetrics)) );
1232 listAffectedMetrics(virtualBox,
1233 ComSafeArrayAsInParam(affectedMetrics));
1234 affectedMetrics.setNull();
1235
1236 // Get console
1237 ComPtr <IConsole> console;
1238 printf ("Getting console object...\n");
1239 CHECK_RC_BREAK (session->COMGETTER(Console) (console.asOutParam()));
1240
1241 RTThreadSleep(5000); // Sleep for 5 seconds
1242
1243 printf("\nMetrics collected with VM running: --------------------\n");
1244 queryMetrics(virtualBox, collector, ComSafeArrayAsInParam(objects));
1245
1246 // Pause
1247 //printf ("Press enter to pause the VM execution in the remote session...");
1248 //getchar();
1249 CHECK_RC (console->Pause());
1250
1251 RTThreadSleep(5000); // Sleep for 5 seconds
1252
1253 printf("\nMetrics collected with VM paused: ---------------------\n");
1254 queryMetrics(virtualBox, collector, ComSafeArrayAsInParam(objects));
1255
1256 printf("\nDrop collected metrics: ----------------------------------------\n");
1257 CHECK_ERROR_BREAK (collector,
1258 SetupMetrics(ComSafeArrayAsInParam(baseMetrics),
1259 ComSafeArrayAsInParam(objects),
1260 1u, 5u, ComSafeArrayAsOutParam(affectedMetrics)) );
1261 listAffectedMetrics(virtualBox,
1262 ComSafeArrayAsInParam(affectedMetrics));
1263 affectedMetrics.setNull();
1264 queryMetrics(virtualBox, collector, ComSafeArrayAsInParam(objects));
1265
1266 com::SafeIfaceArray<IUnknown> vmObject(1);
1267 machine.queryInterfaceTo(&vmObject[0]);
1268
1269 printf("\nDisable collection of VM metrics: ------------------------------\n");
1270 CHECK_ERROR_BREAK (collector,
1271 DisableMetrics(ComSafeArrayAsInParam(baseMetrics),
1272 ComSafeArrayAsInParam(vmObject),
1273 ComSafeArrayAsOutParam(affectedMetrics)) );
1274 listAffectedMetrics(virtualBox,
1275 ComSafeArrayAsInParam(affectedMetrics));
1276 affectedMetrics.setNull();
1277 RTThreadSleep(5000); // Sleep for 5 seconds
1278 queryMetrics(virtualBox, collector, ComSafeArrayAsInParam(objects));
1279
1280 printf("\nRe-enable collection of all metrics: ---------------------------\n");
1281 CHECK_ERROR_BREAK (collector,
1282 EnableMetrics(ComSafeArrayAsInParam(baseMetrics),
1283 ComSafeArrayAsInParam(objects),
1284 ComSafeArrayAsOutParam(affectedMetrics)) );
1285 listAffectedMetrics(virtualBox,
1286 ComSafeArrayAsInParam(affectedMetrics));
1287 affectedMetrics.setNull();
1288 RTThreadSleep(5000); // Sleep for 5 seconds
1289 queryMetrics(virtualBox, collector, ComSafeArrayAsInParam(objects));
1290
1291 // Power off
1292 printf ("Press enter to power off VM...");
1293 getchar();
1294 CHECK_RC (console->PowerDown());
1295 printf ("Press enter to close this session...");
1296 getchar();
1297 session->Close();
1298 } while (false);
1299#endif /* VBOX_WITH_RESOURCE_USAGE_API */
1300#if 0
1301 // check of OVF appliance handling
1302 ///////////////////////////////////////////////////////////////////////////
1303 do
1304 {
1305 Bstr ovf = argc > 1 ? argv [1] : "someOVF.ovf";
1306 RTPrintf ("Try to open %ls ...\n", ovf.raw());
1307
1308 ComPtr <IAppliance> appliance;
1309 CHECK_ERROR_BREAK (virtualBox,
1310 CreateAppliance (appliance.asOutParam()));
1311 CHECK_ERROR_BREAK (appliance,
1312 Read (ovf));
1313 Bstr path;
1314 CHECK_ERROR_BREAK (appliance, COMGETTER (Path)(path.asOutParam()));
1315 RTPrintf ("Successfully opened %ls.\n", path.raw());
1316 CHECK_ERROR_BREAK (appliance,
1317 Interpret());
1318 RTPrintf ("Successfully interpreted %ls.\n", path.raw());
1319 RTPrintf ("Appliance:\n");
1320 // Fetch all disks
1321 com::SafeArray<BSTR> retDisks;
1322 CHECK_ERROR_BREAK (appliance,
1323 COMGETTER (Disks)(ComSafeArrayAsOutParam (retDisks)));
1324 if (retDisks.size() > 0)
1325 {
1326 RTPrintf ("Disks:");
1327 for (unsigned i = 0; i < retDisks.size(); i++)
1328 printf (" %ls", Bstr (retDisks [i]).raw());
1329 RTPrintf ("\n");
1330 }
1331 /* Fetch all virtual system descriptions */
1332 com::SafeIfaceArray<IVirtualSystemDescription> retVSD;
1333 CHECK_ERROR_BREAK (appliance,
1334 COMGETTER (VirtualSystemDescriptions) (ComSafeArrayAsOutParam (retVSD)));
1335 if (retVSD.size() > 0)
1336 {
1337 for (unsigned i = 0; i < retVSD.size(); ++i)
1338 {
1339 com::SafeArray<VirtualSystemDescriptionType_T> retTypes;
1340 com::SafeArray<BSTR> retRefValues;
1341 com::SafeArray<BSTR> retOrigValues;
1342 com::SafeArray<BSTR> retAutoValues;
1343 com::SafeArray<BSTR> retConfiguration;
1344 CHECK_ERROR_BREAK (retVSD [i],
1345 GetDescription (ComSafeArrayAsOutParam (retTypes),
1346 ComSafeArrayAsOutParam (retRefValues),
1347 ComSafeArrayAsOutParam (retOrigValues),
1348 ComSafeArrayAsOutParam (retAutoValues),
1349 ComSafeArrayAsOutParam (retConfiguration)));
1350
1351 RTPrintf ("VirtualSystemDescription:\n");
1352 for (unsigned a = 0; a < retTypes.size(); ++a)
1353 {
1354 printf (" %d %ls %ls %ls\n",
1355 retTypes [a],
1356 Bstr (retOrigValues [a]).raw(),
1357 Bstr (retAutoValues [a]).raw(),
1358 Bstr (retConfiguration [a]).raw());
1359 }
1360 /* Show warnings from interpret */
1361 com::SafeArray<BSTR> retWarnings;
1362 CHECK_ERROR_BREAK (retVSD [i],
1363 GetWarnings(ComSafeArrayAsOutParam (retWarnings)));
1364 if (retWarnings.size() > 0)
1365 {
1366 RTPrintf ("The following warnings occurs on interpret:\n");
1367 for (unsigned r = 0; r < retWarnings.size(); ++r)
1368 RTPrintf ("%ls\n", Bstr (retWarnings [r]).raw());
1369 RTPrintf ("\n");
1370 }
1371 }
1372 RTPrintf ("\n");
1373 }
1374 RTPrintf ("Try to import the appliance ...\n");
1375 ComPtr<IProgress> progress;
1376 CHECK_ERROR_BREAK (appliance,
1377 ImportMachines (progress.asOutParam()));
1378 CHECK_ERROR (progress, WaitForCompletion (-1));
1379 if (SUCCEEDED (rc))
1380 {
1381 /* Check if the import was successfully */
1382 progress->COMGETTER (ResultCode)(&rc);
1383 if (FAILED (rc))
1384 {
1385 com::ProgressErrorInfo info (progress);
1386 if (info.isBasicAvailable())
1387 RTPrintf ("Error: failed to import appliance. Error message: %lS\n", info.getText().raw());
1388 else
1389 RTPrintf ("Error: failed to import appliance. No error message available!\n");
1390 }else
1391 RTPrintf ("Successfully imported the appliance.\n");
1392 }
1393
1394 }
1395 while (FALSE);
1396 printf ("\n");
1397#endif
1398
1399 printf ("Press enter to release Session and VirtualBox instances...");
1400 getchar();
1401
1402 // end "all-stuff" scope
1403 ////////////////////////////////////////////////////////////////////////////
1404 }
1405 while (0);
1406
1407 printf("Press enter to shutdown COM...");
1408 getchar();
1409
1410 com::Shutdown();
1411
1412 printf ("tstAPI FINISHED.\n");
1413
1414 return rc;
1415}
1416
1417#ifdef VBOX_WITH_RESOURCE_USAGE_API
1418static void queryMetrics (ComPtr<IVirtualBox> aVirtualBox,
1419 ComPtr <IPerformanceCollector> collector,
1420 ComSafeArrayIn (IUnknown *, objects))
1421{
1422 HRESULT rc;
1423
1424 //Bstr metricNames[] = { L"CPU/Load/User:avg,CPU/Load/System:avg,CPU/Load/Idle:avg,RAM/Usage/Total,RAM/Usage/Used:avg" };
1425 Bstr metricNames[] = { L"*" };
1426 com::SafeArray<BSTR> metrics (1);
1427 metricNames[0].cloneTo (&metrics [0]);
1428 com::SafeArray<BSTR> retNames;
1429 com::SafeIfaceArray<IUnknown> retObjects;
1430 com::SafeArray<BSTR> retUnits;
1431 com::SafeArray<ULONG> retScales;
1432 com::SafeArray<ULONG> retSequenceNumbers;
1433 com::SafeArray<ULONG> retIndices;
1434 com::SafeArray<ULONG> retLengths;
1435 com::SafeArray<LONG> retData;
1436 CHECK_ERROR (collector, QueryMetricsData(ComSafeArrayAsInParam(metrics),
1437 ComSafeArrayInArg(objects),
1438 ComSafeArrayAsOutParam(retNames),
1439 ComSafeArrayAsOutParam(retObjects),
1440 ComSafeArrayAsOutParam(retUnits),
1441 ComSafeArrayAsOutParam(retScales),
1442 ComSafeArrayAsOutParam(retSequenceNumbers),
1443 ComSafeArrayAsOutParam(retIndices),
1444 ComSafeArrayAsOutParam(retLengths),
1445 ComSafeArrayAsOutParam(retData)) );
1446 RTPrintf("Object Metric Values\n"
1447 "---------- -------------------- --------------------------------------------\n");
1448 for (unsigned i = 0; i < retNames.size(); i++)
1449 {
1450 Bstr metricUnit(retUnits[i]);
1451 Bstr metricName(retNames[i]);
1452 RTPrintf("%-10ls %-20ls ", getObjectName(aVirtualBox, retObjects[i]).raw(), metricName.raw());
1453 const char *separator = "";
1454 for (unsigned j = 0; j < retLengths[i]; j++)
1455 {
1456 if (retScales[i] == 1)
1457 RTPrintf("%s%d %ls", separator, retData[retIndices[i] + j], metricUnit.raw());
1458 else
1459 RTPrintf("%s%d.%02d%ls", separator, retData[retIndices[i] + j] / retScales[i],
1460 (retData[retIndices[i] + j] * 100 / retScales[i]) % 100, metricUnit.raw());
1461 separator = ", ";
1462 }
1463 RTPrintf("\n");
1464 }
1465}
1466
1467static Bstr getObjectName(ComPtr<IVirtualBox> aVirtualBox,
1468 ComPtr<IUnknown> aObject)
1469{
1470 HRESULT rc;
1471
1472 ComPtr<IHost> host = aObject;
1473 if (!host.isNull())
1474 return Bstr("host");
1475
1476 ComPtr<IMachine> machine = aObject;
1477 if (!machine.isNull())
1478 {
1479 Bstr name;
1480 CHECK_ERROR(machine, COMGETTER(Name)(name.asOutParam()));
1481 if (SUCCEEDED(rc))
1482 return name;
1483 }
1484 return Bstr("unknown");
1485}
1486
1487static void listAffectedMetrics(ComPtr<IVirtualBox> aVirtualBox,
1488 ComSafeArrayIn(IPerformanceMetric*, aMetrics))
1489{
1490 HRESULT rc;
1491 com::SafeIfaceArray<IPerformanceMetric> metrics(ComSafeArrayInArg(aMetrics));
1492 if (metrics.size())
1493 {
1494 ComPtr<IUnknown> object;
1495 Bstr metricName;
1496 RTPrintf("The following metrics were modified:\n\n"
1497 "Object Metric\n"
1498 "---------- --------------------\n");
1499 for (size_t i = 0; i < metrics.size(); i++)
1500 {
1501 CHECK_ERROR(metrics[i], COMGETTER(Object)(object.asOutParam()));
1502 CHECK_ERROR(metrics[i], COMGETTER(MetricName)(metricName.asOutParam()));
1503 RTPrintf("%-10ls %-20ls\n",
1504 getObjectName(aVirtualBox, object).raw(), metricName.raw());
1505 }
1506 RTPrintf("\n");
1507 }
1508 else
1509 {
1510 RTPrintf("No metrics match the specified filter!\n");
1511 }
1512}
1513
1514#endif /* VBOX_WITH_RESOURCE_USAGE_API */
Note: See TracBrowser for help on using the repository browser.

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