summaryrefslogtreecommitdiff
path: root/java/src/IceBox/ServiceManagerI.java
blob: 445e01744bd5961f4bf90bbd7797d03e04512290 (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
// **********************************************************************
//
// Copyright (c) 2003-2006 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.Application server, String[] args)
    {
	_server = server;
	_logger = _server.communicator().getLogger();
	_argv = args;
    }

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

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

    public int
    run()
    {
	try
	{
	    //
	    // 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 = _server.communicator().createObjectAdapter("IceBox.ServiceManager");

	    Ice.Properties properties = _server.communicator().getProperties();

	    String identity = properties.getProperty("IceBox.ServiceManager.Identity");
	    if(identity.length() == 0)
	    {
		identity = properties.getPropertyWithDefault("IceBox.InstanceName", "IceBox") + "/ServiceManager";
	    }
	    adapter.add(this, _server.communicator().stringToIdentity(identity));

	    //
	    // Parse the IceBox.LoadOrder property.
	    //
	    String order = properties.getProperty("IceBox.LoadOrder");
	    String[] loadOrder = null;
	    if(order.length() > 0)
	    {
		loadOrder = order.trim().split("[,\t ]+");
	    }

	    //
	    // Load and start the services defined in the property set
	    // with the prefix "IceBox.Service.". These properties should
	    // have the following format:
	    //
	    // IceBox.Service.Foo=Package.Foo [args]
	    //
	    // We load the services specified in IceBox.LoadOrder first,
	    // then load any remaining services.
	    //
	    final String prefix = "IceBox.Service.";
	    java.util.Map services = properties.getPropertiesForPrefix(prefix);
	    if(loadOrder != null)
	    {
		for(int i = 0; i < loadOrder.length; ++i)
		{
		    if(loadOrder[i].length() > 0)
		    {
			String key = prefix + loadOrder[i];
			String value = (String)services.get(key);
			if(value == null)
			{
			    FailureException ex = new FailureException();
			    ex.reason = "ServiceManager: no service definition for `" + loadOrder[i] + "'";
			    throw ex;
			}
			load(loadOrder[i], value);
			services.remove(key);
		    }
		}
	    }
	    java.util.Iterator p = services.entrySet().iterator();
	    while(p.hasNext())
	    {
		java.util.Map.Entry entry = (java.util.Map.Entry)p.next();
		String name = ((String)entry.getKey()).substring(prefix.length());
		String value = (String)entry.getValue();
		load(name, value);
	    }

	    //
	    // 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.
	    //
	    _server.shutdownOnInterrupt();

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

	    _server.communicator().waitForShutdown();
	    _server.defaultInterrupt();

	    //
	    // Invoke stop() on the services.
	    //
	    stopAll();
	}
	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());
	    stopAll();
	    return 1;
	}
	catch(Ice.LocalException 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: " + ex + "\n" + sw.toString());
	    stopAll();
	    return 1;
	}
	catch(java.lang.Exception 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: unknown exception\n" + sw.toString());
	    stopAll();
	    return 1;
	}

	return 0;
    }

    private void
    load(String name, String value)
        throws FailureException
    {
	//
	// Separate the entry point from the arguments.
	//
	String className;
	String[] args;
	int pos = IceUtil.StringUtil.findFirstOf(value, " \t\n");
	if(pos == -1)
	{
	    className = value;
	    args = new String[0];
	}
	else
	{
	    className = value.substring(0, pos);
	    try
	    {
		args = IceUtil.Options.split(value.substring(pos));
	    }
	    catch(IceUtil.Options.BadQuote ex)
	    {
		FailureException e = new FailureException();
		e.reason = "ServiceManager: invalid arguments for service `" + name + "':\n" + ex.toString();
		throw e;
	    }
	}

	start(name, className, args);
    }

    private void
    start(String service, String className, String[] args)
        throws FailureException
    {
	//
	// Create the service property set from the service arguments
	// and the server arguments. The service property set will be
	// used to create a new communicator, or will be added to the
	// shared communicator, depending on the value of the
	// IceBox.UseSharedCommunicator property.
	//
	java.util.ArrayList l = new java.util.ArrayList();
	for(int j = 0; j < args.length; j++)
	{
	    l.add(args[j]);
	}
	for(int j = 0; j < _argv.length; j++)
	{
	    if(_argv[j].startsWith("--" + service + "."))
	    {
		l.add(_argv[j]);
	    }
	}

	String[] serviceArgs = new String[l.size()];
	l.toArray(serviceArgs);

	//
	// Instantiate the class.
	//
	ServiceInfo info = new ServiceInfo();
	try
	{
	    Class c = Class.forName(className);
	    java.lang.Object obj = c.newInstance();
	    try
	    {
		info.service = (Service)obj;
	    }
	    catch(ClassCastException ex)
	    {
		FailureException e = new FailureException();
		e.reason = "ServiceManager: class " + className + " does not implement IceBox.Service";
		throw e;
	    }
	}
	catch(ClassNotFoundException ex)
	{
	    FailureException e = new FailureException();
	    e.reason = "ServiceManager: class " + className + " not found";
	    e.initCause(ex);
	    throw e;
	}
	catch(IllegalAccessException ex)
	{
	    FailureException e = new FailureException();
	    e.reason = "ServiceManager: unable to access default constructor in class " + className;
	    e.initCause(ex);
	    throw e;
	}
	catch(InstantiationException ex)
	{
	    FailureException e = new FailureException();
	    e.reason = "ServiceManager: unable to instantiate class " + className;
	    e.initCause(ex);
	    throw e;
	}

	//
	// Invoke Service::start().
	//
	try
	{
	    //
	    // 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.Properties properties = _server.communicator().getProperties();
	    if(properties.getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
	    {
		Ice.Properties fileProperties = Ice.Util.createProperties(serviceArgs);
		properties.parseCommandLineOptions("", fileProperties.getCommandLineOptions());

		serviceArgs = properties.parseIceCommandLineOptions(serviceArgs);
		serviceArgs = properties.parseCommandLineOptions(service, serviceArgs);
	    }
	    else
	    {
		Ice.Properties serviceProperties = properties._clone();

		//
		// Initialize the Ice.ProgramName property with the name of this service.
		//
		String name = serviceProperties.getProperty("Ice.ProgramName");
		if(!name.equals(service))
		{
		    name = name.length() == 0 ? service : name + "-" + service;
		}

		//
		// Load property file eventually specified with
		// --Ice.Config and add the properties from the file to
		// the service properties.
		//
		Ice.Properties fileProperties = Ice.Util.createProperties(serviceArgs);
		serviceProperties.parseCommandLineOptions("", fileProperties.getCommandLineOptions());

		serviceProperties.setProperty("Ice.ProgramName", name);

		//
		// Parse Ice and <service>.* command line options.
		//
		serviceArgs = serviceProperties.parseIceCommandLineOptions(serviceArgs);
		serviceArgs = serviceProperties.parseCommandLineOptions(service, serviceArgs);

		//
		// Remaining command line options are passed to the
		// communicator with argc/argv. This is necessary for Ice
		// plugin properties (e.g.: IceSSL).
		//
		Ice.InitializationData initData = new Ice.InitializationData();
		initData.properties = serviceProperties;
		info.communicator = Ice.Util.initialize(serviceArgs, initData);
	    }
	
	    Ice.Communicator communicator = info.communicator != null ? info.communicator : _server.communicator();

	    try
	    {
		info.service.start(service, communicator, serviceArgs);
	    }
	    catch(Throwable ex)
	    {
		if(info.communicator != null)
		{
		    try
		    {
			info.communicator.shutdown();
			info.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
		    {
			info.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 communciator for service"
					+ service + "\n" + sw.toString());
		    }
		}
		throw ex;
	    }

	    _services.put(service, info);
	}
	catch(FailureException ex)
	{
	    throw ex;
	}
	catch(Throwable ex)
	{
	    FailureException e = new FailureException();
	    e.reason = "ServiceManager: exception while starting service " + service + ": " + ex;
	    e.initCause(ex);
	    throw e;
	}
    }

    private void
    stopAll()
    {
	//
	// First, for each service, we call stop on the service and flush its database environment to 
	// the disk.
	//
	java.util.Iterator p = _services.entrySet().iterator();
	while(p.hasNext())
	{
	    java.util.Map.Entry entry = (java.util.Map.Entry)p.next();
	    String name = (String)entry.getKey();
	    ServiceInfo info = (ServiceInfo)entry.getValue();
	    try
	    {
		info.service.stop();
	    }
	    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 stop for service " + name + "\n" + sw.toString());
	    }

	    if(info.communicator != null)
	    {
		try
		{
		    info.communicator.shutdown();
		    info.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 stop for service " + name + "\n" + sw.toString());
		}
	    
		try
		{
		    info.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 stop for service " + name + "\n" + sw.toString());
		}
	    }
	}

	_services.clear();
    }

    class ServiceInfo
    {
        public Service service;
	public Ice.Communicator communicator = null;
    }

    private Ice.Application _server;
    private Ice.Logger _logger;
    private String[] _argv; // Filtered server argument vector
    private java.util.HashMap _services = new java.util.HashMap();
}