~ubuntu-branches/ubuntu/vivid/virtualbox/vivid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
/* $Id: VBoxWatchdog.cpp $ */
/** @file
 * VBoxWatchdog.cpp - VirtualBox Watchdog.
 */

/*
 * Copyright (C) 2011-2012 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */


/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#ifndef VBOX_ONLY_DOCS
# include <VBox/com/com.h>
# include <VBox/com/string.h>
# include <VBox/com/Guid.h>
# include <VBox/com/array.h>
# include <VBox/com/ErrorInfo.h>
# include <VBox/com/errorprint.h>

# include <VBox/com/EventQueue.h>
# include <VBox/com/listeners.h>
# include <VBox/com/VirtualBox.h>
#endif /* !VBOX_ONLY_DOCS */

#include <VBox/err.h>
#include <VBox/log.h>
#include <VBox/version.h>

#include <package-generated.h>

#include <iprt/asm.h>
#include <iprt/buildconfig.h>
#include <iprt/critsect.h>
#include <iprt/getopt.h>
#include <iprt/initterm.h>
#include <iprt/message.h>
#include <iprt/path.h>
#include <iprt/process.h>
#include <iprt/semaphore.h>
#include <iprt/stream.h>
#include <iprt/string.h>
#include <iprt/system.h>
#include <iprt/time.h>


#include <algorithm>
#include <string>
#include <signal.h>

#include "VBoxWatchdogInternal.h"

using namespace com;

/** External globals. */
bool                                g_fDryrun     = false;
bool                                g_fVerbose    = false;
ComPtr<IVirtualBox>                 g_pVirtualBox = NULL;
ComPtr<ISession>                    g_pSession    = NULL;
mapVM                               g_mapVM;
mapGroup                            g_mapGroup;
# ifdef VBOX_WATCHDOG_GLOBAL_PERFCOL
ComPtr<IPerformanceCollector>       g_pPerfCollector = NULL;
# endif

/** The critical section for the machines map. */
static RTCRITSECT    g_csMachines;

/** Set by the signal handler. */
static volatile bool g_fCanceled = false;

/** Logging parameters. */
static uint32_t      g_cHistory = 10;                   /* Enable log rotation, 10 files. */
static uint32_t      g_uHistoryFileTime = RT_SEC_1DAY;  /* Max 1 day per file. */
static uint64_t      g_uHistoryFileSize = 100 * _1M;    /* Max 100MB per file. */

/** Run in background. */
static bool          g_fDaemonize = false;

/**
 * The details of the services that has been compiled in.
 */
static struct
{
    /** Pointer to the service descriptor. */
    PCVBOXMODULE    pDesc;
    /** Whether Pre-init was called. */
    bool            fPreInited;
    /** Whether the module is enabled or not. */
    bool            fEnabled;
} g_aModules[] =
{
    { &g_ModBallooning, false /* Pre-inited */, true /* Enabled */ },
    { &g_ModAPIMonitor, false /* Pre-inited */, true /* Enabled */ }
};

enum GETOPTDEF_WATCHDOG
{
    GETOPTDEF_WATCHDOG_DRYRUN = 1000
};

/**
 * Command line arguments.
 */
static const RTGETOPTDEF g_aOptions[] = {
#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
    { "--background",           'b',                                       RTGETOPT_REQ_NOTHING },
#endif
    /** For displayHelp(). */
    { "--dryrun",               GETOPTDEF_WATCHDOG_DRYRUN,                 RTGETOPT_REQ_NOTHING },
    { "--help",                 'h',                                       RTGETOPT_REQ_NOTHING },
    { "--verbose",              'v',                                       RTGETOPT_REQ_NOTHING },
    { "--pidfile",              'P',                                       RTGETOPT_REQ_STRING },
    { "--logfile",              'F',                                       RTGETOPT_REQ_STRING },
    { "--logrotate",            'R',                                       RTGETOPT_REQ_UINT32 },
    { "--logsize",              'S',                                       RTGETOPT_REQ_UINT64 },
    { "--loginterval",          'I',                                       RTGETOPT_REQ_UINT32 }
};

/** Global static objects. */
static ComPtr<IVirtualBoxClient> g_pVirtualBoxClient = NULL;
static ComPtr<IEventSource>      g_pEventSource = NULL;
static ComPtr<IEventSource>      g_pEventSourceClient = NULL;
static ComPtr<IEventListener>    g_pVBoxEventListener = NULL;
static EventQueue               *g_pEventQ = NULL;

