/
Dempsy.java
596 lines (504 loc) · 24 KB
/
Dempsy.java
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
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nokia.dempsy;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;
import com.nokia.dempsy.cluster.ClusterInfoException;
import com.nokia.dempsy.cluster.ClusterInfoSession;
import com.nokia.dempsy.cluster.ClusterInfoSessionFactory;
import com.nokia.dempsy.config.ApplicationDefinition;
import com.nokia.dempsy.config.ClusterDefinition;
import com.nokia.dempsy.config.ClusterId;
import com.nokia.dempsy.container.MpContainer;
import com.nokia.dempsy.executor.DempsyExecutor;
import com.nokia.dempsy.internal.util.SafeString;
import com.nokia.dempsy.messagetransport.Destination;
import com.nokia.dempsy.messagetransport.Receiver;
import com.nokia.dempsy.messagetransport.Transport;
import com.nokia.dempsy.monitoring.StatsCollector;
import com.nokia.dempsy.monitoring.StatsCollectorFactory;
import com.nokia.dempsy.output.OutputExecuter;
import com.nokia.dempsy.router.CurrentClusterCheck;
import com.nokia.dempsy.router.Router;
import com.nokia.dempsy.router.RoutingStrategy;
import com.nokia.dempsy.serialization.Serializer;
/**
* This class is the master orchestrator of the setup of a VM running the application.
* It is intended to have the ApplicationDefinitions autowired in so it picks up
* each one.
*/
public class Dempsy
{
static Logger logger = LoggerFactory.getLogger(Dempsy.class);
/**
* There is an instance of an application for every ApplicationDefinition
* autowired into the Dempsy instance. In most real cases this will be only
* one.
*/
public class Application
{
/**
* Currently a "Dempsy.Application.Cluster" has no utility since it only has a single Node.
* This may change
*/
public class Cluster
{
/**
* A Node is essentially an {@link MpContainer} with all of the attending infrastructure.
* Currently a Node is instantiated within the Dempsy orchestrator as a one to one with the
* {@link Cluster}.
*/
public class Node
{
protected ClusterDefinition clusterDefinition;
Router router = null;
private MpContainer container = null;
RoutingStrategy.Inbound strategyInbound = null;
List<Class<?>> acceptedMessageClasses = null;
Receiver receiver = null;
StatsCollector statsCollector = null;
private Node(ClusterDefinition clusterDefinition) { this.clusterDefinition = clusterDefinition; }
@SuppressWarnings("unchecked")
private void start() throws DempsyException
{
try
{
DempsyExecutor executor = (DempsyExecutor)clusterDefinition.getExecutor(); // this can be null
if (executor != null)
executor.start();
ClusterInfoSession clusterSession = clusterSessionFactory.createSession();
ClusterId currentClusterId = clusterDefinition.getClusterId();
router = new Router(clusterDefinition.getParentApplicationDefinition());
router.setCurrentCluster(currentClusterId);
router.setClusterSession(clusterSession);
// get the executor if one is set
container = new MpContainer(currentClusterId);
container.setDispatcher(router);
if (executor != null)
container.setExecutor(executor);
Object messageProcessorPrototype = clusterDefinition.getMessageProcessorPrototype();
if (messageProcessorPrototype != null)
{
preInitializePrototype(messageProcessorPrototype);
container.setPrototype(messageProcessorPrototype);
}
acceptedMessageClasses = getAcceptedMessages(clusterDefinition);
Serializer<Object> serializer = (Serializer<Object>)clusterDefinition.getSerializer();
if (serializer != null)
container.setSerializer(serializer);
// there is only a reciever if we have an Mp (that is, we aren't an adaptor) and start accepting messages
Destination thisDestination = null;
if (messageProcessorPrototype != null && acceptedMessageClasses != null && acceptedMessageClasses.size() > 0)
{
receiver = transport.createInbound(executor);
receiver.setListener(container);
receiver.start();
thisDestination = receiver.getDestination();
}
StatsCollectorFactory statsFactory = (StatsCollectorFactory)clusterDefinition.getStatsCollectorFactory();
if (statsFactory != null)
{
statsCollector = statsFactory.createStatsCollector(currentClusterId,
receiver != null ? thisDestination : null);
router.setStatsCollector(statsCollector);
container.setStatCollector(statsCollector);
if (receiver != null)
receiver.setStatsCollector(statsCollector);
}
router.setDefaultSenderFactory(transport.createOutbound(executor, statsCollector));
RoutingStrategy strategy = (RoutingStrategy)clusterDefinition.getRoutingStrategy();
KeySource<?> keySource = clusterDefinition.getKeySource();
if (keySource != null)
container.setKeySource(keySource);
// there is only an inbound strategy if we have an Mp (that is, we aren't an adaptor) and
// we actually accept messages
if (messageProcessorPrototype != null && acceptedMessageClasses != null && acceptedMessageClasses.size() > 0)
strategyInbound = strategy.createInbound(clusterSession,currentClusterId,acceptedMessageClasses, thisDestination,container);
// this can fail because of down cluster manager server ... but it should eventually recover.
try { router.initialize(); }
catch (ClusterInfoException e)
{
logger.warn("Strategy failed to initialize. Continuing anyway. The cluster manager issue will be resolved automatically.",e);
}
Adaptor adaptor = clusterDefinition.isRouteAdaptorType() ? clusterDefinition.getAdaptor() : null;
if (adaptor != null)
adaptor.setDispatcher(router);
else {
OutputExecuter outputExecuter = (OutputExecuter) clusterDefinition.getOutputExecuter();
if (outputExecuter != null) {
outputExecuter.setOutputInvoker(container);
}
}
container.startEvictionThread(Cluster.this.clusterDefinition.getEvictionFrequency(), Cluster.this.clusterDefinition.getEvictionTimeUnit());
}
catch(RuntimeException e) { throw e; }
catch(Exception e) { throw new DempsyException(e); }
}
public StatsCollector getStatsCollector() { return statsCollector; }
public MpContainer getMpContainer() { return container; }
public void stop()
{
if (receiver != null)
{
try { receiver.stop(); receiver = null; }
catch (Throwable th)
{
logger.error("Error stoping the reciever " + SafeString.objectDescription(receiver) +
" for " + SafeString.valueOf(clusterDefinition) + " due to the following exception:",th);
}
}
// shut the container down prior to the router.
if (container != null)
try { container.shutdown(); container = null; } catch (Throwable th) { logger.info("Problem shutting down node for " + SafeString.valueOf(clusterDefinition), th); }
// the cluster session is stopped by the router.
if (router != null)
try { router.stop(); router = null; } catch (Throwable th) { logger.info("Problem shutting down node for " + SafeString.valueOf(clusterDefinition), th); }
if (statsCollector != null)
try { statsCollector.stop(); statsCollector = null;} catch (Throwable th) { logger.info("Problem shutting down node for " + SafeString.valueOf(clusterDefinition), th); }
if (strategyInbound != null)
try { strategyInbound.stop(); strategyInbound = null;} catch (Throwable th) { logger.info("Problem shutting down node for " + SafeString.valueOf(clusterDefinition), th); }
DempsyExecutor executor = (DempsyExecutor)clusterDefinition.getExecutor(); // this can be null
if (executor != null)
try { executor.shutdown(); } catch (Throwable th) { logger.info("Problem shutting down node for " + SafeString.valueOf(clusterDefinition), th); }
}
// Only called from tests
public Router retouRteg() { return router; }
/**
* Run any methods annotated PreInitilze on the MessageProcessor prototype
* @param prototype reference to MessageProcessor prototype
*/
private void preInitializePrototype(Object prototype) {
// TODO, should this return a boolean and stop the cluster from starting?
for (Method method: prototype.getClass().getMethods()) {
if (method.isAnnotationPresent(com.nokia.dempsy.annotations.Start.class)) {
try {
method.invoke(prototype);
break; // Only allow one such method, which is checked during validation
}catch(Exception e) {
logger.error(MarkerFactory.getMarker("FATAL"), "can't run MP initializer " + method.getName(), e);
}
}
}
}
} // end Node definition
private List<Node> nodes = new ArrayList<Node>(1);
protected ClusterDefinition clusterDefinition;
private Cluster(ClusterDefinition clusterDefinition)
{
this.clusterDefinition = clusterDefinition;
allClusters.put(clusterDefinition.getClusterId(),this);
}
private void start() throws DempsyException
{
nodes.clear();
Node node = new Node(clusterDefinition);
nodes.add(node);
node.start();
}
private void stop()
{
for(Node node : nodes)
node.stop();
}
public List<Node> getNodes() { return nodes; }
/**
* This is only public for testing - DO NOT CALL!
* @throws DempsyException
*/
public void instantiateAndStartAnotherNodeForTesting() throws DempsyException
{
Node node = new Node(clusterDefinition);
nodes.add(node);
node.start();
}
} // end Cluster Definition
protected ApplicationDefinition applicationDefinition;
protected List<Cluster> appClusters = new ArrayList<Cluster>();
private List<AdaptorThread> adaptorThreads = new ArrayList<AdaptorThread>();
public Application(ApplicationDefinition applicationDefinition)
{
this.applicationDefinition = applicationDefinition;
}
private DempsyException failedStart = null;
/**
*
* @return boolean - true if starts the cluster, else false
* @throws DempsyException
*/
public boolean start() throws DempsyException
{
failedStart = null;
boolean clusterStarted = false;
for (ClusterDefinition clusterDef : applicationDefinition.getClusterDefinitions())
{
if(clusterCheck.isThisNodePartOfCluster(clusterDef.getClusterId()))
{
Cluster cluster = new Cluster(clusterDef);
appClusters.add(cluster);
}
}
List<Thread> toJoin = new ArrayList<Thread>(appClusters.size());
for (Cluster cluster : appClusters)
{
// if (multiThreadedStart)
// {
// Thread t = new Thread(new ClusterStart(cluster),"Starting cluster:" + cluster.clusterDefinition);
// toJoin.add(t);
// t.start();
// clusterStarted = true;
// }
// else
// {
cluster.start();
clusterStarted = true;
// }
}
for (Thread t : toJoin)
{
try { t.join(); } catch(InterruptedException e) { /* just continue */ }
}
if (failedStart != null)
throw failedStart;
for (Cluster cluster : appClusters)
{
if (clusterCheck.isThisNodePartOfCluster(cluster.clusterDefinition.getClusterId()))
{
Adaptor adaptor = cluster.clusterDefinition.getAdaptor();
if (adaptor != null)
{
AdaptorThread adaptorRunnable = new AdaptorThread(adaptor);
Thread thread = new Thread(adaptorRunnable , "Adaptor - " + SafeString.objectDescription(adaptor) );
adaptorThreads.add(adaptorRunnable);
if (cluster.clusterDefinition.isAdaptorDaemon())
thread.setDaemon(true);
thread.start();
clusterStarted = true;
}
else {
OutputExecuter outputExecuter = (OutputExecuter) cluster.clusterDefinition.getOutputExecuter();
if (outputExecuter != null) {
outputExecuter.start();
}
}
}
}
return clusterStarted;
}
public void stop()
{
// first stop all of the adaptor threads
for(AdaptorThread adaptorThread : adaptorThreads)
adaptorThread.stop();
// stop all of the non-adaptor clusters.
for(Cluster cluster : appClusters)
{
OutputExecuter outputExecuter = (OutputExecuter) cluster.clusterDefinition.getOutputExecuter();
if (outputExecuter != null) {
outputExecuter.stop();
}
cluster.stop();
}
}
} // end Application definition
private static class AdaptorThread implements Runnable
{
private Adaptor adaptor = null;
private Thread thread = null;
public AdaptorThread(Adaptor adaptor) { this.adaptor = adaptor; }
@Override
public void run()
{
thread = Thread.currentThread();
logger.info("Starting adaptor thread for " + SafeString.objectDescription(adaptor));
try { adaptor.start(); }
catch (Throwable th) { logger.warn("Adaptor " + SafeString.objectDescription(adaptor) + " threw an unexpected exception.", th); }
finally { logger.info("Adaptor thread for " + SafeString.objectDescription(adaptor) + " is shutting down"); }
}
/**
* This is a helper method that should stop the running thread by initiating
* a stop on the adaptor, then interrupting the thread in case it's in a
* blocking call somewhere.
*/
public void stop()
{
try { if (adaptor != null) adaptor.stop(); } catch (Throwable th) { logger.error("Problem trying to stop the Adaptor " + SafeString.objectDescription(adaptor), th); }
if (thread != null) thread.interrupt();
}
}
private List<ApplicationDefinition> applicationDefinitions = null;
protected List<Application> applications = null;
private CurrentClusterCheck clusterCheck = null;
protected ClusterInfoSessionFactory clusterSessionFactory = null;
private RoutingStrategy defaultRoutingStrategy = null;
private Serializer<Object> defaultSerializer = null;
private Transport transport = null;
private Map<ClusterId,Application.Cluster> allClusters = new HashMap<ClusterId, Application.Cluster>();
private StatsCollectorFactory defaultStatsCollectorFactory = null;
// Dempsy lifecycle state
private volatile boolean isRunning = false;
private Object isRunningEvent = new Object();
// // this is mainly for testing purposes.
// private boolean multiThreadedStart = false;
public Dempsy() { }
/**
* This is meant to be autowired by type.
*/
public void setApplicationDefinitions(List<ApplicationDefinition> applicationDefinitions)
{
this.applicationDefinitions = applicationDefinitions;
}
public synchronized void start() throws DempsyException
{
if (isRunning())
throw new DempsyException("The Dempsy application " + applicationDefinitions + " has already been started." );
if (applicationDefinitions == null || applicationDefinitions.size() == 0)
throw new DempsyException("Cannot start this application because there are no ApplicationDefinitions");
if (clusterSessionFactory == null)
throw new DempsyException("Cannot start this application because there was no ClusterFactory implementaiton set.");
if (clusterCheck == null)
throw new DempsyException("Cannot start this application because there's no way to tell which cluster to start. Make sure the appropriate " +
CurrentClusterCheck.class.getSimpleName() + " is set.");
if (defaultRoutingStrategy == null)
throw new DempsyException("Cannot start this application because there's no default routing strategy defined.");
if (defaultSerializer == null)
throw new DempsyException("Cannot start this application because there's no default serializer defined.");
if (transport == null)
throw new DempsyException("Cannot start this application because there's no transport implementation defined");
if (defaultStatsCollectorFactory == null)
throw new DempsyException("Cannot start this application because there's no default stats collector factory defined.");
try
{
applications = new ArrayList<Application>(applicationDefinitions.size());
for(ApplicationDefinition appDef: this.applicationDefinitions)
{
appDef.initialize();
if (clusterCheck.isThisNodePartOfApplication(appDef.getApplicationName()))
{
Application app = new Application(appDef);
// set the default routing strategy if there isn't one already set.
if (appDef.getRoutingStrategy() == null)
appDef.setRoutingStrategy(defaultRoutingStrategy);
if (appDef.getSerializer() == null)
appDef.setSerializer(defaultSerializer);
if (appDef.getStatsCollectorFactory() == null)
appDef.setStatsCollectorFactory(defaultStatsCollectorFactory);
applications.add(app);
}
}
boolean clusterStarted = false;
for (Application app : applications)
clusterStarted = app.start();
if(!clusterStarted)
{
throw new DempsyException("Cannot start this application because cluster defination was not found.");
}
// if we got to here we can assume we're started
synchronized(isRunningEvent) { isRunning = true; }
}
catch (RuntimeException rte)
{
logger.error("Failed to start Dempsy. Attempting to stop.");
// if something unpexpected happened then we should attempt to stop
try { stop(); } catch (Throwable th) {}
throw rte;
}
}
public synchronized void stop()
{
try
{
for(Application app : applications)
app.stop();
}
finally
{
// even though we may have had an exception, there's no way Dempsy
// can be considered still "running."
synchronized(isRunningEvent) { isRunning = false; isRunningEvent.notifyAll(); }
}
}
public ClusterInfoSessionFactory getClusterSessionFactory()
{
return clusterSessionFactory;
}
public void setClusterSessionFactory(ClusterInfoSessionFactory clusterFactory) {
this.clusterSessionFactory = clusterFactory;
}
public void setClusterCheck(CurrentClusterCheck clusterCheck)
{
this.clusterCheck = clusterCheck;
}
// public void setMultithreadedStart(boolean multiThreadedStart) { this.multiThreadedStart = multiThreadedStart; }
public void setDefaultTransport(Transport transport) { this.transport = transport; }
public void setDefaultRoutingStrategy(RoutingStrategy defaultRoutingStrategy) { this.defaultRoutingStrategy = defaultRoutingStrategy; }
public void setDefaultSerializer(Serializer<Object> defaultSerializer) { this.defaultSerializer = defaultSerializer; }
public void setDefaultStatsCollectorFactory(StatsCollectorFactory defaultfactory) { this.defaultStatsCollectorFactory = defaultfactory; }
public Application.Cluster getCluster(ClusterId clusterId)
{
return allClusters.get(clusterId);
}
public boolean isRunning() { return isRunning; }
/**
* Wait for Dempsy to be stopped. This is useful in a 'main' that needs to wait
* for an external shutdown to complete.
* @throws InterruptedException if the waiting was interrupted.
*/
public void waitToBeStopped() throws InterruptedException { waitToBeStopped(-1); }
/**
* Wait for Dempsy to be stopped for the specified time.
* @return true if Dempsy actually stopped. false if the timeout was reached.
* @throws InterruptedException if the waiting was interrupted.
*/
public boolean waitToBeStopped(long timeInMillis) throws InterruptedException
{
synchronized(isRunningEvent)
{
while (isRunning)
{
if (timeInMillis < 0)
isRunningEvent.wait();
else
isRunningEvent.wait(timeInMillis);
}
return !isRunning();
}
}
protected static List<Class<?>> getAcceptedMessages(ClusterDefinition clusterDef)
{
List<Class<?>> messageClasses = new ArrayList<Class<?>>();
Object prototype = clusterDef.getMessageProcessorPrototype();
if (prototype != null)
{
for(Method method: prototype.getClass().getMethods())
{
if(method.isAnnotationPresent(com.nokia.dempsy.annotations.MessageHandler.class))
{
for(Class<?> messageType : method.getParameterTypes())
{
messageClasses.add(messageType);
}
}
}
}
return messageClasses;
}
}