summaryrefslogtreecommitdiff
path: root/java/src/IceBox/ServiceManagerI.java
blob: 9d7b830bbb61ef5eb10bf676876d82fb5ed1eb03 (plain)
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
// **********************************************************************
//
// Copyright (c) 2003-2012 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

package IceBox;

//
// NOTE: the class isn't final on purpose to allow users to eventually
// extend it.
//
public class ServiceManagerI extends _ServiceManagerDisp
{
    public
    ServiceManagerI(Ice.Communicator communicator, String[] args)
    {
        _communicator = communicator;
        _logger = _communicator.getLogger();
        _argv = args;
        _traceServiceObserver = _communicator.getProperties().getPropertyAsInt("IceBox.Trace.ServiceObserver");
        _observerCompletedCB = new Ice.Callback()
            {
                public void completed(Ice.AsyncResult result)
                {
                    try
                    {
                        result.throwLocalException();
                    }
                    catch(Ice.LocalException ex)
                    {
                        ServiceObserverPrx observer = ServiceObserverPrxHelper.uncheckedCast(result.getProxy());
                        synchronized(ServiceManagerI.this)
                        {
                            if(_observers.remove(observer))
                            {
                                observerRemoved(observer, ex);
                            }
                        }
                    }
                }
            };
    }

    public java.util.Map<String, String>
    getSliceChecksums(Ice.Current current)
    {
        return SliceChecksums.checksums;
    }

    public void
    startService(String name, Ice.Current current)
        throws AlreadyStartedException, NoSuchServiceException
    {
        ServiceInfo info = null;
        synchronized(this)
        {
            //
            // Search would be more efficient if services were contained in
            // a map, but order is required for shutdown.
            //
            for(ServiceInfo p : _services)
            {
                if(p.name.equals(name))
                {
                    if(p.status == StatusStarted)
                    {
                        throw new AlreadyStartedException();
                    }
                    p.status = StatusStarting;
                    info = (ServiceInfo)p.clone();
                    break;
                }
            }
            if(info == null)
            {
                throw new NoSuchServiceException();
            }
            _pendingStatusChanges = true;
        }

        boolean started = false;
        try
        {
            info.service.start(name, info.communicator == null ? _sharedCommunicator : info.communicator, info.args);
            started = true;
        }
        catch(java.lang.Exception e)
        {
            java.io.StringWriter sw = new java.io.StringWriter();
            java.io.PrintWriter pw = new java.io.PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            _logger.warning("ServiceManager: exception while starting service " + info.name + ":\n" + sw.toString());
        }

        synchronized(this)
        {
            for(ServiceInfo p : _services)
            {
                if(p.name.equals(name))
                {
                    if(started)
                    {
                        p.status = StatusStarted;

                        java.util.List<String> services = new java.util.ArrayList<String>();
                        services.add(name);
                        servicesStarted(services, _observers);
                    }
                    else
                    {
                        p.status = StatusStopped;
                    }
                    break;
                }
            }
            _pendingStatusChanges = false;
            notifyAll();
        }
    }

    public void
    stopService(String name, Ice.Current current)
        throws AlreadyStoppedException, NoSuchServiceException
    {
        ServiceInfo info = null;
        synchronized(this)
        {
            //
            // Search would be more efficient if services were contained in
            // a map, but order is required for shutdown.
            //
            for(ServiceInfo p : _services)
            {
                if(p.name.equals(name))
                {
                    if(p.status == StatusStopped)
                    {
                        throw new AlreadyStoppedException();
                    }
                    p.status = StatusStopping;
                    info = (ServiceInfo)p.clone();
                    break;
                }
            }
            if(info == null)
            {
                throw new NoSuchServiceException();
            }
            _pendingStatusChanges = true;
        }

        boolean stopped = false;
        try
        {
            info.service.stop();
            stopped = true;
        }
        catch(java.lang.Exception e)
        {
            java.io.StringWriter sw = new java.io.StringWriter();
            java.io.PrintWriter pw = new java.io.PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            _logger.warning("ServiceManager: exception while stopping service " + info.name + ":\n" + sw.toString());
        }

        synchronized(this)
        {
            for(ServiceInfo p : _services)
            {
                if(p.name.equals(name))
                {
                    if(stopped)
                    {
                        p.status = StatusStopped;

                        java.util.List<String> services = new java.util.ArrayList<String>();
                        services.add(name);
                        servicesStopped(services, _observers);
                    }
                    else
                    {
                        p.status = StatusStarted;
                    }
                    break;
                }
            }
            _pendingStatusChanges = false;
            notifyAll();
        }
    }