/* Prototypes. */
static int machineAdd(const Bstr &strUuid);
static int machineRemove(const Bstr &strUuid);
static int watchdogSetup();
static void watchdogShutdown();

#ifdef RT_OS_WINDOWS
/* Required for ATL. */
static CComModule _Module;
#endif

/**
 *  Handler for global events.
 */
class VirtualBoxEventListener
{
    public:
        VirtualBoxEventListener()
        {
        }

        virtual ~VirtualBoxEventListener()
        {
        }

        HRESULT init()
        {
            return S_OK;
        }

        void uninit()
        {
        }

        STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
        {
            switch (aType)
            {
                case VBoxEventType_OnMachineRegistered:
                {
                    ComPtr<IMachineRegisteredEvent> pEvent = aEvent;
                    Assert(pEvent);

                    Bstr uuid;
                    BOOL fRegistered;
                    HRESULT hr = pEvent->COMGETTER(Registered)(&fRegistered);
                    if (SUCCEEDED(hr))
                        hr = pEvent->COMGETTER(MachineId)(uuid.asOutParam());

                    if (SUCCEEDED(hr))
                    {
                        int rc = RTCritSectEnter(&g_csMachines);
                        if (RT_SUCCESS(rc))
                        {
                            rc = fRegistered
                               ? machineAdd(uuid)
                               : machineRemove(uuid);
                            int rc2 = RTCritSectLeave(&g_csMachines);
                            if (RT_SUCCESS(rc))
                                rc = rc2;
                            AssertRC(rc);
                        }
                    }
                    break;
                }

                case VBoxEventType_OnMachineStateChanged:
                {
                    ComPtr<IMachineStateChangedEvent> pEvent = aEvent;
                    Assert(pEvent);

                    MachineState_T machineState;
                    Bstr uuid;

                    HRESULT hr = pEvent->COMGETTER(State)(&machineState);
                    if (SUCCEEDED(hr))
                        hr = pEvent->COMGETTER(MachineId)(uuid.asOutParam());

                    if (SUCCEEDED(hr))
                    {
                        int rc = RTCritSectEnter(&g_csMachines);
                        if (RT_SUCCESS(rc))
                        {
                            for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
                                if (g_aModules[j].fEnabled)
                                {
                                    int rc2 = g_aModules[j].pDesc->pfnOnMachineStateChanged(uuid,
                                                                                            machineState);
                                    if (RT_FAILURE(rc2))
                                        serviceLog("Module '%s' reported an error: %Rrc\n",
                                                   g_aModules[j].pDesc->pszName, rc);
                                    /* Keep going. */
                                }

                            int rc2 = RTCritSectLeave(&g_csMachines);
                            if (RT_SUCCESS(rc))
                                rc = rc2;
                            AssertRC(rc);
                        }
                    }
                    break;
                }

                case VBoxEventType_OnVBoxSVCAvailabilityChanged:
                {
                    ComPtr<IVBoxSVCAvailabilityChangedEvent> pVSACEv = aEvent;
                    Assert(pVSACEv);
                    BOOL fAvailable = FALSE;
                    pVSACEv->COMGETTER(Available)(&fAvailable);

                    /* First, notify all modules. */
                    for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
                        if (g_aModules[j].fEnabled)
                        {
                            int rc2 = g_aModules[j].pDesc->pfnOnServiceStateChanged(RT_BOOL(fAvailable));
                            if (RT_FAILURE(rc2))
                                serviceLog("Module '%s' reported an error: %Rrc\n",
                                           g_aModules[j].pDesc->pszName, rc2);
                            /* Keep going. */
                        }

                    /* Do global teardown/re-creation stuff. */
                    if (!fAvailable)
                    {
                        serviceLog("VBoxSVC became unavailable\n");
                        watchdogShutdown();
                    }
                    else
                    {
                        serviceLog("VBoxSVC became available\n");
                        int rc2 = watchdogSetup();
                        if (RT_FAILURE(rc2))
                            serviceLog("Unable to re-set up watchdog (rc=%Rrc)!\n", rc2);
                    }

                    break;
                }

                default:
                    /* Not handled event, just skip it. */
                    break;
            }

            return S_OK;
        }

