VirtualBox

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

Last change on this file since 30020 was 30020, checked in by vboxsync, 15 years ago

Guest Control/Main: Get rid of busy waiting, use multi stage progress objects, clean up temporary callback contexts.

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