VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxService.cpp@ 26292

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

Moved statistics and balloon handling to the guest service process

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 20.2 KB
Line 
1/* $Id: VBoxService.cpp 26292 2010-02-05 14:28:23Z vboxsync $ */
2/** @file
3 * VBoxService - Guest Additions Service Skeleton.
4 */
5
6/*
7 * Copyright (C) 2007-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/*******************************************************************************
25* Header Files *
26*******************************************************************************/
27/** @todo LOG_GROUP*/
28#ifndef _MSC_VER
29# include <unistd.h>
30#endif
31#include <errno.h>
32
33#include <iprt/asm.h>
34#include <iprt/buildconfig.h>
35#include <iprt/initterm.h>
36#include <iprt/path.h>
37#include <iprt/string.h>
38#include <iprt/stream.h>
39#include <iprt/thread.h>
40
41#include <VBox/VBoxGuestLib.h>
42#include <VBox/log.h>
43
44#include "VBoxServiceInternal.h"
45
46
47/*******************************************************************************
48* Global Variables *
49*******************************************************************************/
50/** The program name (derived from argv[0]). */
51char *g_pszProgName = (char *)"";
52/** The current verbosity level. */
53int g_cVerbosity = 0;
54/** The default service interval (the -i | --interval) option). */
55uint32_t g_DefaultInterval = 0;
56/** Shutdown the main thread. (later, for signals.) */
57bool volatile g_fShutdown;
58
59/**
60 * The details of the services that has been compiled in.
61 */
62static struct
63{
64 /** Pointer to the service descriptor. */
65 PCVBOXSERVICE pDesc;
66 /** The worker thread. NIL_RTTHREAD if it's the main thread. */
67 RTTHREAD Thread;
68 /** Shutdown indicator. */
69 bool volatile fShutdown;
70 /** Indicator set by the service thread exiting. */
71 bool volatile fStopped;
72 /** Whether the service was started or not. */
73 bool fStarted;
74 /** Whether the service is enabled or not. */
75 bool fEnabled;
76} g_aServices[] =
77{
78#ifdef VBOXSERVICE_CONTROL
79 { &g_Control, NIL_RTTHREAD, false, false, false, true },
80#endif
81#ifdef VBOXSERVICE_TIMESYNC
82 { &g_TimeSync, NIL_RTTHREAD, false, false, false, true },
83#endif
84#ifdef VBOXSERVICE_CLIPBOARD
85 { &g_Clipboard, NIL_RTTHREAD, false, false, false, true },
86#endif
87#ifdef VBOXSERVICE_VMINFO
88 { &g_VMInfo, NIL_RTTHREAD, false, false, false, true },
89#endif
90#ifdef VBOXSERVICE_EXEC
91 { &g_Exec, NIL_RTTHREAD, false, false, false, true },
92#endif
93#ifdef VBOXSERVICE_CPUHOTPLUG /* Disabled by default. Use --enable-cpuhotplug to enable */
94 { &g_CpuHotPlug, NIL_RTTHREAD, false, false, false, false },
95#endif
96#ifdef VBOXSERVICE_MANAGEMENT
97 { &g_MemBalloon, NIL_RTTHREAD, false, false, false, false },
98 { &g_VMStatistics, NIL_RTTHREAD, false, false, false, false },
99#endif
100};
101
102
103/**
104 * Displays the program usage message.
105 *
106 * @returns 1.
107 */
108static int VBoxServiceUsage(void)
109{
110 RTPrintf("usage: %s [-f|--foreground] [-v|--verbose] [-i|--interval <seconds>]\n"
111 " [--disable-<service>] [--enable-<service>] [-h|-?|--help]\n", g_pszProgName);
112#ifdef RT_OS_WINDOWS
113 RTPrintf(" [-r|--register] [-u|--unregister]\n");
114#endif
115 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
116 RTPrintf(" %s\n", g_aServices[j].pDesc->pszUsage);
117 RTPrintf("\n"
118 "Options:\n"
119 " -i | --interval The default interval.\n"
120 " -f | --foreground Don't daemonzie the program. For debugging.\n"
121 " -v | --verbose Increment the verbosity level. For debugging.\n"
122 " -h | -? | --help Show this message and exit with status 1.\n"
123 );
124#ifdef RT_OS_WINDOWS
125 RTPrintf(" -r | --register Installs the service.\n"
126 " -u | --unregister Uninstall service.\n");
127#endif
128
129 RTPrintf("\n"
130 "Service specific options:\n");
131 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
132 {
133 RTPrintf(" --enable-%-10s Enables the %s service. (default)\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
134 RTPrintf(" --disable-%-9s Disables the %s service.\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
135 RTPrintf("%s", g_aServices[j].pDesc->pszOptions);
136 }
137 RTPrintf("\n"
138 " Copyright (C) 2009 Sun Microsystems, Inc.\n");
139
140 return 1;
141}
142
143
144/**
145 * Displays a syntax error message.
146 *
147 * @returns 1
148 * @param pszFormat The message text.
149 * @param ... Format arguments.
150 */
151int VBoxServiceSyntax(const char *pszFormat, ...)
152{
153 RTStrmPrintf(g_pStdErr, "%s: syntax error: ", g_pszProgName);
154
155 va_list va;
156 va_start(va, pszFormat);
157 RTStrmPrintfV(g_pStdErr, pszFormat, va);
158 va_end(va);
159
160 return 1;
161}
162
163
164/**
165 * Displays an error message.
166 *
167 * @returns 1
168 * @param pszFormat The message text.
169 * @param ... Format arguments.
170 */
171int VBoxServiceError(const char *pszFormat, ...)
172{
173 RTStrmPrintf(g_pStdErr, "%s: error: ", g_pszProgName);
174
175 va_list va;
176 va_start(va, pszFormat);
177 RTStrmPrintfV(g_pStdErr, pszFormat, va);
178 va_end(va);
179
180 va_start(va, pszFormat);
181 LogRel(("%s: Error: %N", g_pszProgName, pszFormat, &va));
182 va_end(va);
183
184 return 1;
185}
186
187
188/**
189 * Displays a verbose message.
190 *
191 * @returns 1
192 * @param pszFormat The message text.
193 * @param ... Format arguments.
194 */
195void VBoxServiceVerbose(int iLevel, const char *pszFormat, ...)
196{
197 if (iLevel <= g_cVerbosity)
198 {
199 RTStrmPrintf(g_pStdOut, "%s: ", g_pszProgName);
200 va_list va;
201 va_start(va, pszFormat);
202 RTStrmPrintfV(g_pStdOut, pszFormat, va);
203 va_end(va);
204
205 va_start(va, pszFormat);
206 LogRel(("%s: %N", g_pszProgName, pszFormat, &va));
207 va_end(va);
208 }
209}
210
211
212/**
213 * Gets a 32-bit value argument.
214 *
215 * @returns 0 on success, non-zero exit code on error.
216 * @param argc The argument count.
217 * @param argv The argument vector
218 * @param psz Where in *pi to start looking for the value argument.
219 * @param pi Where to find and perhaps update the argument index.
220 * @param pu32 Where to store the 32-bit value.
221 * @param u32Min The minimum value.
222 * @param u32Max The maximum value.
223 */
224int VBoxServiceArgUInt32(int argc, char **argv, const char *psz, int *pi, uint32_t *pu32, uint32_t u32Min, uint32_t u32Max)
225{
226 if (*psz == ':' || *psz == '=')
227 psz++;
228 if (!*psz)
229 {
230 if (*pi + 1 >= argc)
231 return VBoxServiceSyntax("Missing value for the '%s' argument\n", argv[*pi]);
232 psz = argv[++*pi];
233 }
234
235 char *pszNext;
236 int rc = RTStrToUInt32Ex(psz, &pszNext, 0, pu32);
237 if (RT_FAILURE(rc) || *pszNext)
238 return VBoxServiceSyntax("Failed to convert interval '%s' to a number.\n", psz);
239 if (*pu32 < u32Min || *pu32 > u32Max)
240 return VBoxServiceSyntax("The timesync interval of %RU32 secconds is out of range [%RU32..%RU32].\n",
241 *pu32, u32Min, u32Max);
242 return 0;
243}
244
245
246/**
247 * The service thread.
248 *
249 * @returns Whatever the worker function returns.
250 * @param ThreadSelf My thread handle.
251 * @param pvUser The service index.
252 */
253static DECLCALLBACK(int) VBoxServiceThread(RTTHREAD ThreadSelf, void *pvUser)
254{
255 const unsigned i = (uintptr_t)pvUser;
256 int rc = g_aServices[i].pDesc->pfnWorker(&g_aServices[i].fShutdown);
257 ASMAtomicXchgBool(&g_aServices[i].fShutdown, true);
258 RTThreadUserSignal(ThreadSelf);
259 return rc;
260}
261
262
263unsigned VBoxServiceGetStartedServices(void)
264{
265 unsigned iMain = ~0U;
266 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
267 if (g_aServices[j].fEnabled)
268 {
269 iMain = j;
270 break;
271 }
272
273 return iMain; /* Return the index of the main service (must always come last!). */
274}
275
276/**
277 * Starts the service.
278 *
279 * @returns VBox status code, errors are fully bitched.
280 *
281 * @param iMain The index of the service that belongs to the main
282 * thread. Pass ~0U if none does.
283 */
284int VBoxServiceStartServices(unsigned iMain)
285{
286 int rc;
287
288 /*
289 * Initialize the services.
290 */
291 VBoxServiceVerbose(2, "Initializing services ...\n");
292 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
293 if (g_aServices[j].fEnabled)
294 {
295 rc = g_aServices[j].pDesc->pfnInit();
296 if (RT_FAILURE(rc))
297 {
298 VBoxServiceError("Service '%s' failed to initialize: %Rrc\n",
299 g_aServices[j].pDesc->pszName, rc);
300 return rc;
301 }
302 }
303
304 /*
305 * Start the service(s).
306 */
307 VBoxServiceVerbose(2, "Starting services ...\n");
308 rc = VINF_SUCCESS;
309 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
310 {
311 if ( !g_aServices[j].fEnabled
312 || j == iMain)
313 continue;
314
315 VBoxServiceVerbose(2, "Starting service '%s' ...\n", g_aServices[j].pDesc->pszName);
316 rc = RTThreadCreate(&g_aServices[j].Thread, VBoxServiceThread, (void *)(uintptr_t)j, 0,
317 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, g_aServices[j].pDesc->pszName);
318 if (RT_FAILURE(rc))
319 {
320 VBoxServiceError("RTThreadCreate failed, rc=%Rrc\n", rc);
321 break;
322 }
323 g_aServices[j].fStarted = true;
324
325 /* wait for the thread to initialize */
326 RTThreadUserWait(g_aServices[j].Thread, 60 * 1000);
327 if (g_aServices[j].fShutdown)
328 {
329 VBoxServiceError("Service '%s' failed to start!\n", g_aServices[j].pDesc->pszName);
330 rc = VERR_GENERAL_FAILURE;
331 }
332 }
333 if (RT_SUCCESS(rc))
334 {
335 /* The final service runs in the main thread. */
336 VBoxServiceVerbose(1, "Starting '%s' in the main thread\n", g_aServices[iMain].pDesc->pszName);
337 rc = g_aServices[iMain].pDesc->pfnWorker(&g_fShutdown);
338 if (rc != VINF_SUCCESS) /* Only complain if service returned an error. Otherwise the service is a one-timer. */
339 {
340 VBoxServiceError("Service '%s' stopped unexpected; rc=%Rrc\n", g_aServices[iMain].pDesc->pszName, rc);
341 }
342 }
343 return rc;
344}
345
346
347/**
348 * Stops and terminates the services.
349 *
350 * This should be called even when VBoxServiceStartServices fails so it can
351 * clean up anything that we succeeded in starting.
352 */
353int VBoxServiceStopServices(void)
354{
355 int rc = VINF_SUCCESS;
356
357 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
358 ASMAtomicXchgBool(&g_aServices[j].fShutdown, true);
359 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
360 if (g_aServices[j].fStarted)
361 g_aServices[j].pDesc->pfnStop();
362 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
363 if (g_aServices[j].fEnabled)
364 {
365 if (g_aServices[j].Thread != NIL_RTTHREAD)
366 {
367 int rc;
368 VBoxServiceVerbose(2, "Waiting for service '%s' to stop ...\n", g_aServices[j].pDesc->pszName);
369 for (int i = 0; i < 30; i++) /* Wait 30 seconds in total */
370 {
371 rc = RTThreadWait(g_aServices[j].Thread, 1000 /* Wait 1 second */, NULL);
372 if (RT_SUCCESS(rc))
373 break;
374#ifdef RT_OS_WINDOWS
375 /* Notify SCM that it takes a bit longer ... */
376 VBoxServiceWinSetStatus(SERVICE_STOP_PENDING, i);
377#endif
378 }
379 if (RT_FAILURE(rc))
380 VBoxServiceError("Service '%s' failed to stop. (%Rrc)\n", g_aServices[j].pDesc->pszName, rc);
381 }
382 VBoxServiceVerbose(3, "Terminating service '%s' (%d) ...\n", g_aServices[j].pDesc->pszName, j);
383 g_aServices[j].pDesc->pfnTerm();
384 }
385
386 VBoxServiceVerbose(2, "Stopping services returned: rc=%Rrc\n", rc);
387 return rc;
388}
389
390
391int main(int argc, char **argv)
392{
393 int rc = VINF_SUCCESS;
394 /*
395 * Init globals and such.
396 */
397 RTR3Init();
398
399 /*
400 * Connect to the kernel part before daemonizing so we can fail
401 * and complain if there is some kind of problem. We need to initialize
402 * the guest lib *before* we do the pre-init just in case one of services
403 * needs do to some initial stuff with it.
404 */
405 VBoxServiceVerbose(2, "Calling VbgR3Init()\n");
406 rc = VbglR3Init();
407 if (RT_FAILURE(rc))
408 return VBoxServiceError("VbglR3Init failed with rc=%Rrc.\n", rc);
409
410 /* Do pre-init of services. */
411 g_pszProgName = RTPathFilename(argv[0]);
412 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
413 {
414 rc = g_aServices[j].pDesc->pfnPreInit();
415 if (RT_FAILURE(rc))
416 return VBoxServiceError("Service '%s' failed pre-init: %Rrc\n", g_aServices[j].pDesc->pszName);
417 }
418
419#ifdef RT_OS_WINDOWS
420 /* Make sure only one instance of VBoxService runs at a time. Create a global mutex for that.
421 Do not use a global namespace ("Global\\") for mutex name here, will blow up NT4 compatibility! */
422 HANDLE hMutexAppRunning = CreateMutex (NULL, FALSE, VBOXSERVICE_NAME);
423 if ( hMutexAppRunning != NULL
424 && GetLastError() == ERROR_ALREADY_EXISTS)
425 {
426 VBoxServiceError("%s is already running! Terminating.", g_pszProgName);
427
428 /* Close the mutex for this application instance. */
429 CloseHandle(hMutexAppRunning);
430 hMutexAppRunning = NULL;
431 }
432#endif
433
434 /*
435 * Parse the arguments.
436 */
437 bool fDaemonize = true;
438 bool fDaemonized = false;
439 for (int i = 1; i < argc; i++)
440 {
441 const char *psz = argv[i];
442 if (*psz != '-')
443 return VBoxServiceSyntax("Unknown argument '%s'\n", psz);
444 psz++;
445
446 /* translate long argument to short */
447 if (*psz == '-')
448 {
449 psz++;
450 size_t cch = strlen(psz);
451#define MATCHES(strconst) ( cch == sizeof(strconst) - 1 \
452 && !memcmp(psz, strconst, sizeof(strconst) - 1) )
453 if (MATCHES("foreground"))
454 psz = "f";
455 else if (MATCHES("verbose"))
456 psz = "v";
457 else if (MATCHES("help"))
458 psz = "h";
459 else if (MATCHES("interval"))
460 psz = "i";
461#ifdef RT_OS_WINDOWS
462 else if (MATCHES("register"))
463 psz = "r";
464 else if (MATCHES("unregister"))
465 psz = "u";
466#endif
467 else if (MATCHES("daemonized"))
468 {
469 fDaemonized = true;
470 continue;
471 }
472 else
473 {
474 bool fFound = false;
475
476 if (cch > sizeof("enable-") && !memcmp(psz, "enable-", sizeof("enable-") - 1))
477 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
478 if ((fFound = !RTStrICmp(psz + sizeof("enable-") - 1, g_aServices[j].pDesc->pszName)))
479 g_aServices[j].fEnabled = true;
480
481 if (cch > sizeof("disable-") && !memcmp(psz, "disable-", sizeof("disable-") - 1))
482 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
483 if ((fFound = !RTStrICmp(psz + sizeof("disable-") - 1, g_aServices[j].pDesc->pszName)))
484 g_aServices[j].fEnabled = false;
485
486 if (!fFound)
487 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
488 {
489 rc = g_aServices[j].pDesc->pfnOption(NULL, argc, argv, &i);
490 fFound = rc == 0;
491 if (fFound)
492 break;
493 if (rc != -1)
494 return rc;
495 }
496 if (!fFound)
497 return VBoxServiceSyntax("Unknown option '%s'\n", argv[i]);
498 continue;
499 }
500#undef MATCHES
501 }
502
503 /* handle the string of short options. */
504 do
505 {
506 switch (*psz)
507 {
508 case 'i':
509 rc = VBoxServiceArgUInt32(argc, argv, psz + 1, &i,
510 &g_DefaultInterval, 1, (UINT32_MAX / 1000) - 1);
511 if (rc)
512 return rc;
513 psz = NULL;
514 break;
515
516 case 'f':
517 fDaemonize = false;
518 break;
519
520 case 'v':
521 g_cVerbosity++;
522 break;
523
524 case 'h':
525 case '?':
526 return VBoxServiceUsage();
527
528#ifdef RT_OS_WINDOWS
529 case 'r':
530 return VBoxServiceWinInstall();
531
532 case 'u':
533 return VBoxServiceWinUninstall();
534#endif
535
536 default:
537 {
538 bool fFound = false;
539 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
540 {
541 rc = g_aServices[j].pDesc->pfnOption(&psz, argc, argv, &i);
542 fFound = rc == 0;
543 if (fFound)
544 break;
545 if (rc != -1)
546 return rc;
547 }
548 if (!fFound)
549 return VBoxServiceSyntax("Unknown option '%c' (%s)\n", *psz, argv[i]);
550 break;
551 }
552 }
553 } while (psz && *++psz);
554 }
555 /*
556 * Check that at least one service is enabled.
557 */
558 unsigned iMain = VBoxServiceGetStartedServices();
559 if (iMain == ~0U)
560 return VBoxServiceSyntax("At least one service must be enabled.\n");
561
562 VBoxServiceVerbose(0, "%s r%s started. Verbose level = %d\n",
563 RTBldCfgVersion(), RTBldCfgRevisionStr(), g_cVerbosity);
564
565 /*
566 * Daemonize if requested.
567 */
568 if (fDaemonize && !fDaemonized)
569 {
570#ifdef RT_OS_WINDOWS
571 /** @todo Should do something like VBoxSVC here, OR automatically re-register
572 * the service and start it. Involving VbglR3Daemonize isn't an option
573 * here.
574 *
575 * Also, the idea here, IIRC, was to map the sub service to windows
576 * services. The todo below is for mimicking windows services on
577 * non-windows systems. Not sure if this is doable or not, but in anycase
578 * this code can be moved into -win.
579 *
580 * You should return when StartServiceCtrlDispatcher, btw., not
581 * continue.
582 */
583 VBoxServiceVerbose(2, "Starting service dispatcher ...\n");
584 if (!StartServiceCtrlDispatcher(&g_aServiceTable[0]))
585 return VBoxServiceError("StartServiceCtrlDispatcher: %u. Please start %s with option -f (foreground)!",
586 GetLastError(), g_pszProgName);
587 /* Service now lives in the control dispatcher registered above. */
588#else
589 VBoxServiceVerbose(1, "Daemonizing...\n");
590 rc = VbglR3Daemonize(false /* fNoChDir */, false /* fNoClose */);
591 if (RT_FAILURE(rc))
592 return VBoxServiceError("Daemon failed: %Rrc\n", rc);
593 /* in-child */
594#endif
595 }
596#ifdef RT_OS_WINDOWS
597 else
598 {
599 /* Run the app just like a console one if not daemonized. */
600#endif
601 /** @todo Make the main thread responsive to signal so it can shutdown/restart the threads on non-SIGKILL signals. */
602
603 /*
604 * Start the service, enter the main threads run loop and stop them again when it returns.
605 */
606 rc = VBoxServiceStartServices(iMain);
607 VBoxServiceStopServices();
608#ifdef RT_OS_WINDOWS
609 }
610#endif
611
612#ifdef RT_OS_WINDOWS
613 /*
614 * Release instance mutex if we got it.
615 */
616 if (hMutexAppRunning != NULL)
617 {
618 ::CloseHandle(hMutexAppRunning);
619 hMutexAppRunning = NULL;
620 }
621#endif
622
623 VBoxServiceVerbose(0, "Ended.\n");
624 return RT_SUCCESS(rc) ? 0 : 1;
625}
626
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