    private:
};
typedef ListenerImpl<VirtualBoxEventListener> VirtualBoxEventListenerImpl;
VBOX_LISTENER_DECLARE(VirtualBoxEventListenerImpl)

/**
 * Signal handler that sets g_fGuestCtrlCanceled.
 *
 * This can be executed on any thread in the process, on Windows it may even be
 * a thread dedicated to delivering this signal.  Do not doing anything
 * unnecessary here.
 */
static void signalHandler(int iSignal)
{
    NOREF(iSignal);
    ASMAtomicWriteBool(&g_fCanceled, true);

    if (!g_pEventQ)
    {
        int rc = g_pEventQ->interruptEventQueueProcessing();
        if (RT_FAILURE(rc))
            serviceLog("Error: interruptEventQueueProcessing failed with rc=%Rrc\n", rc);
    }
}

/**
 * Installs a custom signal handler to get notified
 * whenever the user wants to intercept the program.
 */
static void signalHandlerInstall()
{
    signal(SIGINT,   signalHandler);
#ifdef SIGBREAK
    signal(SIGBREAK, signalHandler);
#endif
}

/**
 * Uninstalls a previously installed signal handler.
 */
static void signalHandlerUninstall()
{
    signal(SIGINT,   SIG_DFL);
#ifdef SIGBREAK
    signal(SIGBREAK, SIG_DFL);
#endif
}

/**
 * Adds a specified machine to the list (map) of handled machines.
 * Does not do locking -- needs to be done by caller!
 *
 * @return  IPRT status code.
 * @param   strUuid                 UUID of the specified machine.
 */
static int machineAdd(const Bstr &strUuid)
{
    HRESULT rc;

    /** @todo Add exception handling! */

    do
    {
        ComPtr <IMachine> machine;
        CHECK_ERROR_BREAK(g_pVirtualBox, FindMachine(strUuid.raw(), machine.asOutParam()));
        Assert(!machine.isNull());

        /*
         * Get groups for this machine.
        */
        com::SafeArray<BSTR> groups;
        CHECK_ERROR_BREAK(machine, COMGETTER(Groups)(ComSafeArrayAsOutParam(groups)));
        Utf8Str strGroups;
        for (size_t i = 0; i < groups.size(); i++)
        {
            if (i != 0)
                strGroups.append(",");
            strGroups.append(Utf8Str(groups[i]));
        }

        /*
         * Add machine to map.
         */
        VBOXWATCHDOG_MACHINE m;
        m.machine = machine;
        int rc2 = groupAdd(m.groups, strGroups.c_str(), 0 /* Flags */);
        AssertRC(rc2);

        mapVMIter it = g_mapVM.find(strUuid);
        Assert(it == g_mapVM.end());
        g_mapVM.insert(std::make_pair(strUuid, m));
        serviceLogVerbose(("Added machine \"%ls\"\n", strUuid.raw()));

        /*
         * Get the machine's VM group(s).
         */
        mapGroupsIterConst itGroup = m.groups.begin();
        while (itGroup != m.groups.end())
        {
            serviceLogVerbose(("Machine \"%ls\" is in VM group \"%s\"\n",
                               strUuid.raw(), itGroup->first.c_str()));

            /* Add machine to group(s). */
            mapGroupIter itGroups = g_mapGroup.find(itGroup->first);
            if (itGroups == g_mapGroup.end())
            {
                vecGroupMembers vecMembers;
                vecMembers.push_back(strUuid);
                g_mapGroup.insert(std::make_pair(itGroup->first, vecMembers));

                itGroups = g_mapGroup.find(itGroup->first);
                Assert(itGroups != g_mapGroup.end());
            }
            else
                itGroups->second.push_back(strUuid);
            serviceLogVerbose(("Group \"%s\" has now %ld machine(s)\n",
                               itGroup->first.c_str(), itGroups->second.size()));
            itGroup++;
        }

        /*
         * Let all modules know. Typically all modules would register
         * their per-machine payload here.
         */
        for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
            if (g_aModules[j].fEnabled)
            {
                rc2 = g_aModules[j].pDesc->pfnOnMachineRegistered(strUuid);
                if (RT_FAILURE(rc2))
                    serviceLog("OnMachineRegistered: Module '%s' reported an error: %Rrc\n",
                               g_aModules[j].pDesc->pszName, rc);
                /* Keep going. */
            }

    } while (0);

    /** @todo Add std exception handling! */

    return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_COM_IPRT_ERROR; /* @todo Find a better error! */
}

