VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxManage/VBoxManage.cpp@ 33764

Last change on this file since 33764 was 33764, checked in by vboxsync, 14 years ago

VBoxManage: Fixed incorrect return from errorGetOpt (VINF_SUCCESS instead of non-zero). Some rc cleanup in main().

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 15.5 KB
Line 
1/* $Id: VBoxManage.cpp 33764 2010-11-04 13:50:21Z vboxsync $ */
2/** @file
3 * VBoxManage - VirtualBox's command-line interface.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
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
18
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#ifndef VBOX_ONLY_DOCS
23# include <VBox/com/com.h>
24# include <VBox/com/string.h>
25# include <VBox/com/Guid.h>
26# include <VBox/com/array.h>
27# include <VBox/com/ErrorInfo.h>
28# include <VBox/com/errorprint.h>
29# include <VBox/com/EventQueue.h>
30
31# include <VBox/com/VirtualBox.h>
32#endif /* !VBOX_ONLY_DOCS */
33
34#include <VBox/err.h>
35#include <VBox/version.h>
36
37#include <iprt/asm.h>
38#include <iprt/buildconfig.h>
39#include <iprt/initterm.h>
40#include <iprt/stream.h>
41#include <iprt/string.h>
42
43#include <signal.h>
44
45#include "VBoxManage.h"
46
47
48/*******************************************************************************
49* Global Variables *
50*******************************************************************************/
51/*extern*/ bool g_fDetailedProgress = false;
52
53#ifndef VBOX_ONLY_DOCS
54/** Set by the signal handler. */
55static volatile bool g_fCanceled = false;
56
57
58/**
59 * Signal handler that sets g_fCanceled.
60 *
61 * This can be executed on any thread in the process, on Windows it may even be
62 * a thread dedicated to delivering this signal. Do not doing anything
63 * unnecessary here.
64 */
65static void showProgressSignalHandler(int iSignal)
66{
67 NOREF(iSignal);
68 ASMAtomicWriteBool(&g_fCanceled, true);
69}
70
71
72/**
73 * Print out progress on the console
74 */
75HRESULT showProgress(ComPtr<IProgress> progress)
76{
77 using namespace com;
78
79 BOOL fCompleted;
80 ULONG ulCurrentPercent;
81 ULONG ulLastPercent = 0;
82
83 ULONG ulCurrentOperationPercent;
84 ULONG ulLastOperationPercent = (ULONG)-1;
85
86 ULONG ulLastOperation = (ULONG)-1;
87 Bstr bstrOperationDescription;
88
89 ULONG cOperations;
90 progress->COMGETTER(OperationCount)(&cOperations);
91
92 if (!g_fDetailedProgress)
93 {
94 RTStrmPrintf(g_pStdErr, "0%%...");
95 RTStrmFlush(g_pStdErr);
96 }
97
98 /* setup signal handling if cancelable */
99 bool fCanceledAlready = false;
100 BOOL fCancelable;
101 HRESULT hrc = progress->COMGETTER(Cancelable)(&fCancelable);
102 if (FAILED(hrc))
103 fCancelable = FALSE;
104 if (fCancelable)
105 {
106 signal(SIGINT, showProgressSignalHandler);
107#ifdef SIGBREAK
108 signal(SIGBREAK, showProgressSignalHandler);
109#endif
110 }
111
112 while (SUCCEEDED(progress->COMGETTER(Completed(&fCompleted))))
113 {
114 ULONG ulOperation;
115 progress->COMGETTER(Operation)(&ulOperation);
116
117 progress->COMGETTER(Percent(&ulCurrentPercent));
118 progress->COMGETTER(OperationPercent(&ulCurrentOperationPercent));
119
120 if (g_fDetailedProgress)
121 {
122 if (ulLastOperation != ulOperation)
123 {
124 progress->COMGETTER(OperationDescription(bstrOperationDescription.asOutParam()));
125 ulLastPercent = (ULONG)-1; // force print
126 ulLastOperation = ulOperation;
127 }
128
129 if ( ulCurrentPercent != ulLastPercent
130 || ulCurrentOperationPercent != ulLastOperationPercent
131 )
132 {
133 LONG lSecsRem;
134 progress->COMGETTER(TimeRemaining)(&lSecsRem);
135
136 RTStrmPrintf(g_pStdErr, "(%ld/%ld) %ls %ld%% => %ld%% (%d s remaining)\n", ulOperation + 1, cOperations, bstrOperationDescription.raw(), ulCurrentOperationPercent, ulCurrentPercent, lSecsRem);
137 ulLastPercent = ulCurrentPercent;
138 ulLastOperationPercent = ulCurrentOperationPercent;
139 }
140 }
141 else
142 {
143 /* did we cross a 10% mark? */
144 if (ulCurrentPercent / 10 > ulLastPercent / 10)
145 {
146 /* make sure to also print out missed steps */
147 for (ULONG curVal = (ulLastPercent / 10) * 10 + 10; curVal <= (ulCurrentPercent / 10) * 10; curVal += 10)
148 {
149 if (curVal < 100)
150 {
151 RTStrmPrintf(g_pStdErr, "%ld%%...", curVal);
152 RTStrmFlush(g_pStdErr);
153 }
154 }
155 ulLastPercent = (ulCurrentPercent / 10) * 10;
156 }
157 }
158 if (fCompleted)
159 break;
160
161 /* process async cancelation */
162 if (g_fCanceled && !fCanceledAlready)
163 {
164 hrc = progress->Cancel();
165 if (SUCCEEDED(hrc))
166 fCanceledAlready = true;
167 else
168 g_fCanceled = false;
169 }
170
171 /* make sure the loop is not too tight */
172 progress->WaitForCompletion(100);
173 }
174
175 /* undo signal handling */
176 if (fCancelable)
177 {
178 signal(SIGINT, SIG_DFL);
179#ifdef SIGBREAK
180 signal(SIGBREAK, SIG_DFL);
181#endif
182 }
183
184 /* complete the line. */
185 LONG iRc = E_FAIL;
186 if (SUCCEEDED(progress->COMGETTER(ResultCode)(&iRc)))
187 {
188 if (SUCCEEDED(iRc))
189 RTStrmPrintf(g_pStdErr, "100%%\n");
190 else if (g_fCanceled)
191 RTStrmPrintf(g_pStdErr, "CANCELED\n");
192 else
193 RTStrmPrintf(g_pStdErr, "FAILED\n");
194 }
195 else
196 RTStrmPrintf(g_pStdErr, "\n");
197 RTStrmFlush(g_pStdErr);
198 return iRc;
199}
200
201#endif /* !VBOX_ONLY_DOCS */
202
203int main(int argc, char *argv[])
204{
205 /*
206 * Before we do anything, init the runtime without loading
207 * the support driver.
208 */
209 RTR3Init();
210
211 /*
212 * Parse the global options
213 */
214 bool fShowLogo = false;
215 bool fShowHelp = false;
216 int iCmd = 1;
217 int iCmdArg;
218
219 for (int i = 1; i < argc || argc <= iCmd; i++)
220 {
221 if ( argc <= iCmd
222 || !strcmp(argv[i], "help")
223 || !strcmp(argv[i], "-?")
224 || !strcmp(argv[i], "-h")
225 || !strcmp(argv[i], "-help")
226 || !strcmp(argv[i], "--help"))
227 {
228 if (i >= argc - 1)
229 {
230 showLogo(g_pStdOut);
231 printUsage(USAGE_ALL, g_pStdOut);
232 return 0;
233 }
234 fShowLogo = true;
235 fShowHelp = true;
236 iCmd++;
237 continue;
238 }
239
240 if ( !strcmp(argv[i], "-v")
241 || !strcmp(argv[i], "-version")
242 || !strcmp(argv[i], "-Version")
243 || !strcmp(argv[i], "--version"))
244 {
245 /* Print version number, and do nothing else. */
246 RTPrintf("%sr%d\n", VBOX_VERSION_STRING, RTBldCfgRevision());
247 return 0;
248 }
249
250 if ( !strcmp(argv[i], "--dumpopts")
251 || !strcmp(argv[i], "-dumpopts"))
252 {
253 /* Special option to dump really all commands,
254 * even the ones not understood on this platform. */
255 printUsage(USAGE_DUMPOPTS, g_pStdOut);
256 return 0;
257 }
258
259 if ( !strcmp(argv[i], "--nologo")
260 || !strcmp(argv[i], "-nologo")
261 || !strcmp(argv[i], "-q"))
262 {
263 /* suppress the logo */
264 fShowLogo = false;
265 iCmd++;
266 }
267 else
268 {
269 break;
270 }
271 }
272
273 iCmdArg = iCmd + 1;
274
275 if (fShowLogo)
276 showLogo(g_pStdOut);
277
278
279#ifndef VBOX_ONLY_DOCS
280 /*
281 * Initialize COM.
282 */
283 using namespace com;
284 HRESULT hrc = com::Initialize();
285 if (FAILED(hrc))
286 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM!");
287
288 /*
289 * The input is ASSUMED to be in the current process codeset (NT guarantees
290 * ACP, unixy systems doesn't guarantee anything). This loop converts all
291 * the argv[*] strings to UTF-8, which is a tad ugly but who cares.
292 * (As a rule all strings in VirtualBox are UTF-8.)
293 */
294 for (int i = iCmdArg; i < argc; i++)
295 {
296 char *pszConverted;
297 int rc = RTStrCurrentCPToUtf8(&pszConverted, argv[i]);
298 if (RT_SUCCESS(rc))
299 argv[i] = pszConverted;
300 else
301 /* Conversion was not possible,probably due to invalid characters.
302 * Keep in mind that we do RTStrFree on the whole array below. */
303 argv[i] = RTStrDup(argv[i]);
304 }
305
306 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
307 do
308 {
309 ///////////////////////////////////////////////////////////////////////////
310 // scopes all the stuff till shutdown
311 /*
312 * convertfromraw: does not need a VirtualBox instantiation.
313 */
314 if (argc >= iCmdArg && ( !strcmp(argv[iCmd], "convertfromraw")
315 || !strcmp(argv[iCmd], "convertdd")))
316 {
317 rcExit = handleConvertFromRaw(argc - iCmdArg, argv + iCmdArg);
318 break;
319 }
320
321 /*
322 * Get the remote VirtualBox object and create a local session object.
323 */
324 ComPtr<IVirtualBox> virtualBox;
325 ComPtr<ISession> session;
326
327 hrc = virtualBox.createLocalObject(CLSID_VirtualBox);
328 if (FAILED(hrc))
329 RTMsgError("Failed to create the VirtualBox object!");
330 else
331 {
332 hrc = session.createInprocObject(CLSID_Session);
333 if (FAILED(hrc))
334 RTMsgError("Failed to create a session object!");
335 }
336 if (FAILED(hrc))
337 {
338 com::ErrorInfo info;
339 if (!info.isFullAvailable() && !info.isBasicAvailable())
340 {
341 com::GluePrintRCMessage(hrc);
342 RTMsgError("Most likely, the VirtualBox COM server is not running or failed to start.");
343 }
344 else
345 com::GluePrintErrorInfo(info);
346 break;
347 }
348
349 /*
350 * All registered command handlers
351 */
352 static const struct
353 {
354 const char *command;
355 USAGECATEGORY help;
356 int (*handler)(HandlerArg *a);
357 } s_commandHandlers[] =
358 {
359 { "internalcommands", 0, handleInternalCommands },
360 { "list", USAGE_LIST, handleList },
361 { "showvminfo", USAGE_SHOWVMINFO, handleShowVMInfo },
362 { "registervm", USAGE_REGISTERVM, handleRegisterVM },
363 { "unregistervm", USAGE_UNREGISTERVM, handleUnregisterVM },
364 { "createhd", USAGE_CREATEHD, handleCreateHardDisk },
365 { "createvdi", USAGE_CREATEHD, handleCreateHardDisk }, /* backward compatibility */
366 { "modifyhd", USAGE_MODIFYHD, handleModifyHardDisk },
367 { "modifyvdi", USAGE_MODIFYHD, handleModifyHardDisk }, /* backward compatibility */
368 { "clonehd", USAGE_CLONEHD, handleCloneHardDisk },
369 { "clonevdi", USAGE_CLONEHD, handleCloneHardDisk }, /* backward compatibility */
370 { "addiscsidisk", USAGE_ADDISCSIDISK, handleAddiSCSIDisk },
371 { "createvm", USAGE_CREATEVM, handleCreateVM },
372 { "modifyvm", USAGE_MODIFYVM, handleModifyVM },
373 { "startvm", USAGE_STARTVM, handleStartVM },
374 { "controlvm", USAGE_CONTROLVM, handleControlVM },
375 { "discardstate", USAGE_DISCARDSTATE, handleDiscardState },
376 { "adoptstate", USAGE_ADOPTSTATE, handleAdoptState },
377 { "snapshot", USAGE_SNAPSHOT, handleSnapshot },
378 { "closemedium", USAGE_CLOSEMEDIUM, handleCloseMedium },
379 { "storageattach", USAGE_STORAGEATTACH, handleStorageAttach },
380 { "storagectl", USAGE_STORAGECONTROLLER, handleStorageController },
381 { "showhdinfo", USAGE_SHOWHDINFO, handleShowHardDiskInfo },
382 { "showvdiinfo", USAGE_SHOWHDINFO, handleShowHardDiskInfo }, /* backward compatibility */
383 { "getextradata", USAGE_GETEXTRADATA, handleGetExtraData },
384 { "setextradata", USAGE_SETEXTRADATA, handleSetExtraData },
385 { "setproperty", USAGE_SETPROPERTY, handleSetProperty },
386 { "usbfilter", USAGE_USBFILTER, handleUSBFilter },
387 { "sharedfolder", USAGE_SHAREDFOLDER, handleSharedFolder },
388 { "vmstatistics", USAGE_VM_STATISTICS, handleVMStatistics },
389#ifdef VBOX_WITH_GUEST_PROPS
390 { "guestproperty", USAGE_GUESTPROPERTY, handleGuestProperty },
391#endif
392#ifdef VBOX_WITH_GUEST_CONTROL
393 { "guestcontrol", USAGE_GUESTCONTROL, handleGuestControl },
394#endif
395 { "metrics", USAGE_METRICS, handleMetrics },
396 { "import", USAGE_IMPORTAPPLIANCE, handleImportAppliance },
397 { "export", USAGE_EXPORTAPPLIANCE, handleExportAppliance },
398#ifdef VBOX_WITH_NETFLT
399 { "hostonlyif", USAGE_HOSTONLYIFS, handleHostonlyIf },
400#endif
401 { "dhcpserver", USAGE_DHCPSERVER, handleDHCPServer},
402 { "vrde", USAGE_VRDE, handleVRDE},
403 { NULL, 0, NULL }
404 };
405
406 HandlerArg handlerArg = { 0, NULL, virtualBox, session };
407 int commandIndex;
408 for (commandIndex = 0; s_commandHandlers[commandIndex].command != NULL; commandIndex++)
409 {
410 if (!strcmp(s_commandHandlers[commandIndex].command, argv[iCmd]))
411 {
412 handlerArg.argc = argc - iCmdArg;
413 handlerArg.argv = &argv[iCmdArg];
414
415 if ( fShowHelp
416 || ( argc - iCmdArg == 0
417 && s_commandHandlers[commandIndex].help))
418 {
419 printUsage(s_commandHandlers[commandIndex].help, g_pStdOut);
420 rcExit = RTEXITCODE_FAILURE; /* error */
421 }
422 else
423 rcExit = (RTEXITCODE)s_commandHandlers[commandIndex].handler(&handlerArg); /** @todo Change to return RTEXITCODE. */
424 break;
425 }
426 }
427 if (!s_commandHandlers[commandIndex].command)
428 rcExit = errorSyntax(USAGE_ALL, "Invalid command '%s'", Utf8Str(argv[iCmd]).c_str());
429
430 /* Although all handlers should always close the session if they open it,
431 * we do it here just in case if some of the handlers contains a bug --
432 * leaving the direct session not closed will turn the machine state to
433 * Aborted which may have unwanted side effects like killing the saved
434 * state file (if the machine was in the Saved state before). */
435 session->UnlockMachine();
436
437 EventQueue::getMainEventQueue()->processEventQueue(0);
438
439 // end "all-stuff" scope
440 ///////////////////////////////////////////////////////////////////////////
441 } while (0);
442
443 com::Shutdown();
444
445 /*
446 * Free converted argument vector
447 */
448 for (int i = iCmdArg; i < argc; i++)
449 {
450 RTStrFree(argv[i]);
451 argv[i] = NULL;
452 }
453
454 return rcExit;
455#else /* VBOX_ONLY_DOCS */
456 return RTEXITCODE_SUCCESS;
457#endif /* VBOX_ONLY_DOCS */
458}
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