VirtualBox

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

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

Enabled testcase for Host::MemorySize and MemoryAvailable in tstAPI by default.

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