static int machineDestroy(const Bstr &strUuid)
{
    AssertReturn(!strUuid.isEmpty(), VERR_INVALID_PARAMETER);
    int rc = VINF_SUCCESS;

    /* Let all modules know. */
    for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
        if (g_aModules[j].fEnabled)
        {
            int rc2 = g_aModules[j].pDesc->pfnOnMachineUnregistered(strUuid);
            if (RT_FAILURE(rc2))
                serviceLog("OnMachineUnregistered: Module '%s' reported an error: %Rrc\n",
                           g_aModules[j].pDesc->pszName, rc);
            /* Keep going. */
        }

    /* Must log before erasing the iterator because of the UUID ref! */
    serviceLogVerbose(("Removing machine \"%ls\"\n", strUuid.raw()));

    try
    {
        mapVMIter itVM = g_mapVM.find(strUuid);
        Assert(itVM != g_mapVM.end());

        /* Remove machine from group(s). */
        mapGroupsIterConst itGroups = itVM->second.groups.begin();
        while (itGroups != itVM->second.groups.end())
        {
            mapGroupIter itGroup = g_mapGroup.find(itGroups->first);
            Assert(itGroup != g_mapGroup.end());

            vecGroupMembers vecMembers = itGroup->second;
            vecGroupMembersIter itMember = std::find(vecMembers.begin(),
                                                     vecMembers.end(),
                                                     strUuid);
            Assert(itMember != vecMembers.end());
            vecMembers.erase(itMember);

            serviceLogVerbose(("Group \"%s\" has %ld machines left\n",
                               itGroup->first.c_str(), vecMembers.size()));
            if (!vecMembers.size())
            {
                serviceLogVerbose(("Deleting group \"%s\"\n", itGroup->first.c_str()));
                g_mapGroup.erase(itGroup);
            }

            itGroups++;
        }

#ifndef VBOX_WATCHDOG_GLOBAL_PERFCOL
        itVM->second.collector.setNull();
#endif
        itVM->second.machine.setNull();

        /*
         * Remove machine from map.
         */
        g_mapVM.erase(itVM);
    }
    catch (...)
    {
        AssertFailed();
    }

    return rc;
}

/**
 * Removes a specified machine from the list of handled machines.
 * Does not do locking -- needs to be done by caller!
 *
 * @return  IPRT status code.
 * @param   strUuid                 UUID of the specified machine.
 */
