aboutsummaryrefslogtreecommitdiffstats
path: root/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java
blob: 152425711df184c87137044ef7f761371660049f (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
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2019 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.service.engine.runtime.impl;

import java.io.ByteArrayInputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.onap.policy.apex.context.ContextException;
import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
import org.onap.policy.apex.service.engine.event.ApexEvent;
import org.onap.policy.apex.service.engine.event.ApexPeriodicEventGenerator;
import org.onap.policy.apex.service.engine.runtime.ApexEventListener;
import org.onap.policy.apex.service.engine.runtime.EngineService;
import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface;
import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters;
import org.onap.policy.common.parameters.GroupValidationResult;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

/**
 * The Class EngineServiceImpl controls a thread pool that runs a set of Apex engine workers, each of which is running
 * on an identical Apex model. This class handles the management of the engine worker instances, their threads, and
 * event forwarding to and from the engine workers.
 *
 * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
 * @author Liam Fallon (liam.fallon@ericsson.com)
 * @author John Keeney (john.keeney@ericsson.com)
 */
public final class EngineServiceImpl implements EngineService, EngineServiceEventInterface {
    // Logging static variables
    private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineServiceImpl.class);
    private static final boolean DEBUG_ENABLED = LOGGER.isDebugEnabled();

    // Recurring string constants
    private static final String ENGINE_KEY_PREAMBLE = "engine with key ";
    private static final String NOT_FOUND_SUFFIX = " not found in engine service";
    private static final String ENGINE_KEY_NOT_SPECIFIED = "engine key must be specified and may not be null";

    // Constants for timing
    private static final long MAX_START_WAIT_TIME = 5000; // 5 seconds
    private static final long MAX_STOP_WAIT_TIME = 5000; // 5 seconds
    private static final int ENGINE_SERVICE_STOP_START_WAIT_INTERVAL = 200;

    // The ID of this engine
    private AxArtifactKey engineServiceKey = null;

    // The Apex engine workers this engine service is handling
    private final Map<AxArtifactKey, EngineService> engineWorkerMap = Collections
                    .synchronizedMap(new LinkedHashMap<AxArtifactKey, EngineService>());

    // Event queue for events being sent into the Apex engines, it used by all engines within a
    // group.
    private final BlockingQueue<ApexEvent> queue = new LinkedBlockingQueue<>();

    // Thread factory for thread management
    private final ApplicationThreadFactory atFactory = new ApplicationThreadFactory("apex-engine-service", 512);

    // Periodic event generator and its period in milliseconds
    private ApexPeriodicEventGenerator periodicEventGenerator = null;
    private long periodicEventPeriod;

    /**
     * This constructor instantiates engine workers and adds them to the set of engine workers to be managed. The
     * constructor is private to prevent subclassing.
     *
     * @param engineServiceKey the engine service key
     * @param threadCount the thread count, the number of engine workers to start
     * @param periodicEventPeriod the period in milliseconds at which periodic events are generated
     * @throws ApexException on worker instantiation errors
     */
    private EngineServiceImpl(final AxArtifactKey engineServiceKey, final int threadCount,
                    final long periodicEventPeriod) {
        LOGGER.entry(engineServiceKey, threadCount);

        this.engineServiceKey = engineServiceKey;
        this.periodicEventPeriod = periodicEventPeriod;

        // Start engine workers
        for (int engineCounter = 0; engineCounter < threadCount; engineCounter++) {
            final AxArtifactKey engineWorkerKey = new AxArtifactKey(engineServiceKey.getName() + '-' + engineCounter,
                            engineServiceKey.getVersion());
            engineWorkerMap.put(engineWorkerKey, new EngineWorker(engineWorkerKey, queue, atFactory));
            LOGGER.info("Created apex engine {} .", engineWorkerKey.getId());
        }

        LOGGER.info("APEX service created.");
        LOGGER.exit();
    }

    /**
     * Create an Apex Engine Service instance. This method does not load the policy so
     * {@link #updateModel(AxArtifactKey, AxPolicyModel, boolean)} or
     * {@link #updateModel(AxArtifactKey, AxPolicyModel, boolean)} must be used to load a model. This method does not
     * start the Engine Service so {@link #start(AxArtifactKey)} or {@link #startAll()} must be used.
     *
     * @param config the configuration for this Apex Engine Service.
     * @return the Engine Service instance
     * @throws ApexException on worker instantiation errors
     */
    public static EngineServiceImpl create(final EngineServiceParameters config) throws ApexException {
        if (config == null) {
            LOGGER.warn("Engine service configuration parameters is null");
            throw new ApexException("engine service configuration parameters are null");
        }

        final GroupValidationResult validation = config.validate();
        if (!validation.isValid()) {
            LOGGER.warn("Invalid engine service configuration parameters: {}" + validation.getResult());
            throw new ApexException("Invalid engine service configuration parameters: " + validation);
        }

        final AxArtifactKey engineServiceKey = config.getEngineKey();
        final int threadCount = config.getInstanceCount();

        return new EngineServiceImpl(engineServiceKey, threadCount, config.getPeriodicEventPeriod());
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void registerActionListener(final String listenerName, final ApexEventListener apexEventListener) {
        LOGGER.entry(apexEventListener);

        if (listenerName == null) {
            String message = "listener name must be specified and may not be null";
            LOGGER.warn(message);
            return;
        }

        if (apexEventListener == null) {
            String message = "apex event listener must be specified and may not be null";
            LOGGER.warn(message);
            return;
        }

        // Register the Apex event listener on all engine workers, each worker will return Apex
        // events to the listening application
        for (final EngineService engineWorker : engineWorkerMap.values()) {
            engineWorker.registerActionListener(listenerName, apexEventListener);
        }

        LOGGER.info("Added the action listener to the engine");
        LOGGER.exit();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void deregisterActionListener(final String listenerName) {
        LOGGER.entry(listenerName);

        // Register the Apex event listener on all engine workers, each worker will return Apex
        // events to the listening application
        for (final EngineService engineWorker : engineWorkerMap.values()) {
            engineWorker.deregisterActionListener(listenerName);
        }

        LOGGER.info("Removed the action listener from the engine");
        LOGGER.exit();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public EngineServiceEventInterface getEngineServiceEventInterface() {
        return this;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public AxArtifactKey getKey() {
        return engineServiceKey;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public Collection<AxArtifactKey> getEngineKeys() {
        return engineWorkerMap.keySet();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public AxArtifactKey getApexModelKey() {
        if (engineWorkerMap.size() == 0) {
            return null;
        }

        return engineWorkerMap.entrySet().iterator().next().getValue().getApexModelKey();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void updateModel(final AxArtifactKey incomingEngineServiceKey, final String apexModelString,
                    final boolean forceFlag) throws ApexException {
        AxPolicyModel apexPolicyModel = createModel(incomingEngineServiceKey, apexModelString);

        // Update the model
        updateModel(incomingEngineServiceKey, apexPolicyModel, forceFlag);

        LOGGER.exit();
    }

    /**
    * Method to create model.
    *
    * @param incomingEngineServiceKey incoming engine service key
    * @param apexModelString apex model string
    * @return apexPolicyModel the policy model
    * @throws ApexException apex exception
    */
    public static AxPolicyModel createModel(final AxArtifactKey incomingEngineServiceKey, final String apexModelString)
        throws ApexException {
        // Check if the engine service key specified is sane
        if (incomingEngineServiceKey == null) {
            String message = ENGINE_KEY_NOT_SPECIFIED;
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        // Check if the Apex model specified is sane
        if (apexModelString == null || apexModelString.trim().length() == 0) {
            String emptyModelMessage = "model for updating engine service with key "
                            + incomingEngineServiceKey.getId() + " is empty";
            LOGGER.warn(emptyModelMessage);
            throw new ApexException(emptyModelMessage);
        }

        // Read the Apex model into memory using the Apex Model Reader
        AxPolicyModel apexPolicyModel = null;
        try {
            final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class);
            apexPolicyModel = modelReader.read(new ByteArrayInputStream(apexModelString.getBytes()));
        } catch (final ApexModelException e) {
            String message = "failed to unmarshal the apex model on engine service " + incomingEngineServiceKey.getId();
            LOGGER.error(message, e);
            throw new ApexException(message, e);
        }
        return apexPolicyModel;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void updateModel(final AxArtifactKey incomingEngineServiceKey, final AxPolicyModel apexModel,
                    final boolean forceFlag) throws ApexException {
        LOGGER.entry(incomingEngineServiceKey);

        // Check if the engine service key specified is sane
        if (incomingEngineServiceKey == null) {
            String message = ENGINE_KEY_NOT_SPECIFIED;
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        // Check if the Apex model specified is sane
        if (apexModel == null) {
            LOGGER.warn("model for updating on engine service with key " + incomingEngineServiceKey.getId()
                            + " is null");
            throw new ApexException("model for updating on engine service with key " + incomingEngineServiceKey.getId()
                            + " is null");
        }

        // Check if the key on the update request is correct
        if (!this.engineServiceKey.equals(incomingEngineServiceKey)) {
            LOGGER.warn("engine service key " + incomingEngineServiceKey.getId() + " does not match the key"
                            + engineServiceKey.getId() + " of this engine service");
            throw new ApexException("engine service key " + incomingEngineServiceKey.getId() + " does not match the key"
                            + engineServiceKey.getId() + " of this engine service");
        }

        // Check model compatibility
        if (ModelService.existsModel(AxPolicyModel.class)) {
            // The current policy model may or may not be defined
            final AxPolicyModel currentModel = ModelService.getModel(AxPolicyModel.class);
            if (!currentModel.getKey().isCompatible(apexModel.getKey())) {
                handleIncompatibility(apexModel, forceFlag, currentModel);
            }
        }

        executeModelUpdate(incomingEngineServiceKey, apexModel, forceFlag);

        LOGGER.exit();
    }

    /**
     * Execute the model update on the engine instances.
     *
     * @param incomingEngineServiceKey the engine service key to update
     * @param apexModel the model to update the engines with
     * @param forceFlag if true, ignore compatibility problems
     * @throws ApexException on model update errors
     */
    private void executeModelUpdate(final AxArtifactKey incomingEngineServiceKey, final AxPolicyModel apexModel,
                    final boolean forceFlag) throws ApexException {

        if (!isStopped()) {
            stopEngines(incomingEngineServiceKey);
        }

        // Update the engines
        for (final Entry<AxArtifactKey, EngineService> engineWorkerEntry : engineWorkerMap.entrySet()) {
            LOGGER.info("Registering apex model on engine {}", engineWorkerEntry.getKey().getId());
            engineWorkerEntry.getValue().updateModel(engineWorkerEntry.getKey(), apexModel, forceFlag);
        }

        // start all engines on this engine service if it was not stopped before the update
        startAll();
        final long starttime = System.currentTimeMillis();
        while (!isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT_TIME) {
            ThreadUtilities.sleep(ENGINE_SERVICE_STOP_START_WAIT_INTERVAL);
        }
        // Check if all engines are running
        final StringBuilder notRunningEngineIdBuilder = new StringBuilder();
        for (final Entry<AxArtifactKey, EngineService> engineWorkerEntry : engineWorkerMap.entrySet()) {
            if (engineWorkerEntry.getValue().getState() != AxEngineState.READY
                            && engineWorkerEntry.getValue().getState() != AxEngineState.EXECUTING) {
                notRunningEngineIdBuilder.append(engineWorkerEntry.getKey().getId());
                notRunningEngineIdBuilder.append('(');
                notRunningEngineIdBuilder.append(engineWorkerEntry.getValue().getState());
                notRunningEngineIdBuilder.append(") ");
            }
        }
        if (notRunningEngineIdBuilder.length() > 0) {
            final String errorString = "engine start error on model update on engine service with key "
                            + incomingEngineServiceKey.getId() + ", engines not running are: "
                            + notRunningEngineIdBuilder.toString().trim();
            LOGGER.warn(errorString);
            throw new ApexException(errorString);
        }
    }

    /**
     * Stop engines for a model update.
     * @param incomingEngineServiceKey the engine service key for the engines that are to be stopped
     * @throws ApexException on errors stopping engines
     */
    private void stopEngines(final AxArtifactKey incomingEngineServiceKey) throws ApexException {
        // Stop all engines on this engine service
        stop();
        final long stoptime = System.currentTimeMillis();
        while (!isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT_TIME) {
            ThreadUtilities.sleep(ENGINE_SERVICE_STOP_START_WAIT_INTERVAL);
        }
        // Check if all engines are stopped
        final StringBuilder notStoppedEngineIdBuilder = new StringBuilder();
        for (final Entry<AxArtifactKey, EngineService> engineWorkerEntry : engineWorkerMap.entrySet()) {
            if (engineWorkerEntry.getValue().getState() != AxEngineState.STOPPED) {
                notStoppedEngineIdBuilder.append(engineWorkerEntry.getKey().getId());
                notStoppedEngineIdBuilder.append('(');
                notStoppedEngineIdBuilder.append(engineWorkerEntry.getValue().getState());
                notStoppedEngineIdBuilder.append(") ");
            }
        }
        if (notStoppedEngineIdBuilder.length() > 0) {
            final String errorString = "cannot update model on engine service with key "
                            + incomingEngineServiceKey.getId() + ", engines not stopped after " + MAX_STOP_WAIT_TIME
                            + "ms are: " + notStoppedEngineIdBuilder.toString().trim();
            LOGGER.warn(errorString);
            throw new ApexException(errorString);
        }
    }

    /**
     * Issue compatibility warning or error message.
     * @param apexModel The model name
     * @param forceFlag true if we are forcing the update
     * @param currentModel the existing model that is loaded
     * @throws ContextException on compatibility errors
     */
    private void handleIncompatibility(final AxPolicyModel apexModel, final boolean forceFlag,
                    final AxPolicyModel currentModel) throws ContextException {
        if (forceFlag) {
            LOGGER.warn("apex model update forced, supplied model with key \"" + apexModel.getKey().getId()
                            + "\" is not a compatible model update from the existing engine model with key \""
                            + currentModel.getKey().getId() + "\"");
        } else {
            throw new ContextException("apex model update failed, supplied model with key \""
                            + apexModel.getKey().getId()
                            + "\" is not a compatible model update from the existing engine model with key \""
                            + currentModel.getKey().getId() + "\"");
        }
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public AxEngineState getState() {
        // If one worker is running then we are running, otherwise we are stopped
        for (final EngineService engine : engineWorkerMap.values()) {
            if (engine.getState() != AxEngineState.STOPPED) {
                return AxEngineState.EXECUTING;
            }
        }

        return AxEngineState.STOPPED;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void startAll() throws ApexException {
        for (final EngineService engine : engineWorkerMap.values()) {
            start(engine.getKey());
        }
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void start(final AxArtifactKey engineKey) throws ApexException {
        LOGGER.entry(engineKey);

        if (engineKey == null) {
            String message = ENGINE_KEY_NOT_SPECIFIED;
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        // Check if we have this key on our map
        if (!engineWorkerMap.containsKey(engineKey)) {
            String message = ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX;
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        // Start the engine
        engineWorkerMap.get(engineKey).start(engineKey);

        // Check if periodic events should be turned on
        if (periodicEventPeriod > 0) {
            startPeriodicEvents(periodicEventPeriod);
        }

        LOGGER.exit(engineKey);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void stop() throws ApexException {
        LOGGER.entry();

        if (periodicEventGenerator != null) {
            periodicEventGenerator.cancel();
            periodicEventGenerator = null;
        }

        // Stop each engine
        for (final EngineService engine : engineWorkerMap.values()) {
            if (engine.getState() != AxEngineState.STOPPED) {
                engine.stop();
            }
        }

        LOGGER.exit();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void stop(final AxArtifactKey engineKey) throws ApexException {
        LOGGER.entry(engineKey);

        if (engineKey == null) {
            String message = ENGINE_KEY_NOT_SPECIFIED;
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        // Check if we have this key on our map
        if (!engineWorkerMap.containsKey(engineKey)) {
            LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX);
            throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX);
        }

        // Stop the engine
        engineWorkerMap.get(engineKey).stop(engineKey);

        LOGGER.exit(engineKey);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void clear() throws ApexException {
        LOGGER.entry();

        // Stop each engine
        for (final EngineService engine : engineWorkerMap.values()) {
            if (engine.getState() == AxEngineState.STOPPED) {
                engine.clear();
            }
        }

        LOGGER.exit();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void clear(final AxArtifactKey engineKey) throws ApexException {
        LOGGER.entry(engineKey);

        if (engineKey == null) {
            String message = ENGINE_KEY_NOT_SPECIFIED;
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        // Check if we have this key on our map
        if (!engineWorkerMap.containsKey(engineKey)) {
            LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX);
            throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX);
        }

        // Clear the engine
        if (engineWorkerMap.get(engineKey).getState() == AxEngineState.STOPPED) {
            engineWorkerMap.get(engineKey).stop(engineKey);
        }

        LOGGER.exit(engineKey);
    }

    /**
     * Check all engines are started.
     *
     * @return true if <i>all</i> engines are started
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#isStarted()
     */
    @Override
    public boolean isStarted() {
        for (final EngineService engine : engineWorkerMap.values()) {
            if (!engine.isStarted()) {
                return false;
            }
        }
        return true;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public boolean isStarted(final AxArtifactKey engineKey) {
        if (engineKey == null) {
            String message = ENGINE_KEY_NOT_SPECIFIED;
            LOGGER.warn(message);
            return false;
        }

        // Check if we have this key on our map
        if (!engineWorkerMap.containsKey(engineKey)) {
            LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX);
            return false;
        }
        return engineWorkerMap.get(engineKey).isStarted();
    }

    /**
     * Check all engines are stopped.
     *
     * @return true if <i>all</i> engines are stopped
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#isStopped()
     */
    @Override
    public boolean isStopped() {
        for (final EngineService engine : engineWorkerMap.values()) {
            if (!engine.isStopped()) {
                return false;
            }
        }
        return true;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public boolean isStopped(final AxArtifactKey engineKey) {
        if (engineKey == null) {
            String message = ENGINE_KEY_NOT_SPECIFIED;
            LOGGER.warn(message);
            return true;
        }

        // Check if we have this key on our map
        if (!engineWorkerMap.containsKey(engineKey)) {
            LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX);
            return true;
        }
        return engineWorkerMap.get(engineKey).isStopped();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void startPeriodicEvents(final long period) throws ApexException {
        // Check if periodic events are already started
        if (periodicEventGenerator != null) {
            String message = "Peiodic event geneation already running on engine " + engineServiceKey.getId() + ", "
                            + periodicEventGenerator.toString();
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        // Set up periodic event execution, its a Java Timer/TimerTask
        periodicEventGenerator = new ApexPeriodicEventGenerator(this.getEngineServiceEventInterface(), period);

        // Record the periodic event period because it may have been set over the Web Socket admin
        // interface
        this.periodicEventPeriod = period;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void stopPeriodicEvents() throws ApexException {
        // Check if periodic events are already started
        if (periodicEventGenerator == null) {
            LOGGER.warn("Peiodic event geneation not running on engine " + engineServiceKey.getId());
            throw new ApexException("Peiodic event geneation not running on engine " + engineServiceKey.getId());
        }

        // Stop periodic events
        periodicEventGenerator.cancel();
        periodicEventGenerator = null;
        periodicEventPeriod = 0;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public String getStatus(final AxArtifactKey engineKey) throws ApexException {
        if (engineKey == null) {
            String message = ENGINE_KEY_NOT_SPECIFIED;
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        // Check if we have this key on our map
        if (!engineWorkerMap.containsKey(engineKey)) {
            LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX);
            throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX);
        }

        // Return the information for this worker
        return engineWorkerMap.get(engineKey).getStatus(engineKey);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public String getRuntimeInfo(final AxArtifactKey engineKey) throws ApexException {
        if (engineKey == null) {
            String message = ENGINE_KEY_NOT_SPECIFIED;
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        // Check if we have this key on our map
        if (!engineWorkerMap.containsKey(engineKey)) {
            LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX);
            throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX);
        }

        // Return the information for this worker
        return engineWorkerMap.get(engineKey).getRuntimeInfo(engineKey);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void sendEvent(final ApexEvent event) {
        if (event == null) {
            LOGGER.warn("Null events cannot be processed, in engine service " + engineServiceKey.getId());
            return;
        }

        // Check if we have this key on our map
        if (getState() == AxEngineState.STOPPED) {
            LOGGER.warn("event " + event.getName() + " not processed, no engines on engine service "
                            + engineServiceKey.getId() + " are running");
            return;
        }

        if (DEBUG_ENABLED) {
            LOGGER.debug("Forwarding Apex Event {} to the processing engine", event);
        }

        // Add the incoming event to the queue, the next available worker will process it
        queue.add(event);
    }
}