    public void
    addObserver(final ServiceObserverPrx observer, Ice.Current current)
    {
        java.util.List<String> activeServices = new java.util.LinkedList<String>();

        //
        // Null observers and duplicate registrations are ignored
        //

        synchronized(this)
        {
            if(observer != null && _observers.add(observer))
            {
                if(_traceServiceObserver >= 1)
                {
                    _logger.trace("IceBox.ServiceObserver",
                                  "Added service observer " + _communicator.proxyToString(observer));
                }

                for(ServiceInfo info: _services)
                {
                    if(info.status == StatusStarted)
                    {
                        activeServices.add(info.name);
                    }
                }
            }
        }

        if(activeServices.size() > 0)
        {
            observer.begin_servicesStarted(activeServices.toArray(new String[0]), _observerCompletedCB);
        }
    }

    public void
    shutdown(Ice.Current current)
    {
        _communicator.shutdown();
    }

    public int
    run()
    {
        try
        {
            Ice.Properties properties = _communicator.getProperties();

            //
            // Create an object adapter. Services probably should NOT share
            // this object adapter, as the endpoint(s) for this object adapter
            // will most likely need to be firewalled for security reasons.
            //
            Ice.ObjectAdapter adapter = null;
            if(properties.getProperty("IceBox.ServiceManager.Endpoints").length() != 0)
            {
                adapter = _communicator.createObjectAdapter("IceBox.ServiceManager");

                Ice.Identity identity = new Ice.Identity();
                identity.category = properties.getPropertyWithDefault("IceBox.InstanceName", "IceBox");
                identity.name = "ServiceManager";
                adapter.add(this, identity);
            }

            //
            // Parse the property set with the prefix "IceBox.Service.". These
            // properties should have the following format:
            //
            // IceBox.Service.Foo=[jar-or-dir:]Package.Foo [args]
            //
            // We parse the service properties specified in IceBox.LoadOrder
            // first, then the ones from remaining services.
            //
            final String prefix = "IceBox.Service.";
            java.util.Map<String, String> services = properties.getPropertiesForPrefix(prefix);
            String[] loadOrder = properties.getPropertyAsList("IceBox.LoadOrder");
            java.util.List<StartServiceInfo> servicesInfo = new java.util.ArrayList<StartServiceInfo>();
            for(String name : loadOrder)
            {
                if(name.length() > 0)
                {
                    String key = prefix + name;
                    String value = services.get(key);
                    if(value == null)
                    {
                        FailureException ex = new FailureException();
                        ex.reason = "ServiceManager: no service definition for `" + name + "'";
                        throw ex;
                    }
                    servicesInfo.add(new StartServiceInfo(name, value, _argv));
                    services.remove(key);
                }
            }
            for(java.util.Map.Entry<String, String> p : services.entrySet())
            {
                String name = p.getKey().substring(prefix.length());
                String value = p.getValue();
                servicesInfo.add(new StartServiceInfo(name, value, _argv));
            }

            //
            // Check if some services are using the shared communicator in which
            // case we create the shared communicator now with a property set which
            // is the union of all the service properties (services which are using
            // the shared communicator).
            //
            if(properties.getPropertiesForPrefix("IceBox.UseSharedCommunicator.").size() > 0)
            {
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = createServiceProperties("SharedCommunicator");
                for(StartServiceInfo service : servicesInfo)
                {
                    if(properties.getPropertyAsInt("IceBox.UseSharedCommunicator." + service.name) <= 0)
                    {
                        continue;
                    }

                    //
                    // Load the service properties using the shared communicator properties as
                    // the default properties.
                    //
                    Ice.StringSeqHolder serviceArgs = new Ice.StringSeqHolder(service.args);
                    Ice.Properties svcProperties = Ice.Util.createProperties(serviceArgs, initData.properties);
                    service.args = serviceArgs.value;

                    //
                    // Erase properties from the shared communicator which don't exist in the
                    // service properties (which include the shared communicator properties
                    // overriden by the service properties).
                    //
                    java.util.Map<String, String> allProps = initData.properties.getPropertiesForPrefix("");
                    for(String key : allProps.keySet())
                    {
                        if(svcProperties.getProperty(key).length() == 0)
                        {
                            initData.properties.setProperty(key, "");
                        }
                    }

                    //
                    // Add the service properties to the shared communicator properties.
                    //
                    for(java.util.Map.Entry<String, String> p : svcProperties.getPropertiesForPrefix("").entrySet())
                    {
                        initData.properties.setProperty(p.getKey(), p.getValue());
                    }

                    //
                    // Parse <service>.* command line options (the Ice command line options
                    // were parsed by the createProperties above)
                    //
                    service.args = initData.properties.parseCommandLineOptions(service.name, service.args);
                }

                //
                // If Ice metrics are enabled on the IceBox communicator, we also enable them on the 
                // shared communicator.
                // 
                IceInternal.MetricsAdminI metricsAdmin = null;
                if(_communicator.getObserver() instanceof IceMX.CommunicatorObserverI)
                {
                    metricsAdmin = new IceInternal.MetricsAdminI(initData.properties, Ice.Util.getProcessLogger());
                    initData.observer = new IceMX.CommunicatorObserverI(metricsAdmin);
                }

                _sharedCommunicator = Ice.Util.initialize(initData);

                //
                // Ensure the metrics admin plugin uses the same property set as the
                // communicator. This is necessary to correctly deal with runtime 
                // property updates.
                //
                if(metricsAdmin != null)
                {
                    metricsAdmin.setProperties(_sharedCommunicator.getProperties());
                }
            }

            for(StartServiceInfo s : servicesInfo)
            {
                start(s.name, s.className, s.classDir, s.absolutePath, s.args);
            }

            //
            // We may want to notify external scripts that the services
            // have started. This is done by defining the property:
            //
            // IceBox.PrintServicesReady=bundleName
            //
            // Where bundleName is whatever you choose to call this set of
            // services. It will be echoed back as "bundleName ready".
            //
            // This must be done after start() has been invoked on the
            // services.
            //
            String bundleName = properties.getProperty("IceBox.PrintServicesReady");
            if(bundleName.length() > 0)
            {
                System.out.println(bundleName + " ready");
            }

            //
            // Don't move after the adapter activation. This allows
            // applications to wait for the service manager to be
            // reachable before sending a signal to shutdown the
            // IceBox.
            //
            Ice.Application.shutdownOnInterrupt();

            //
            // Register "this" as a facet to the Admin object and
            // create Admin object
            //
            try
            {
                _communicator.addAdminFacet(this, "IceBox.ServiceManager");
                _communicator.getAdmin();
            }
            catch(Ice.ObjectAdapterDeactivatedException ex)
            {
                //
                // Expected if the communicator has been shutdown.
                //
            }

            //
            // Start request dispatching after we've started the services.
            //
            if(adapter != null)
            {
                try
                {
                    adapter.activate();
                }
                catch(Ice.ObjectAdapterDeactivatedException ex)
                {
                    //
                    // Expected if the communicator has been shutdown.
                    //
                }
            }

            _communicator.waitForShutdown();
            Ice.Application.defaultInterrupt();
        }
        catch(FailureException ex)
        {
            java.io.StringWriter sw = new java.io.StringWriter();
            java.io.PrintWriter pw = new java.io.PrintWriter(sw);
            pw.println(ex.reason);
            ex.printStackTrace(pw);
            pw.flush();
            _logger.error(sw.toString());
            return 1;
        }
        catch(Throwable ex)
        {
            java.io.StringWriter sw = new java.io.StringWriter();
            java.io.PrintWriter pw = new java.io.PrintWriter(sw);
            ex.printStackTrace(pw);
            pw.flush();
            _logger.error("ServiceManager: caught exception:\n" + sw.toString());
            return 1;
        }
        finally
        {
            //
            // Invoke stop() on the services.
            //
            stopAll();
        }

        return 0;
    }