static int machineRemove(const Bstr &strUuid)
{
    AssertReturn(!strUuid.isEmpty(), VERR_INVALID_PARAMETER);
    int rc = VINF_SUCCESS;

    mapVMIter it = g_mapVM.find(strUuid);
    if (it != g_mapVM.end())
    {
        int rc2 = machineDestroy(strUuid);
        if (RT_FAILURE(rc))
        {
            serviceLog(("Machine \"%ls\" failed to destroy, rc=%Rc\n"));
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        serviceLogVerbose(("Warning: Removing not added machine \"%ls\"\n", strUuid.raw()));
        rc = VERR_NOT_FOUND;
    }

    return rc;
}

static void vmListDestroy()
{
    serviceLogVerbose(("Destroying VM list ...\n"));

    int rc = RTCritSectEnter(&g_csMachines);
    if (RT_SUCCESS(rc))
    {
        mapVMIter it = g_mapVM.begin();
        while (it != g_mapVM.end())
        {
            machineDestroy(it->first);
            it = g_mapVM.begin();
        }

        g_mapVM.clear();

        rc = RTCritSectLeave(&g_csMachines);
    }
    AssertRC(rc);
}

static int vmListBuild()
{
    serviceLogVerbose(("Building VM list ...\n"));

    int rc = RTCritSectEnter(&g_csMachines);
    if (RT_SUCCESS(rc))
    {
        /*
         * Make sure the list is empty.
         */
        g_mapVM.clear();

        /*
         * Get the list of all _running_ VMs
         */
        com::SafeIfaceArray<IMachine> machines;
        HRESULT hrc = g_pVirtualBox->COMGETTER(Machines)(ComSafeArrayAsOutParam(machines));
        if (SUCCEEDED(hrc))
        {
            /*
             * Iterate through the collection
             */
            for (size_t i = 0; i < machines.size(); ++i)
            {
                if (machines[i])
                {
                    Bstr strUUID;
                    CHECK_ERROR_BREAK(machines[i], COMGETTER(Id)(strUUID.asOutParam()));

                    BOOL fAccessible;
                    CHECK_ERROR_BREAK(machines[i], COMGETTER(Accessible)(&fAccessible));
                    if (!fAccessible)
                    {
                        serviceLogVerbose(("Machine \"%ls\" is inaccessible, skipping\n",
                                           strUUID.raw()));
                        continue;
                    }

                    rc = machineAdd(strUUID);
                    if (RT_FAILURE(rc))
                        break;
                }
            }

            if (!machines.size())
                serviceLogVerbose(("No machines to add found at the moment!\n"));
        }

        int rc2 = RTCritSectLeave(&g_csMachines);
        if (RT_SUCCESS(rc))
            rc = rc2;
    }
    return rc;
}

/**
 * Lazily calls the pfnPreInit method on each service.
 *
 * @returns VBox status code, error message displayed.
 */
static int watchdogLazyPreInit(void)
{
    for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
        if (!g_aModules[j].fPreInited)
        {
            int rc = g_aModules[j].pDesc->pfnPreInit();
            if (RT_FAILURE(rc))
            {
                serviceLog("Module '%s' failed pre-init: %Rrc\n",
                           g_aModules[j].pDesc->pszName, rc);
                return rc;
            }
            g_aModules[j].fPreInited = true;
        }
    return VINF_SUCCESS;
}

/**
 * Starts all registered modules.
 *
 * @return  IPRT status code.
 * @return  int
 */
static int watchdogStartModules()
{
    int rc = VINF_SUCCESS;

    for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
        if (g_aModules[j].fEnabled)
        {
            rc = g_aModules[j].pDesc->pfnInit();
            if (RT_FAILURE(rc))
            {
                if (rc != VERR_SERVICE_DISABLED)
                {
                    serviceLog("Module '%s' failed to initialize: %Rrc\n",
                               g_aModules[j].pDesc->pszName, rc);
                    return rc;
                }
                g_aModules[j].fEnabled = false;
                serviceLog(0, "Module '%s' was disabled because of missing functionality\n",
                           g_aModules[j].pDesc->pszName);

            }
        }

    return rc;
}

static int watchdogShutdownModules()
{
    int rc = VINF_SUCCESS;

    for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
        if (g_aModules[j].fEnabled)
        {
            int rc2 = g_aModules[j].pDesc->pfnStop();
            if (RT_FAILURE(rc2))
            {
                serviceLog("Module '%s' failed to stop: %Rrc\n",
                           g_aModules[j].pDesc->pszName, rc);
                /* Keep original rc. */
                if (RT_SUCCESS(rc))
                    rc = rc2;
            }
            /* Keep going. */
        }

    for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
        if (g_aModules[j].fEnabled)
        {
            g_aModules[j].pDesc->pfnTerm();
        }

    return rc;
}

static RTEXITCODE watchdogMain(HandlerArg *a)
{
    HRESULT rc = S_OK;

    do
    {
        /* Initialize global weak references. */
        g_pEventQ = com::EventQueue::getMainEventQueue();

        /*
         * Install signal handlers.
         */
        signal(SIGINT,   signalHandler);
    #ifdef SIGBREAK
        signal(SIGBREAK, signalHandler);
    #endif

        /*
         * Setup the global event listeners:
         * - g_pEventSource for machine events
         * - g_pEventSourceClient for VBoxClient events (like VBoxSVC handling)
         */
        CHECK_ERROR_BREAK(g_pVirtualBox, COMGETTER(EventSource)(g_pEventSource.asOutParam()));
        CHECK_ERROR_BREAK(g_pVirtualBoxClient, COMGETTER(EventSource)(g_pEventSourceClient.asOutParam()));

        ComObjPtr<VirtualBoxEventListenerImpl> vboxListenerImpl;
        vboxListenerImpl.createObject();
        vboxListenerImpl->init(new VirtualBoxEventListener());

        com::SafeArray<VBoxEventType_T> eventTypes;
        eventTypes.push_back(VBoxEventType_OnMachineRegistered);
        eventTypes.push_back(VBoxEventType_OnMachineStateChanged);
        eventTypes.push_back(VBoxEventType_OnVBoxSVCAvailabilityChanged); /* Processed by g_pEventSourceClient. */

        g_pVBoxEventListener = vboxListenerImpl;
        CHECK_ERROR_BREAK(g_pEventSource, RegisterListener(g_pVBoxEventListener, ComSafeArrayAsInParam(eventTypes), true /* Active listener */));
        CHECK_ERROR_BREAK(g_pEventSourceClient, RegisterListener(g_pVBoxEventListener, ComSafeArrayAsInParam(eventTypes), true /* Active listener */));

        /*
         * Set up modules.
         */
        int vrc = watchdogStartModules();
        if (RT_FAILURE(vrc))
            break;

        for (;;)
        {
            /*
             * Do the actual work.
             */

            vrc = RTCritSectEnter(&g_csMachines);
            if (RT_SUCCESS(vrc))
            {
                for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
                    if (g_aModules[j].fEnabled)
                    {
                        int rc2 = g_aModules[j].pDesc->pfnMain();
                        if (RT_FAILURE(rc2))
                            serviceLog("Module '%s' reported an error: %Rrc\n",
                                       g_aModules[j].pDesc->pszName, rc2);
                        /* Keep going. */
                    }

                int rc2 = RTCritSectLeave(&g_csMachines);
                if (RT_SUCCESS(vrc))
                    vrc = rc2;
                AssertRC(vrc);
            }

            /*
             * Process pending events, then wait for new ones. Note, this
             * processes NULL events signalling event loop termination.
             */
            g_pEventQ->processEventQueue(500 / 10);

            if (g_fCanceled)
            {
                serviceLog("Signal caught, exiting ...\n");
                break;
            }
        }

        signal(SIGINT,   SIG_DFL);
    #ifdef SIGBREAK
        signal(SIGBREAK, SIG_DFL);
    #endif

        /* VirtualBox callback unregistration. */
        if (g_pVBoxEventListener)
        {
            if (!g_pEventSource.isNull())
                CHECK_ERROR(g_pEventSource, UnregisterListener(g_pVBoxEventListener));
            g_pVBoxEventListener.setNull();
        }

        g_pEventSource.setNull();
        g_pEventSourceClient.setNull();

        vrc = watchdogShutdownModules();
        AssertRC(vrc);

        if (RT_FAILURE(vrc))
            rc = VBOX_E_IPRT_ERROR;

    } while (0);

    return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}

void serviceLog(const char *pszFormat, ...)
{
    va_list args;
    va_start(args, pszFormat);
    char *psz = NULL;
    RTStrAPrintfV(&psz, pszFormat, args);
    va_end(args);

    LogRel(("%s", psz));

    RTStrFree(psz);
}

static void displayHeader()
{
    RTStrmPrintf(g_pStdErr, VBOX_PRODUCT " Watchdog " VBOX_VERSION_STRING "\n"
                 "(C) " VBOX_C_YEAR " " VBOX_VENDOR "\n"
                 "All rights reserved.\n\n");
}

/**
 * Displays the help.
 *
 * @param   pszImage                Name of program name (image).
 */
static void displayHelp(const char *pszImage)
{
    AssertPtrReturnVoid(pszImage);

    displayHeader();

    RTStrmPrintf(g_pStdErr,
                 "Usage:\n"
                 " %s [-v|--verbose] [-h|-?|--help] [-P|--pidfile]\n"
                 " [-F|--logfile=<file>] [-R|--logrotate=<num>] [-S|--logsize=<bytes>]\n"
                 " [-I|--loginterval=<seconds>]\n", pszImage);
    for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
        if (g_aModules[j].pDesc->pszUsage)
            RTStrmPrintf(g_pStdErr, "%s", g_aModules[j].pDesc->pszUsage);

    RTStrmPrintf(g_pStdErr, "\n"
                 "Options:\n");

    for (unsigned i = 0;
         i < RT_ELEMENTS(g_aOptions);
         ++i)
    {
        std::string str(g_aOptions[i].pszLong);
        if (g_aOptions[i].iShort < 1000) /* Don't show short options which are defined by an ID! */
        {
            str += ", -";
            str += g_aOptions[i].iShort;
        }
        str += ":";

        const char *pcszDescr = "";

        switch (g_aOptions[i].iShort)
        {
            case GETOPTDEF_WATCHDOG_DRYRUN:
                pcszDescr = "Dryrun mode -- do not perform any actions.";
                break;

            case 'h':
                pcszDescr = "Print this help message and exit.";
                break;

#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
            case 'b':
                pcszDescr = "Run in background (daemon mode).";
                break;
#endif
            case 'P':
                pcszDescr = "Name of the PID file which is created when the daemon was started.";
                break;

            case 'F':
                pcszDescr = "Name of file to write log to (no file).";
                break;

            case 'R':
                pcszDescr = "Number of log files (0 disables log rotation).";
                break;

            case 'S':
                pcszDescr = "Maximum size of a log file to trigger rotation (bytes).";
                break;

            case 'I':
                pcszDescr = "Maximum time interval to trigger log rotation (seconds).";
                break;
        }

        RTStrmPrintf(g_pStdErr, "%-23s%s\n", str.c_str(), pcszDescr);
    }

    for (unsigned j = 0; j < RT_ELEMENTS(g_aModules); j++)
    {
        if (g_aModules[j].pDesc->pszOptions)
            RTPrintf("%s", g_aModules[j].pDesc->pszOptions);
    }

    /** @todo Change VBOXBALLOONCTRL_RELEASE_LOG to WATCHDOG*. */
    RTStrmPrintf(g_pStdErr, "\nUse environment variable VBOXBALLOONCTRL_RELEASE_LOG for logging options.\n");
}

/**
 * Creates all global COM objects.
 *
 * @return  HRESULT
 */
static int watchdogSetup()
{
    serviceLogVerbose(("Setting up ...\n"));

    /*
     * Setup VirtualBox + session interfaces.
     */
    HRESULT rc = g_pVirtualBoxClient->COMGETTER(VirtualBox)(g_pVirtualBox.asOutParam());
    if (SUCCEEDED(rc))
    {
        rc = g_pSession.createInprocObject(CLSID_Session);
        if (FAILED(rc))
            RTMsgError("Failed to create a session object (rc=%Rhrc)!", rc);
    }
    else
        RTMsgError("Failed to get VirtualBox object (rc=%Rhrc)!", rc);

    if (FAILED(rc))
        return VERR_COM_OBJECT_NOT_FOUND;

    /*
     * Setup metrics.
     */
#ifdef VBOX_WATCHDOG_GLOBAL_PERFCOL
    CHECK_ERROR_RET(g_pVirtualBox,
                    COMGETTER(PerformanceCollector)(g_pPerfCollector.asOutParam()), VERR_COM_UNEXPECTED);
#endif

    int vrc = RTCritSectInit(&g_csMachines);
    if (RT_SUCCESS(vrc))
    {

        /*
         * Build up initial VM list.
         */
        vrc = vmListBuild();
    }

    return vrc;
}

static void watchdogShutdown()
{
    serviceLogVerbose(("Shutting down ...\n"));

    vmListDestroy();

    int rc = RTCritSectDelete(&g_csMachines);
    AssertRC(rc);

#ifdef VBOX_WATCHDOG_GLOBAL_PERFCOL
    g_pPerfCollector.setNull();
#endif

    g_pSession.setNull();
    g_pVirtualBox.setNull();
}

int main(int argc, char *argv[])
{
    /*
     * Before we do anything, init the runtime without loading
     * the support driver.
     */
    int rc = RTR3InitExe(argc, &argv, 0);
    if (RT_FAILURE(rc))
        return RTMsgInitFailure(rc);

    /*
     * Parse the global options
    */
    int c;
    const char *pszLogFile = NULL;
    const char *pszPidFile = NULL;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, argc, argv,
                 g_aOptions, RT_ELEMENTS(g_aOptions), 1 /* First */, 0 /*fFlags*/);
    while ((c = RTGetOpt(&GetState, &ValueUnion)))
    {
        switch (c)
        {
            case GETOPTDEF_WATCHDOG_DRYRUN:
                g_fDryrun = true;
                break;

            case 'h':
                displayHelp(argv[0]);
                return 0;

            case 'v':
                g_fVerbose = true;
                break;

#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
            case 'b':
                g_fDaemonize = true;
                break;
#endif
            case 'V':
                RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
                return 0;

            case 'P':
                pszPidFile = ValueUnion.psz;
                break;

            case 'F':
                pszLogFile = ValueUnion.psz;
                break;

            case 'R':
                g_cHistory = ValueUnion.u32;
                break;

            case 'S':
                g_uHistoryFileSize = ValueUnion.u64;
                break;

            case 'I':
                g_uHistoryFileTime = ValueUnion.u32;
                break;

            default:
            {
                bool fFound = false;

                /** @todo Add "--disable-<module>" etc. here! */

                if (!fFound)
                {
                    rc = watchdogLazyPreInit();
                    if (RT_FAILURE(rc))
                        return RTEXITCODE_FAILURE;

                    for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aModules); j++)
                    {
                        int iArgCnt = argc - GetState.iNext + 1;
                        int iArgIndex = GetState.iNext - 1;
                        int iConsumed = 0;
                        rc = g_aModules[j].pDesc->pfnOption(iArgCnt,
                                                            &argv[iArgIndex],
                                                            &iConsumed);
                        fFound = rc == 0;
                        if (fFound)
                        {
                            GetState.iNext += iConsumed;
                            break;
                        }
                        if (rc != -1)
                            return rc;
                    }
                }
                if (!fFound)
                    return RTGetOptPrintError(c, &ValueUnion);
                continue;
            }
        }
    }

    /** @todo Add "--quiet/-q" option to not show the header. */
    displayHeader();

    /* create release logger, to stdout */
    char szError[RTPATH_MAX + 128];
    rc = com::VBoxLogRelCreate("Watchdog", g_fDaemonize ? NULL : pszLogFile,
                               RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
                               "all", "VBOXBALLOONCTRL_RELEASE_LOG",
                               RTLOGDEST_STDOUT, UINT32_MAX /* cMaxEntriesPerGroup */,
                               g_cHistory, g_uHistoryFileTime, g_uHistoryFileSize,
                               szError, sizeof(szError));
    if (RT_FAILURE(rc))
        return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, rc);

