VirtualBox

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

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

Guest Control/Main: Update on local process list and IGuest::GetProcessStatus().

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 14.5 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 28780 2010-04-26 20:26:03Z vboxsync $ */
2/** @file
3 * VBoxManage - The 'guestcontrol' command.
4 */
5
6/*
7 * Copyright (C) 2010 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22
23/*******************************************************************************
24* Header Files *
25*******************************************************************************/
26#include "VBoxManage.h"
27
28#include <VBox/com/com.h>
29#include <VBox/com/string.h>
30#include <VBox/com/array.h>
31#include <VBox/com/ErrorInfo.h>
32#include <VBox/com/errorprint.h>
33
34#include <VBox/com/VirtualBox.h>
35#include <VBox/com/EventQueue.h>
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#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
62void usageGuestControl(void)
63{
64 RTPrintf("VBoxManage guestcontrol execute <vmname>|<uuid>\n"
65 " <path to program> [--arguments \"<arguments>\"] [--environment \"<NAME=VALUE NAME=VALUE>\"]\n"
66 " [--flags <flags>] [--timeout <msec>] [--username <name> [--password <password>]]\n"
67 " [--verbose] [--wait-for exit,stdout,stderr||]\n"
68 "\n");
69}
70
71static int handleExecProgram(HandlerArg *a)
72{
73 /*
74 * Check the syntax. We can deduce the correct syntax from the number of
75 * arguments.
76 */
77 if (a->argc < 2) /* At least the command we want to execute in the guest should be present :-). */
78 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
79
80 Utf8Str Utf8Cmd(a->argv[1]);
81 uint32_t uFlags = 0;
82 com::SafeArray <BSTR> args;
83 com::SafeArray <BSTR> env;
84 Utf8Str Utf8StdIn;
85 Utf8Str Utf8StdOut;
86 Utf8Str Utf8StdErr;
87 Utf8Str Utf8UserName;
88 Utf8Str Utf8Password;
89 uint32_t u32TimeoutMS = 0;
90 bool waitForExit = false;
91 bool waitForStdOut = false;
92 bool waitForStdErr = false;
93 bool verbose = false;
94 bool have_timeout = false;
95
96 /* Always use the actual command line as argv[0]. */
97 args.push_back(Bstr(Utf8Cmd));
98
99 /* Iterate through all possible commands (if available). */
100 bool usageOK = true;
101 for (int i = 2; usageOK && i < a->argc; i++)
102 {
103 if ( !strcmp(a->argv[i], "--arguments")
104 || !strcmp(a->argv[i], "--args")
105 || !strcmp(a->argv[i], "--arg"))
106 {
107 if (i + 1 >= a->argc)
108 usageOK = false;
109 else
110 {
111 char **papszArg;
112 int cArgs;
113
114 int vrc = RTGetOptArgvFromString(&papszArg, &cArgs, a->argv[i + 1], NULL);
115 if (RT_SUCCESS(vrc))
116 {
117 for (int j = 0; j < cArgs; j++)
118 args.push_back(Bstr(papszArg[j]));
119
120 RTGetOptArgvFree(papszArg);
121 }
122 ++i;
123 }
124 }
125 else if ( !strcmp(a->argv[i], "--environment")
126 || !strcmp(a->argv[i], "--env"))
127 {
128 if (i + 1 >= a->argc)
129 usageOK = false;
130 else
131 {
132 char **papszArg;
133 int cArgs;
134
135 int vrc = RTGetOptArgvFromString(&papszArg, &cArgs, a->argv[i + 1], NULL);
136 if (RT_SUCCESS(vrc))
137 {
138 for (int j = 0; j < cArgs; j++)
139 env.push_back(Bstr(papszArg[j]));
140
141 RTGetOptArgvFree(papszArg);
142 }
143 ++i;
144 }
145 }
146 else if (!strcmp(a->argv[i], "--flags"))
147 {
148 if ( i + 1 >= a->argc
149 || RTStrToUInt32Full(a->argv[i + 1], 10, &uFlags) != VINF_SUCCESS)
150 usageOK = false;
151 else
152 ++i;
153 }
154 else if ( !strcmp(a->argv[i], "--username")
155 || !strcmp(a->argv[i], "--user"))
156 {
157 if (i + 1 >= a->argc)
158 usageOK = false;
159 else
160 {
161 Utf8UserName = a->argv[i + 1];
162 ++i;
163 }
164 }
165 else if ( !strcmp(a->argv[i], "--password")
166 || !strcmp(a->argv[i], "--pwd"))
167 {
168 if (i + 1 >= a->argc)
169 usageOK = false;
170 else
171 {
172 Utf8Password = a->argv[i + 1];
173 ++i;
174 }
175 }
176 else if (!strcmp(a->argv[i], "--timeout"))
177 {
178 if ( i + 1 >= a->argc
179 || RTStrToUInt32Full(a->argv[i + 1], 10, &u32TimeoutMS) != VINF_SUCCESS
180 || u32TimeoutMS == 0)
181 {
182 usageOK = false;
183 }
184 else
185 {
186 have_timeout = true;
187 ++i;
188 }
189 }
190 else if (!strcmp(a->argv[i], "--wait-for"))
191 {
192 if (i + 1 >= a->argc)
193 usageOK = false;
194 else
195 {
196 if (!strcmp(a->argv[i + 1], "exit"))
197 waitForExit = true;
198 else if (!strcmp(a->argv[i + 1], "stdout"))
199 {
200 waitForExit = true;
201 waitForStdOut = true;
202 }
203 else if (!strcmp(a->argv[i + 1], "stderr"))
204 {
205 waitForExit = true;
206 waitForStdErr = true;
207 }
208 else
209 usageOK = false;
210 ++i;
211 }
212 }
213 else if (!strcmp(a->argv[i], "--verbose"))
214 {
215 verbose = true;
216 }
217 /** @todo Add fancy piping stuff here. */
218 else
219 {
220 return errorSyntax(USAGE_GUESTCONTROL,
221 "Invalid parameter '%s'", Utf8Str(a->argv[i]).raw());
222 }
223 }
224
225 if (!usageOK)
226 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
227
228 /* If a password was specified, check if we also got a user name. */
229 if ( !Utf8Password.isEmpty()
230 && Utf8UserName.isEmpty())
231 {
232 return errorSyntax(USAGE_GUESTCONTROL,
233 "No user name for password specified!");
234 }
235
236 /* lookup VM. */
237 ComPtr<IMachine> machine;
238 /* assume it's an UUID */
239 HRESULT rc = a->virtualBox->GetMachine(Bstr(a->argv[0]), machine.asOutParam());
240 if (FAILED(rc) || !machine)
241 {
242 /* must be a name */
243 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]), machine.asOutParam()));
244 }
245
246 if (machine)
247 {
248 do
249 {
250 Bstr uuid;
251 machine->COMGETTER(Id)(uuid.asOutParam());
252
253 /* open an existing session for VM - so the VM has to be running */
254 CHECK_ERROR_BREAK(a->virtualBox, OpenExistingSession(a->session, uuid));
255
256 /* get the mutable session machine */
257 a->session->COMGETTER(Machine)(machine.asOutParam());
258
259 /* get the associated console */
260 ComPtr<IConsole> console;
261 CHECK_ERROR_BREAK(a->session, COMGETTER(Console)(console.asOutParam()));
262
263 ComPtr<IGuest> guest;
264 CHECK_ERROR_BREAK(console, COMGETTER(Guest)(guest.asOutParam()));
265
266 ComPtr<IProgress> progress;
267 ULONG uPID = 0;
268
269 if (verbose)
270 {
271 if (u32TimeoutMS == 0)
272 RTPrintf("Waiting for guest to start process ...\n");
273 else
274 RTPrintf("Waiting for guest to start process (within %ums)\n", u32TimeoutMS);
275 }
276
277 /* Get current time stamp to later calculate rest of timeout left. */
278 uint64_t u64StartMS = RTTimeMilliTS();
279
280 /* Execute the process. */
281 CHECK_ERROR_BREAK(guest, ExecuteProcess(Bstr(Utf8Cmd), uFlags,
282 ComSafeArrayAsInParam(args), ComSafeArrayAsInParam(env),
283 Bstr(Utf8StdIn), Bstr(Utf8StdOut), Bstr(Utf8StdErr),
284 Bstr(Utf8UserName), Bstr(Utf8Password), u32TimeoutMS,
285 &uPID, progress.asOutParam()));
286 if (verbose) RTPrintf("Process '%s' (PID: %u) started.\n", Utf8Cmd.raw(), uPID);
287 if (waitForExit)
288 {
289 if (have_timeout)
290 {
291 /* Calculate timeout value left after process has been started. */
292 uint64_t u64Diff = RTTimeMilliTS() - u64StartMS;
293 /** @todo Check for uint64_t vs. uint32_t here! */
294 if (u32TimeoutMS > u64Diff) /* Is timeout still bigger than current difference? */
295 {
296 u32TimeoutMS = u32TimeoutMS - u64Diff;
297 if (verbose)
298 RTPrintf("Waiting for process to exit (%ums left) ...\n", u32TimeoutMS);
299 }
300 else
301 {
302 if (verbose)
303 RTPrintf("No time left to wait for process!\n");
304 }
305 }
306 else if (verbose)
307 RTPrintf("Waiting for process to exit ...\n");
308
309 /* Wait for process to exit ... */
310 ASSERT(progress);
311 rc = progress->WaitForCompletion(have_timeout ?
312 (u32TimeoutMS + 5000) : /* Timeout value + safety counter */
313 -1 /* Wait forever */);
314 if (FAILED(rc))
315 {
316 if (u32TimeoutMS)
317 RTPrintf("Process '%s' (PID: %u) did not end within %ums! Wait aborted.\n",
318 Utf8Cmd.raw(), uPID, u32TimeoutMS);
319 break;
320 }
321 else
322 {
323 BOOL completed;
324 CHECK_ERROR_RET(progress, COMGETTER(Completed)(&completed), rc);
325 ASSERT(completed);
326
327 LONG iRc;
328 CHECK_ERROR_RET(progress, COMGETTER(ResultCode)(&iRc), rc);
329 if (FAILED(iRc))
330 {
331 ComPtr<IVirtualBoxErrorInfo> execError;
332 rc = progress->COMGETTER(ErrorInfo)(execError.asOutParam());
333 com::ErrorInfo info (execError);
334 RTPrintf("Process error details:\n");
335 GluePrintErrorInfo(info);
336 RTPrintf("\n");
337 }
338 else
339 {
340 ULONG uStatus, uExitCode, uFlags;
341 CHECK_ERROR_BREAK(guest, GetProcessStatus(uPID, &uExitCode, &uFlags, &uStatus));
342 if (verbose)
343 RTPrintf("Process completed. Exit code = %u (Status = %u, Flags = %u)\n",
344 uExitCode, uStatus, uFlags);
345 }
346
347 /* Print output if wanted. */
348 if ( waitForStdOut
349 || waitForStdErr)
350 {
351 if (verbose) RTPrintf("Retrieving output data ...\n");
352 while (true)
353 {
354 SafeArray<BYTE> aOutputData;
355 ULONG cbOutputData;
356 CHECK_ERROR_BREAK(guest, GetProcessOutput(uPID, 0 /* aFlags */,
357 u32TimeoutMS, _64K, ComSafeArrayAsOutParam(aOutputData)));
358 cbOutputData = aOutputData.size();
359 if (cbOutputData == 0)
360 break;
361
362 /* aOutputData has a platform dependent line ending, standardize on
363 * Unix style, as RTStrmWrite does the LF -> CR/LF replacement on
364 * Windows. Otherwise we end up with CR/CR/LF on Windows. */
365 ULONG cbOutputDataPrint = cbOutputData;
366 for (BYTE *s = aOutputData.raw(), *d = s;
367 s - aOutputData.raw() < (ssize_t)cbOutputData;
368 s++, d++)
369 {
370 if (*s == '\r')
371 {
372 /* skip over CR, adjust destination */
373 d--;
374 cbOutputDataPrint--;
375 }
376 else if (s != d)
377 *d = *s;
378 }
379 RTStrmWrite(g_pStdOut, aOutputData.raw(), cbOutputDataPrint);
380 }
381 }
382 }
383 }
384 a->session->Close();
385 } while (0);
386 }
387 return SUCCEEDED(rc) ? 0 : 1;
388}
389
390/**
391 * Access the guest control store.
392 *
393 * @returns 0 on success, 1 on failure
394 * @note see the command line API description for parameters
395 */
396int handleGuestControl(HandlerArg *a)
397{
398 HandlerArg arg = *a;
399 arg.argc = a->argc - 1;
400 arg.argv = a->argv + 1;
401
402 if (a->argc == 0)
403 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
404
405 /* switch (cmd) */
406 if ( strcmp(a->argv[0], "exec") == 0
407 || strcmp(a->argv[0], "execute") == 0)
408 return handleExecProgram(&arg);
409
410 /* default: */
411 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
412}
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