VirtualBox

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

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

Main: rename ISession::close() to ISession::unlockMachine(); API documentation

  • 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 31070 2010-07-23 16:00:09Z 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 /* open an existing session for VM */
288 CHECK_ERROR_BREAK(machine, LockMachine(a->session, LockType_Shared));
289 // @todo r=dj assert that it's an existing session
290
291 /* get the mutable session machine */
292 a->session->COMGETTER(Machine)(machine.asOutParam());
293
294 /* get the associated console */
295 ComPtr<IConsole> console;
296 CHECK_ERROR_BREAK(a->session, COMGETTER(Console)(console.asOutParam()));
297
298 ComPtr<IGuest> guest;
299 CHECK_ERROR_BREAK(console, COMGETTER(Guest)(guest.asOutParam()));
300
301 ComPtr<IProgress> progress;
302 ULONG uPID = 0;
303
304 if (fVerbose)
305 {
306 if (u32TimeoutMS == 0)
307 RTPrintf("Waiting for guest to start process ...\n");
308 else
309 RTPrintf("Waiting for guest to start process (within %ums)\n", u32TimeoutMS);
310 }
311
312 /* Get current time stamp to later calculate rest of timeout left. */
313 uint64_t u64StartMS = RTTimeMilliTS();
314
315 /* Execute the process. */
316 rc = guest->ExecuteProcess(Bstr(Utf8Cmd), uFlags,
317 ComSafeArrayAsInParam(args), ComSafeArrayAsInParam(env),
318 Bstr(Utf8UserName), Bstr(Utf8Password), u32TimeoutMS,
319 &uPID, progress.asOutParam());
320 if (FAILED(rc))
321 {
322 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
323 * because it contains more accurate info about what went wrong. */
324 ErrorInfo info(guest, COM_IIDOF(IGuest));
325 if (info.isFullAvailable())
326 {
327 if (rc == VBOX_E_IPRT_ERROR)
328 RTPrintf("%ls.\n", info.getText().raw());
329 else
330 RTPrintf("ERROR: %ls (%Rhrc).\n", info.getText().raw(), info.getResultCode());
331 }
332 break;
333 }
334 if (fVerbose)
335 RTPrintf("Process '%s' (PID: %u) started\n", Utf8Cmd.raw(), uPID);
336 if (fWaitForExit)
337 {
338 if (fTimeout)
339 {
340 /* Calculate timeout value left after process has been started. */
341 uint64_t u64Diff = RTTimeMilliTS() - u64StartMS;
342 /** @todo Check for uint64_t vs. uint32_t here! */
343 if (u32TimeoutMS > u64Diff) /* Is timeout still bigger than current difference? */
344 {
345 u32TimeoutMS = u32TimeoutMS - u64Diff;
346 if (fVerbose)
347 RTPrintf("Waiting for process to exit (%ums left) ...\n", u32TimeoutMS);
348 }
349 else
350 {
351 if (fVerbose)
352 RTPrintf("No time left to wait for process!\n");
353 }
354 }
355 else if (fVerbose)
356 RTPrintf("Waiting for process to exit ...\n");
357
358 /* setup signal handling if cancelable */
359 ASSERT(progress);
360 bool fCanceledAlready = false;
361 BOOL fCancelable;
362 HRESULT hrc = progress->COMGETTER(Cancelable)(&fCancelable);
363 if (FAILED(hrc))
364 fCancelable = FALSE;
365 if (fCancelable)
366 {
367 signal(SIGINT, execProcessSignalHandler);
368 #ifdef SIGBREAK
369 signal(SIGBREAK, execProcessSignalHandler);
370 #endif
371 }
372
373 /* Wait for process to exit ... */
374 BOOL fCompleted = FALSE;
375 BOOL fCanceled = FALSE;
376 while (SUCCEEDED(progress->COMGETTER(Completed(&fCompleted))))
377 {
378 SafeArray<BYTE> aOutputData;
379 ULONG cbOutputData = 0;
380
381 /*
382 * Some data left to output?
383 */
384 if ( fWaitForStdOut
385 || fWaitForStdErr)
386 {
387
388 rc = guest->GetProcessOutput(uPID, 0 /* aFlags */,
389 u32TimeoutMS, _64K, ComSafeArrayAsOutParam(aOutputData));
390 if (FAILED(rc))
391 {
392 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
393 * because it contains more accurate info about what went wrong. */
394 ErrorInfo info(guest, COM_IIDOF(IGuest));
395 if (info.isFullAvailable())
396 {
397 if (rc == VBOX_E_IPRT_ERROR)
398 {
399 RTPrintf("%ls.\n", info.getText().raw());
400 }
401 else
402 {
403 RTPrintf("ERROR: %ls (%Rhrc).\n", info.getText().raw(), info.getResultCode());
404 }
405 }
406 cbOutputData = 0;
407 }
408 else
409 {
410 cbOutputData = aOutputData.size();
411 if (cbOutputData > 0)
412 {
413 /* aOutputData has a platform dependent line ending, standardize on
414 * Unix style, as RTStrmWrite does the LF -> CR/LF replacement on
415 * Windows. Otherwise we end up with CR/CR/LF on Windows. */
416 ULONG cbOutputDataPrint = cbOutputData;
417 for (BYTE *s = aOutputData.raw(), *d = s;
418 s - aOutputData.raw() < (ssize_t)cbOutputData;
419 s++, d++)
420 {
421 if (*s == '\r')
422 {
423 /* skip over CR, adjust destination */
424 d--;
425 cbOutputDataPrint--;
426 }
427 else if (s != d)
428 *d = *s;
429 }
430 RTStrmWrite(g_pStdOut, aOutputData.raw(), cbOutputDataPrint);
431 }
432 }
433 }
434
435 if (cbOutputData <= 0) /* No more output data left? */
436 {
437 if (fCompleted)
438 break;
439
440 if ( fTimeout
441 && RTTimeMilliTS() - u64StartMS > u32TimeoutMS + 5000)
442 {
443 progress->Cancel();
444 break;
445 }
446 }
447
448 /* Process async cancelation */
449 if (g_fExecCanceled && !fCanceledAlready)
450 {
451 hrc = progress->Cancel();
452 if (SUCCEEDED(hrc))
453 fCanceledAlready = TRUE;
454 else
455 g_fExecCanceled = false;
456 }
457
458 /* Progress canceled by Main API? */
459 if ( SUCCEEDED(progress->COMGETTER(Canceled(&fCanceled)))
460 && fCanceled)
461 {
462 break;
463 }
464 }
465
466 /* Undo signal handling */
467 if (fCancelable)
468 {
469 signal(SIGINT, SIG_DFL);
470 #ifdef SIGBREAK
471 signal(SIGBREAK, SIG_DFL);
472 #endif
473 }
474
475 if (fCanceled)
476 {
477 if (fVerbose)
478 RTPrintf("Process execution canceled!\n");
479 }
480 else if ( fCompleted
481 && SUCCEEDED(rc))
482 {
483 LONG iRc = false;
484 CHECK_ERROR_RET(progress, COMGETTER(ResultCode)(&iRc), rc);
485 if (FAILED(iRc))
486 {
487 ComPtr<IVirtualBoxErrorInfo> execError;
488 rc = progress->COMGETTER(ErrorInfo)(execError.asOutParam());
489 com::ErrorInfo info(execError, COM_IIDOF(IVirtualBoxErrorInfo));
490 if (SUCCEEDED(rc) && info.isFullAvailable())
491 {
492 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
493 * because it contains more accurate info about what went wrong. */
494 if (info.getResultCode() == VBOX_E_IPRT_ERROR)
495 {
496 RTPrintf("%ls.\n", info.getText().raw());
497 }
498 else
499 {
500 RTPrintf("\n\nProcess error details:\n");
501 GluePrintErrorInfo(info);
502 RTPrintf("\n");
503 }
504 }
505 else
506 AssertMsgFailed(("Full error description is missing!\n"));
507 }
508 else if (fVerbose)
509 {
510 ULONG uRetStatus, uRetExitCode, uRetFlags;
511 rc = guest->GetProcessStatus(uPID, &uRetExitCode, &uRetFlags, &uRetStatus);
512 if (SUCCEEDED(rc))
513 RTPrintf("Exit code=%u (Status=%u [%s], Flags=%u)\n", uRetExitCode, uRetStatus, getStatus(uRetStatus), uRetFlags);
514 }
515 }
516 else
517 {
518 if (fVerbose)
519 RTPrintf("Process execution aborted!\n");
520 }
521 }
522 a->session->UnlockMachine();
523 } while (0);
524 }
525 return SUCCEEDED(rc) ? 0 : 1;
526}
527
528/**
529 * Access the guest control store.
530 *
531 * @returns 0 on success, 1 on failure
532 * @note see the command line API description for parameters
533 */
534int handleGuestControl(HandlerArg *a)
535{
536 HandlerArg arg = *a;
537 arg.argc = a->argc - 1;
538 arg.argv = a->argv + 1;
539
540 if (a->argc == 0)
541 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
542
543 /* switch (cmd) */
544 if ( strcmp(a->argv[0], "exec") == 0
545 || strcmp(a->argv[0], "execute") == 0)
546 return handleExecProgram(&arg);
547
548 /* default: */
549 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
550}
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