#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
    if (g_fDaemonize)
    {
        /* prepare release logging */
        char szLogFile[RTPATH_MAX];

        if (!pszLogFile || !*pszLogFile)
        {
            rc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
            if (RT_FAILURE(rc))
                 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not get base directory for logging: %Rrc", rc);
            rc = RTPathAppend(szLogFile, sizeof(szLogFile), "vboxballoonctrl.log");
            if (RT_FAILURE(rc))
                 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not construct logging path: %Rrc", rc);
            pszLogFile = szLogFile;
        }

        rc = RTProcDaemonizeUsingFork(false /* fNoChDir */, false /* fNoClose */, pszPidFile);
        if (RT_FAILURE(rc))
            return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to daemonize, rc=%Rrc. exiting.", rc);
        /* create release logger, to file */
        rc = com::VBoxLogRelCreate("Watchdog", pszLogFile,
                                   RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
                                   "all", "VBOXBALLOONCTRL_RELEASE_LOG",
                                   RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
                                   g_cHistory, g_uHistoryFileTime, g_uHistoryFileSize,
                                   szError, sizeof(szError));
        if (RT_FAILURE(rc))
            return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, rc);
    }
#endif

#ifndef VBOX_ONLY_DOCS
    /*
     * Initialize COM.
     */
    using namespace com;
    HRESULT hrc = com::Initialize();
