VirtualBox

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

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

Main: turn read/write param in OpenHardDisk into an enum

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