VirtualBox

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

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

VBoxMange: print exit status in readable form

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