# ifdef VBOX_WITH_XPCOM
    if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
    {
        char szHome[RTPATH_MAX] = "";
        com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
        return RTMsgErrorExit(RTEXITCODE_FAILURE,
               "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
    }
# endif
    if (FAILED(hrc))
        return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM (%Rhrc)!", hrc);

    hrc = g_pVirtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
    if (FAILED(hrc))
    {
        RTMsgError("Failed to create the VirtualBoxClient object (%Rhrc)!", hrc);
        com::ErrorInfo info;
        if (!info.isFullAvailable() && !info.isBasicAvailable())
        {
            com::GluePrintRCMessage(hrc);
            RTMsgError("Most likely, the VirtualBox COM server is not running or failed to start.");
        }
        else
            com::GluePrintErrorInfo(info);
        return RTEXITCODE_FAILURE;
    }

    if (g_fDryrun)
        serviceLog("Running in dryrun mode\n");

    rc = watchdogSetup();
    if (RT_FAILURE(rc))
        return RTEXITCODE_FAILURE;

    HandlerArg handlerArg = { argc, argv };
    RTEXITCODE rcExit = watchdogMain(&handlerArg);

    EventQueue::getMainEventQueue()->processEventQueue(0);

    watchdogShutdown();

    g_pVirtualBoxClient.setNull();

    com::Shutdown();

    return rcExit;
#else  /* VBOX_ONLY_DOCS */
    return RTEXITCODE_SUCCESS;
#endif /* VBOX_ONLY_DOCS */
}