VirtualBox

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

最後變更 在這個檔案從32712是 32712,由 vboxsync 提交於 15 年 前

VBoxManage: forgot the help for guestproperty and guestcontrol; enable the latter for VBOX_ONLY_DOCS=1

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 19.1 KB
 
1/* $Id: VBoxManageGuestCtrl.cpp 32712 2010-09-23 12:16:51Z vboxsync $ */
2/** @file
3 * VBoxManage - Implementation of guestcontrol command.
4 */
5
6/*
7 * Copyright (C) 2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.alldomusa.eu.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#include "VBoxManage.h"
23
24#ifndef VBOX_ONLY_DOCS
25
26#include <VBox/com/com.h>
27#include <VBox/com/string.h>
28#include <VBox/com/array.h>
29#include <VBox/com/ErrorInfo.h>
30#include <VBox/com/errorprint.h>
31
32#include <VBox/com/VirtualBox.h>
33#include <VBox/com/EventQueue.h>
34
35#include <VBox/HostServices/GuestControlSvc.h> /* for PROC_STS_XXX */
36
37#include <VBox/log.h>
38#include <iprt/asm.h>
39#include <iprt/getopt.h>
40#include <iprt/stream.h>
41#include <iprt/string.h>
42#include <iprt/time.h>
43#include <iprt/thread.h>
44
45#ifdef USE_XPCOM_QUEUE
46# include <sys/select.h>
47# include <errno.h>
48#endif
49
50#include <signal.h>
51
52#ifdef RT_OS_DARWIN
53# include <CoreFoundation/CFRunLoop.h>
54#endif
55
56using namespace com;
57
58/**
59 * IVirtualBoxCallback implementation for handling the GuestControlCallback in
60 * relation to the "guestcontrol * wait" command.
61 */
62/** @todo */
63
64/** Set by the signal handler. */
65static volatile bool g_fExecCanceled = false;
66
67#endif /* VBOX_ONLY_DOCS */
68
69void usageGuestControl(PRTSTREAM pStrm)
70{
71 RTStrmPrintf(pStrm,
72 "VBoxManage guestcontrol execute <vmname>|<uuid>\n"
73 " <path to program>\n"
74 " --username <name> --password <password>\n"
75 " [--arguments \"<arguments>\"]\n"
76 " [--environment \"<NAME>=<VALUE> [<NAME>=<VALUE>]\"]\n"
77 " [--flags <flags>] [--timeout <msec>]\n"
78 " [--verbose] [--wait-for exit,stdout,stderr||]\n"
79 "\n");
80}
81
82#ifndef VBOX_ONLY_DOCS
83
84/**
85 * Signal handler that sets g_fCanceled.
86 *
87 * This can be executed on any thread in the process, on Windows it may even be
88 * a thread dedicated to delivering this signal. Do not doing anything
89 * unnecessary here.
90 */
91static void execProcessSignalHandler(int iSignal)
92{
93 NOREF(iSignal);
94 ASMAtomicWriteBool(&g_fExecCanceled, true);
95}
96
97static const char *getStatus(ULONG uStatus)
98{
99 switch (uStatus)
100 {
101 case guestControl::PROC_STS_STARTED:
102 return "started";
103 case guestControl::PROC_STS_TEN:
104 return "successfully terminated";
105 case guestControl::PROC_STS_TES:
106 return "terminated by signal";
107 case guestControl::PROC_STS_TEA:
108 return "abnormally aborted";
109 case guestControl::PROC_STS_TOK:
110 return "timed out";
111 case guestControl::PROC_STS_TOA:
112 return "timed out, hanging";
113 case guestControl::PROC_STS_DWN:
114 return "killed";
115 case guestControl::PROC_STS_ERROR:
116 return "error";
117 default:
118 return "unknown";
119 }
120}
121
122static int handleExecProgram(HandlerArg *a)
123{
124 /*
125 * Check the syntax. We can deduce the correct syntax from the number of
126 * arguments.
127 */
128 if (a->argc < 2) /* At least the command we want to execute in the guest should be present :-). */
129 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
130
131 Utf8Str Utf8Cmd(a->argv[1]);
132 uint32_t uFlags = 0;
133 com::SafeArray <BSTR> args;
134 com::SafeArray <BSTR> env;
135 Utf8Str Utf8UserName;
136 Utf8Str Utf8Password;
137 uint32_t u32TimeoutMS = 0;
138 bool fWaitForExit = false;
139 bool fWaitForStdOut = false;
140 bool fWaitForStdErr = false;
141 bool fVerbose = false;
142 bool fTimeout = false;
143
144 /* Always use the actual command line as argv[0]. */
145 args.push_back(Bstr(Utf8Cmd));
146
147 /* Iterate through all possible commands (if available). */
148 bool usageOK = true;
149 for (int i = 2; usageOK && i < a->argc; i++)
150 {
151 if ( !strcmp(a->argv[i], "--arguments")
152 || !strcmp(a->argv[i], "--args")
153 || !strcmp(a->argv[i], "--arg"))
154 {
155 if (i + 1 >= a->argc)
156 usageOK = false;
157 else
158 {
159 char **papszArg;
160 int cArgs;
161
162 int vrc = RTGetOptArgvFromString(&papszArg, &cArgs, a->argv[i + 1], NULL);
163 if (RT_SUCCESS(vrc))
164 {
165 for (int j = 0; j < cArgs; j++)
166 args.push_back(Bstr(papszArg[j]));
167
168 RTGetOptArgvFree(papszArg);
169 }
170 ++i;
171 }
172 }
173 else if ( !strcmp(a->argv[i], "--environment")
174 || !strcmp(a->argv[i], "--env"))
175 {
176 if (i + 1 >= a->argc)
177 usageOK = false;
178 else
179 {
180 char **papszArg;
181 int cArgs;
182
183 int vrc = RTGetOptArgvFromString(&papszArg, &cArgs, a->argv[i + 1], NULL);
184 if (RT_SUCCESS(vrc))
185 {
186 for (int j = 0; j < cArgs; j++)
187 env.push_back(Bstr(papszArg[j]));
188
189 RTGetOptArgvFree(papszArg);
190 }
191 ++i;
192 }
193 }
194 else if (!strcmp(a->argv[i], "--flags"))
195 {
196 if ( i + 1 >= a->argc
197 || RTStrToUInt32Full(a->argv[i + 1], 10, &uFlags) != VINF_SUCCESS)
198 usageOK = false;
199 else
200 ++i;
201 }
202 else if ( !strcmp(a->argv[i], "--username")
203 || !strcmp(a->argv[i], "--user"))
204 {
205 if (i + 1 >= a->argc)
206 usageOK = false;
207 else
208 {
209 Utf8UserName = a->argv[i + 1];
210 ++i;
211 }
212 }
213 else if ( !strcmp(a->argv[i], "--password")
214 || !strcmp(a->argv[i], "--pwd"))
215 {
216 if (i + 1 >= a->argc)
217 usageOK = false;
218 else
219 {
220 Utf8Password = a->argv[i + 1];
221 ++i;
222 }
223 }
224 else if (!strcmp(a->argv[i], "--timeout"))
225 {
226 if ( i + 1 >= a->argc
227 || RTStrToUInt32Full(a->argv[i + 1], 10, &u32TimeoutMS) != VINF_SUCCESS
228 || u32TimeoutMS == 0)
229 {
230 usageOK = false;
231 }
232 else
233 {
234 fTimeout = true;
235 ++i;
236 }
237 }
238 else if (!strcmp(a->argv[i], "--wait-for"))
239 {
240 if (i + 1 >= a->argc)
241 usageOK = false;
242 else
243 {
244 if (!strcmp(a->argv[i + 1], "exit"))
245 fWaitForExit = true;
246 else if (!strcmp(a->argv[i + 1], "stdout"))
247 {
248 fWaitForExit = true;
249 fWaitForStdOut = true;
250 }
251 else if (!strcmp(a->argv[i + 1], "stderr"))
252 {
253 fWaitForExit = true;
254 fWaitForStdErr = true;
255 }
256 else
257 usageOK = false;
258 ++i;
259 }
260 }
261 else if (!strcmp(a->argv[i], "--verbose"))
262 fVerbose = true;
263 /** @todo Add fancy piping stuff here. */
264 else
265 return errorSyntax(USAGE_GUESTCONTROL,
266 "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
267 }
268
269 if (!usageOK)
270 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
271
272 if (Utf8UserName.isEmpty())
273 return errorSyntax(USAGE_GUESTCONTROL,
274 "No user name specified!");
275
276 /* lookup VM. */
277 ComPtr<IMachine> machine;
278 /* assume it's an UUID */
279 HRESULT rc = a->virtualBox->GetMachine(Bstr(a->argv[0]), machine.asOutParam());
280 if (FAILED(rc) || !machine)
281 {
282 /* must be a name */
283 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]), machine.asOutParam()));
284 }
285
286 if (machine)
287 {
288 do
289 {
290 /* open an existing session for VM */
291 CHECK_ERROR_BREAK(machine, LockMachine(a->session, LockType_Shared));
292 // @todo r=dj assert that it's an existing session
293
294 /* get the mutable session machine */
295 a->session->COMGETTER(Machine)(machine.asOutParam());
296
297 /* get the associated console */
298 ComPtr<IConsole> console;
299 CHECK_ERROR_BREAK(a->session, COMGETTER(Console)(console.asOutParam()));
300
301 ComPtr<IGuest> guest;
302 CHECK_ERROR_BREAK(console, COMGETTER(Guest)(guest.asOutParam()));
303
304 ComPtr<IProgress> progress;
305 ULONG uPID = 0;
306
307 if (fVerbose)
308 {
309 if (u32TimeoutMS == 0)
310 RTPrintf("Waiting for guest to start process ...\n");
311 else
312 RTPrintf("Waiting for guest to start process (within %ums)\n", u32TimeoutMS);
313 }
314
315 /* Get current time stamp to later calculate rest of timeout left. */
316 uint64_t u64StartMS = RTTimeMilliTS();
317
318 /* Execute the process. */
319 rc = guest->ExecuteProcess(Bstr(Utf8Cmd), uFlags,
320 ComSafeArrayAsInParam(args), ComSafeArrayAsInParam(env),
321 Bstr(Utf8UserName), Bstr(Utf8Password), u32TimeoutMS,
322 &uPID, progress.asOutParam());
323 if (FAILED(rc))
324 {
325 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
326 * because it contains more accurate info about what went wrong. */
327 ErrorInfo info(guest, COM_IIDOF(IGuest));
328 if (info.isFullAvailable())
329 {
330 if (rc == VBOX_E_IPRT_ERROR)
331 RTMsgError("%ls.", info.getText().raw());
332 else
333 RTMsgError("%ls (%Rhrc).", info.getText().raw(), info.getResultCode());
334 }
335 break;
336 }
337 if (fVerbose)
338 RTPrintf("Process '%s' (PID: %u) started\n", Utf8Cmd.c_str(), uPID);
339 if (fWaitForExit)
340 {
341 if (fTimeout)
342 {
343 /* Calculate timeout value left after process has been started. */
344 uint64_t u64Elapsed = RTTimeMilliTS() - u64StartMS;
345 /* Is timeout still bigger than current difference? */
346 if (u32TimeoutMS > u64Elapsed)
347 {
348 u32TimeoutMS -= (uint32_t)u64Elapsed;
349 if (fVerbose)
350 RTPrintf("Waiting for process to exit (%ums left) ...\n", u32TimeoutMS);
351 }
352 else
353 {
354 if (fVerbose)
355 RTPrintf("No time left to wait for process!\n");
356 }
357 }
358 else if (fVerbose)
359 RTPrintf("Waiting for process to exit ...\n");
360
361 /* setup signal handling if cancelable */
362 ASSERT(progress);
363 bool fCanceledAlready = false;
364 BOOL fCancelable;
365 HRESULT hrc = progress->COMGETTER(Cancelable)(&fCancelable);
366 if (FAILED(hrc))
367 fCancelable = FALSE;
368 if (fCancelable)
369 {
370 signal(SIGINT, execProcessSignalHandler);
371 #ifdef SIGBREAK
372 signal(SIGBREAK, execProcessSignalHandler);
373 #endif
374 }
375
376 /* Wait for process to exit ... */
377 BOOL fCompleted = FALSE;
378 BOOL fCanceled = FALSE;
379 while (SUCCEEDED(progress->COMGETTER(Completed(&fCompleted))))
380 {
381 SafeArray<BYTE> aOutputData;
382 ULONG cbOutputData = 0;
383
384 /*
385 * Some data left to output?
386 */
387 if ( fWaitForStdOut
388 || fWaitForStdErr)
389 {
390
391 rc = guest->GetProcessOutput(uPID, 0 /* aFlags */,
392 u32TimeoutMS, _64K, ComSafeArrayAsOutParam(aOutputData));
393 if (FAILED(rc))
394 {
395 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
396 * because it contains more accurate info about what went wrong. */
397 ErrorInfo info(guest, COM_IIDOF(IGuest));
398 if (info.isFullAvailable())
399 {
400 if (rc == VBOX_E_IPRT_ERROR)
401 RTMsgError("%ls.", info.getText().raw());
402 else
403 RTMsgError("%ls (%Rhrc).", info.getText().raw(), info.getResultCode());
404 }
405 cbOutputData = 0;
406 }
407 else
408 {
409 cbOutputData = aOutputData.size();
410 if (cbOutputData > 0)
411 {
412 /* aOutputData has a platform dependent line ending, standardize on
413 * Unix style, as RTStrmWrite does the LF -> CR/LF replacement on
414 * Windows. Otherwise we end up with CR/CR/LF on Windows. */
415 ULONG cbOutputDataPrint = cbOutputData;
416 for (BYTE *s = aOutputData.raw(), *d = s;
417 s - aOutputData.raw() < (ssize_t)cbOutputData;
418 s++, d++)
419 {
420 if (*s == '\r')
421 {
422 /* skip over CR, adjust destination */
423 d--;
424 cbOutputDataPrint--;
425 }
426 else if (s != d)
427 *d = *s;
428 }
429 RTStrmWrite(g_pStdOut, aOutputData.raw(), cbOutputDataPrint);
430 }
431 }
432 }
433
434 if (cbOutputData <= 0) /* No more output data left? */
435 {
436 if (fCompleted)
437 break;
438
439 if ( fTimeout
440 && RTTimeMilliTS() - u64StartMS > u32TimeoutMS + 5000)
441 {
442 progress->Cancel();
443 break;
444 }
445 }
446
447 /* Process async cancelation */
448 if (g_fExecCanceled && !fCanceledAlready)
449 {
450 hrc = progress->Cancel();
451 if (SUCCEEDED(hrc))
452 fCanceledAlready = TRUE;
453 else
454 g_fExecCanceled = false;
455 }
456
457 /* Progress canceled by Main API? */
458 if ( SUCCEEDED(progress->COMGETTER(Canceled(&fCanceled)))
459 && fCanceled)
460 {
461 break;
462 }
463 }
464
465 /* Undo signal handling */
466 if (fCancelable)
467 {
468 signal(SIGINT, SIG_DFL);
469 #ifdef SIGBREAK
470 signal(SIGBREAK, SIG_DFL);
471 #endif
472 }
473
474 if (fCanceled)
475 {
476 if (fVerbose)
477 RTPrintf("Process execution canceled!\n");
478 }
479 else if ( fCompleted
480 && SUCCEEDED(rc))
481 {
482 LONG iRc = false;
483 CHECK_ERROR_RET(progress, COMGETTER(ResultCode)(&iRc), rc);
484 if (FAILED(iRc))
485 {
486 ComPtr<IVirtualBoxErrorInfo> execError;
487 rc = progress->COMGETTER(ErrorInfo)(execError.asOutParam());
488 com::ErrorInfo info(execError, COM_IIDOF(IVirtualBoxErrorInfo));
489 if (SUCCEEDED(rc) && info.isFullAvailable())
490 {
491 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
492 * because it contains more accurate info about what went wrong. */
493 if (info.getResultCode() == VBOX_E_IPRT_ERROR)
494 RTMsgError("%ls.", info.getText().raw());
495 else
496 {
497 RTMsgError("Process error details:");
498 GluePrintErrorInfo(info);
499 }
500 }
501 else
502 AssertMsgFailed(("Full error description is missing!\n"));
503 }
504 else if (fVerbose)
505 {
506 ULONG uRetStatus, uRetExitCode, uRetFlags;
507 rc = guest->GetProcessStatus(uPID, &uRetExitCode, &uRetFlags, &uRetStatus);
508 if (SUCCEEDED(rc))
509 RTPrintf("Exit code=%u (Status=%u [%s], Flags=%u)\n", uRetExitCode, uRetStatus, getStatus(uRetStatus), uRetFlags);
510 }
511 }
512 else
513 {
514 if (fVerbose)
515 RTPrintf("Process execution aborted!\n");
516 }
517 }
518 a->session->UnlockMachine();
519 } while (0);
520 }
521 return SUCCEEDED(rc) ? 0 : 1;
522}
523
524/**
525 * Access the guest control store.
526 *
527 * @returns 0 on success, 1 on failure
528 * @note see the command line API description for parameters
529 */
530int handleGuestControl(HandlerArg *a)
531{
532 HandlerArg arg = *a;
533 arg.argc = a->argc - 1;
534 arg.argv = a->argv + 1;
535
536 if (a->argc == 0)
537 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
538
539 /* switch (cmd) */
540 if ( strcmp(a->argv[0], "exec") == 0
541 || strcmp(a->argv[0], "execute") == 0)
542 return handleExecProgram(&arg);
543
544 /* default: */
545 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
546}
547
548#endif /* !VBOX_ONLY_DOCS */
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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