    synchronized private void
    start(String service, String className, String classDir, boolean absolutePath, String[] args)
        throws FailureException
    {
        //
        // Load the class.
        //

        //
        // Use a class loader if the user specified a JAR file or class directory.
        //
        Class<?> c = null;
        if(classDir != null)
        {
            try
            {
                if(!absolutePath)
                {
                    classDir = new java.io.File(System.getProperty("user.dir") + java.io.File.separator +
                                                classDir).getCanonicalPath();
                }
                
                if(!classDir.endsWith(java.io.File.separator) && !classDir.endsWith(".jar"))
                {
                    classDir += java.io.File.separator;
                }
                
                //
                // Reuse an existing class loader if we have already loaded a plug-in with
                // the same value for classDir, otherwise create a new one.
                //
                ClassLoader cl = null;
                
                if(_classLoaders == null)
                {
                    _classLoaders = new java.util.HashMap<String, ClassLoader>();
                }
                else
                {
                    cl = _classLoaders.get(classDir);
                }
                
                if(cl == null)
                {
                    final java.net.URL[] url = new java.net.URL[] { new java.net.URL("file:///" + classDir) };
                    
                    cl = new java.net.URLClassLoader(url);
                    
                    _classLoaders.put(classDir, cl);
                }
                
                c = cl.loadClass(className);
            }
            catch(java.net.MalformedURLException ex)
            {
                throw new FailureException("ServiceManager: invalid entry point format `" + classDir + "'", ex);
            }
            catch(java.io.IOException ex)
            {
                throw new FailureException("ServiceManager: invalid path in plug-in entry point `" + classDir +
                                           "'", ex);
            }
            catch(java.lang.ClassNotFoundException ex)
            {
                // Ignored
            }
        }
        else
        {
            c = IceInternal.Util.findClass(className, null);
        }
        
        if(c == null)
        {
            throw new FailureException("ServiceManager: class " + className + " not found");
        }

        ServiceInfo info = new ServiceInfo();
        info.name = service;
        info.status = StatusStopped;
        info.args = args;

        //
        // If Ice.UseSharedCommunicator.<name> is defined, create a
        // communicator for the service. The communicator inherits
        // from the shared communicator properties. If it's not
        // defined, add the service properties to the shared
        // commnunicator property set.
        //
        Ice.Communicator communicator;
        IceInternal.MetricsAdminI metricsAdmin = null;
        if(_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
        {
            assert(_sharedCommunicator != null);
            communicator = _sharedCommunicator;
            if(communicator.getObserver() instanceof IceMX.CommunicatorObserverI)
            {
                IceMX.CommunicatorObserverI o = (IceMX.CommunicatorObserverI)communicator.getObserver();
                metricsAdmin = o.getMetricsAdmin();
            }
        }
        else
        {
            try
            {
                //
                // Create the service properties. We use the communicator properties as the default
                // properties if IceBox.InheritProperties is set.
                //
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = createServiceProperties(service);
                Ice.StringSeqHolder serviceArgs = new Ice.StringSeqHolder(info.args);
                if(serviceArgs.value.length > 0)
                {
                    //
                    // Create the service properties with the given service arguments. This should
                    // read the service config file if it's specified with --Ice.Config.
                    //
                    initData.properties = Ice.Util.createProperties(serviceArgs, initData.properties);

                    //
                    // Next, parse the service "<service>.*" command line options (the Ice command
                    // line options were parsed by the createProperties above)
                    //
                    serviceArgs.value = initData.properties.parseCommandLineOptions(service, serviceArgs.value);
                }
                
                //
                // Clone the logger to assign a new prefix.
                //
                initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName"));

                //
                // If Ice metrics are enabled on the IceBox communicator, we also enable them on
                // the service communicator.
                // 
                if(_communicator.getObserver() instanceof IceMX.CommunicatorObserverI)
                {
                    metricsAdmin = new IceInternal.MetricsAdminI(initData.properties, initData.logger);
                    initData.observer = new IceMX.CommunicatorObserverI(metricsAdmin);
                }
                
                //
                // Remaining command line options are passed to the communicator. This is
                // necessary for Ice plug-in properties (e.g.: IceSSL).
                //
                info.communicator = Ice.Util.initialize(serviceArgs, initData);
                info.args = serviceArgs.value;
                communicator = info.communicator;

                //
                // Ensure the metrics admin plugin uses the same property set as the
                // communicator. This is necessary to correctly deal with runtime 
                // property updates.
                //
                if(metricsAdmin != null)
                {
                    metricsAdmin.setProperties(communicator.getProperties());
                }
            }
            catch(Throwable ex)
            {
                FailureException e = new FailureException();
                e.reason = "ServiceManager: exception while starting service " + service;
                e.initCause(ex);
                throw e;
            }
        }

        try
        {
            //
            // Add a PropertiesAdmin facet to the service manager's communicator that provides
            // access to this service's property set. We do this prior to instantiating the
            // service so that the service's constructor is able to access the facet (e.g.,
            // in case it wants to set a callback).
            //
            final String facetName = "IceBox.Service." + service + ".Properties";
            IceInternal.PropertiesAdminI propAdmin = new IceInternal.PropertiesAdminI(facetName, 
                                                                                      communicator.getProperties(), 
                                                                                      communicator.getLogger());
            _communicator.addAdminFacet(propAdmin, facetName);

            //
            // If a metrics admin facet is setup for the service, register
            // it with the IceBox communicator.
            //
            if(metricsAdmin != null)
            {
                _communicator.addAdminFacet(metricsAdmin, "IceBox.Service." + info.name + ".MetricsAdmin");

                // Ensure the metrics admin facet is notified of property updates.
                propAdmin.addUpdateCallback(metricsAdmin);
            }

            //
            // Instantiate the service.
            //
            try
            {
                //
                // If the service class provides a constructor that accepts an Ice.Communicator argument,
                // use that in preference to the default constructor.
                //
                java.lang.Object obj = null;
                try
                {
                    java.lang.reflect.Constructor<?> con = c.getDeclaredConstructor(Ice.Communicator.class);
                    obj = con.newInstance(_communicator);
                }
                catch(IllegalAccessException ex)
                {
                    throw new FailureException(
                        "ServiceManager: unable to access service constructor " + className + "(Ice.Communicator)", ex);
                }
                catch(NoSuchMethodException ex)
                {
                    // Ignore.
                }
                catch(java.lang.reflect.InvocationTargetException ex)
                {
                    if(ex.getCause() != null)
                    {
                        throw ex.getCause();
                    }
                    else
                    {
                        throw new FailureException("ServiceManager: exception in service constructor for " + className, ex);
                    }
                }

                if(obj == null)
                {
                    //
                    // Fall back to the default constructor.
                    //
                    try
                    {
                        obj = c.newInstance();
                    }
                    catch(IllegalAccessException ex)
                    {
                        throw new FailureException(
                            "ServiceManager: unable to access default service constructor in class " + className, ex);
                    }
                }

                try
                {
                    info.service = (Service)obj;
                }
                catch(ClassCastException ex)
                {
                    throw new FailureException("ServiceManager: class " + className + " does not implement IceBox.Service");
                }
            }
            catch(InstantiationException ex)
            {
                throw new FailureException("ServiceManager: unable to instantiate class " + className, ex);
            }
            catch(FailureException ex)
            {
                throw ex;
            }
            catch(Throwable ex)
            {
                throw new FailureException("ServiceManager: exception in service constructor for " + className, ex);
            }

            try
            {
                info.service.start(service, communicator, info.args);

                //
                // There is no need to notify the observers since the 'start all'
                // (that indirectly calls this method) occurs before the creation of
                // the Server Admin object, and before the activation of the main
                // object adapter (so before any observer can be registered)
                //
            }
            catch(FailureException ex)
            {
                throw ex;
            }
            catch(Throwable ex)
            {
                FailureException e = new FailureException();
                e.reason = "ServiceManager: exception while starting service " + service;
                e.initCause(ex);
                throw e;
            }

            info.status = StatusStarted;
            _services.add(info);
        }
        catch(Ice.ObjectAdapterDeactivatedException ex)
        {
            //
            // Can be raised by addAdminFacet if the service manager communicator has been shut down.
            //
            if(info.communicator != null)
            {
                destroyServiceCommunicator(service, info.communicator);
            }
        }
        catch(RuntimeException ex)
        {
            try
            {
                _communicator.removeAdminFacet("IceBox.Service." + service + ".Properties");
            }
            catch(Ice.LocalException e)
            {
                // Ignored
            }

            if(info.communicator != null)
            {
                destroyServiceCommunicator(service, info.communicator);
            }

            throw ex;
        }
    }

    private synchronized void
    stopAll()
    {
        //
        // First wait for any active startService/stopService calls to complete.
        //
        while(_pendingStatusChanges)
        {
            try
            {
                wait();
            }
            catch(java.lang.InterruptedException ex)
            {
            }
        }

        //
        // For each service, we call stop on the service and flush its database environment to
        // the disk. Services are stopped in the reverse order of the order they were started.
        //
        java.util.List<String> stoppedServices = new java.util.ArrayList<String>();
        java.util.ListIterator<ServiceInfo> p = _services.listIterator(_services.size());
        while(p.hasPrevious())
        {
            ServiceInfo info = p.previous();
            if(info.status == StatusStarted)
            {
                try
                {
                    info.service.stop();
                    info.status = StatusStopped;
                    stoppedServices.add(info.name);
                }
                catch(Throwable e)
                {
                    java.io.StringWriter sw = new java.io.StringWriter();
                    java.io.PrintWriter pw = new java.io.PrintWriter(sw);
                    e.printStackTrace(pw);
                    pw.flush();
                    _logger.warning("ServiceManager: exception while stopping service " + info.name + ":\n" +
                                    sw.toString());
                }
            }

            try
            {
                _communicator.removeAdminFacet("IceBox.Service." + info.name + ".Properties");
            }
            catch(Ice.LocalException e)
            {
                // Ignored
            }

            if(info.communicator != null)
            {
                destroyServiceCommunicator(info.name, info.communicator);
            }
        }

        if(_sharedCommunicator != null)
        {
            try
            {
                _sharedCommunicator.destroy();
            }
            catch(java.lang.Exception e)
            {
                java.io.StringWriter sw = new java.io.StringWriter();
                java.io.PrintWriter pw = new java.io.PrintWriter(sw);
                e.printStackTrace(pw);
                pw.flush();
                _logger.warning("ServiceManager: exception while destroying shared communicator:\n" + sw.toString());
            }
            _sharedCommunicator = null;
        }

        _services.clear();
        servicesStopped(stoppedServices, _observers);
    }

    private void
    servicesStarted(java.util.List<String> services, java.util.Set<ServiceObserverPrx> observers)
    {
        if(services.size() > 0)
        {
            String[] servicesArray = services.toArray(new String[0]);

            for(final ServiceObserverPrx observer: observers)
            {
                observer.begin_servicesStarted(servicesArray, _observerCompletedCB);
            }
        }
    }

    private void
    servicesStopped(java.util.List<String> services, java.util.Set<ServiceObserverPrx> observers)
    {
        if(services.size() > 0)
        {
            String[] servicesArray = services.toArray(new String[0]);

            for(final ServiceObserverPrx observer: observers)
            {
                observer.begin_servicesStopped(servicesArray, _observerCompletedCB);
            }
        }
    }

    private void
    observerRemoved(ServiceObserverPrx observer, RuntimeException ex)
    {
        if(_traceServiceObserver >= 1)
        {
            //
            // CommunicatorDestroyedException may occur during shutdown. The observer notification has
            // been sent, but the communicator was destroyed before the reply was received. We do not
            // log a message for this exception.
            //
            if(!(ex instanceof Ice.CommunicatorDestroyedException))
            {
                _logger.trace("IceBox.ServiceObserver",
                              "Removed service observer " + _communicator.proxyToString(observer)
                              + "\nafter catching " + ex.toString());
            }
        }
    }

    public final static int StatusStopping = 0;
    public final static int StatusStopped = 1;
    public final static int StatusStarting = 2;
    public final static int StatusStarted = 3;

    static class ServiceInfo implements Cloneable
    {
        public Object clone()
        {
            Object o = null;
            try
            {
                o = super.clone();
            }
            catch(CloneNotSupportedException ex)
            {
            }
            return o;
        }

        public String name;
        public Service service;
        public Ice.Communicator communicator = null;
        public int status;
        public String[] args;
    }

    static class StartServiceInfo
    {
        StartServiceInfo(String service, String value, String[] serverArgs)
        {
            name = service;

            //
            // We support the following formats:
            //
            // <class-name> [args]
            // <jar-file>:<class-name> [args]
            // <class-dir>:<class-name> [args]
            // "<path with spaces>":<class-name> [args]
            // "<path with spaces>:<class-name>" [args]
            //

            try
            {
                args = IceUtilInternal.Options.split(value);
            }
            catch(IceUtilInternal.Options.BadQuote ex)
            {
                throw new FailureException("ServiceManager: invalid arguments for service `" + name + "':\n" +
                                           ex.getMessage());
            }

            assert(args.length > 0);

            final String entryPoint = args[0];

            final boolean isWindows = System.getProperty("os.name").startsWith("Windows");
            absolutePath = false;

            //
            // Find first ':' that isn't part of the file path.
            //
            int pos = entryPoint.indexOf(':');
            if(isWindows)
            {
                final String driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                if(pos == 1 && entryPoint.length() > 2 && driveLetters.indexOf(entryPoint.charAt(0)) != -1 &&
                   (entryPoint.charAt(2) == '\\' || entryPoint.charAt(2) == '/'))
                {
                    absolutePath = true;
                    pos = entryPoint.indexOf(':', pos + 1);
                }
                if(!absolutePath)
                {
                    absolutePath = entryPoint.startsWith("\\\\");
                }
            }
            else
            {
                absolutePath = entryPoint.startsWith("/");
            }

            if((pos == -1 && absolutePath) || (pos != -1 && entryPoint.length() <= pos + 1))
            {
                //
                // Class name is missing.
                //
                throw new FailureException("ServiceManager: invalid entry point for service `" + name + "':\n" +
                                           entryPoint);
            }

            //
            // Extract the JAR file or subdirectory, if any.
            //
            classDir = null; // Path name of JAR file or subdirectory.

            if(pos == -1)
            {
                className = entryPoint;
            }
            else
            {
                classDir = entryPoint.substring(0, pos).trim();
                className = entryPoint.substring(pos + 1).trim();
            }

            //
            // Shift the arguments.
            //
            String[] tmp = new String[args.length - 1];
            System.arraycopy(args, 1, tmp, 0, args.length - 1);
            args = tmp;

            if(serverArgs.length > 0)
            {
                java.util.List<String> l = new java.util.ArrayList<String>(java.util.Arrays.asList(args));
                for(String arg : serverArgs)
                {
                    if(arg.startsWith("--" + service + "."))
                    {
                        l.add(arg);
                    }
                }
                args = l.toArray(args);
            }
        }

        String name;
        String[] args;
        String className;
        String classDir;
        boolean absolutePath;
    }

    private Ice.Properties
    createServiceProperties(String service)
    {
        Ice.Properties properties;
        Ice.Properties communicatorProperties = _communicator.getProperties();
        if(communicatorProperties.getPropertyAsInt("IceBox.InheritProperties") > 0)
        {
            properties = communicatorProperties._clone();
            properties.setProperty("Ice.Admin.Endpoints", ""); // Inherit all except Ice.Admin.Endpoints!
        }
        else
        {
            properties = Ice.Util.createProperties();
        }

        String programName = communicatorProperties.getProperty("Ice.ProgramName");
        if(programName.length() == 0)
        {
            properties.setProperty("Ice.ProgramName", service);
        }
        else
        {
            properties.setProperty("Ice.ProgramName", programName + "-" + service);
        }
        return properties;
    }

    private void
    destroyServiceCommunicator(String service, Ice.Communicator communicator)
    {
        try
        {
            communicator.shutdown();
            communicator.waitForShutdown();
        }
        catch(Ice.CommunicatorDestroyedException e)
        {
            //
            // Ignore, the service might have already destroyed
            // the communicator for its own reasons.
            //
        }
        catch(java.lang.Exception e)
        {
            java.io.StringWriter sw = new java.io.StringWriter();
            java.io.PrintWriter pw = new java.io.PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            _logger.warning("ServiceManager: exception in shutting down communicator for service "
                            + service + "\n" + sw.toString());
        }

        try
        {
            communicator.destroy();
        }
        catch(java.lang.Exception e)
        {
            java.io.StringWriter sw = new java.io.StringWriter();
            java.io.PrintWriter pw = new java.io.PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            _logger.warning("ServiceManager: exception in destroying communicator for service "
                            + service + "\n" + sw.toString());
        }
    }

    private Ice.Communicator _communicator;
    private Ice.Communicator _sharedCommunicator;
    private Ice.Logger _logger;
    private String[] _argv; // Filtered server argument vector
    private java.util.List<ServiceInfo> _services = new java.util.LinkedList<ServiceInfo>();
    private boolean _pendingStatusChanges = false;
    private Ice.Callback _observerCompletedCB;
    private java.util.HashSet<ServiceObserverPrx> _observers = new java.util.HashSet<ServiceObserverPrx>();
    private int _traceServiceObserver = 0;
    private java.util.Map<String, ClassLoader> _classLoaders;
}