VirtualBox

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

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

PerfAPI: Added setupMetricsEx(), enableMetricsEx() and disableMetricsEx(). Added -list option to VBoxManage metrics setup. Updated docs and tstAPI.

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