Changes for checkstyle 8.32
[policy/apex-pdp.git] / services / services-engine / src / main / java / org / onap / policy / apex / service / engine / runtime / impl / EngineWorker.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.service.engine.runtime.impl;
23
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonElement;
27 import com.google.gson.JsonParser;
28 import java.io.ByteArrayInputStream;
29 import java.io.ByteArrayOutputStream;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.concurrent.BlockingQueue;
37 import lombok.Setter;
38 import org.onap.policy.apex.context.ContextException;
39 import org.onap.policy.apex.context.ContextRuntimeException;
40 import org.onap.policy.apex.context.SchemaHelper;
41 import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory;
42 import org.onap.policy.apex.core.engine.engine.ApexEngine;
43 import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory;
44 import org.onap.policy.apex.core.engine.event.EnEvent;
45 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
46 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
47 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
48 import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
49 import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
50 import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
51 import org.onap.policy.apex.model.basicmodel.service.ModelService;
52 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
53 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums;
54 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
55 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
56 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
57 import org.onap.policy.apex.service.engine.event.ApexEvent;
58 import org.onap.policy.apex.service.engine.event.impl.enevent.ApexEvent2EnEventConverter;
59 import org.onap.policy.apex.service.engine.main.ApexPolicyStatisticsManager;
60 import org.onap.policy.apex.service.engine.runtime.ApexEventListener;
61 import org.onap.policy.apex.service.engine.runtime.EngineService;
62 import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface;
63 import org.slf4j.ext.XLogger;
64 import org.slf4j.ext.XLoggerFactory;
65
66 /**
67  * The Class EngineWorker encapsulates a core {@link ApexEngine} instance, which runs policies defined in the
68  * {@link org.onap.policy.apex.model.basicmodel.concepts.AxModelAxModel}. Each policy is triggered by an Apex event, and
69  * when the policy is triggered it runs through to completion in the ApexEngine.
70  *
71  * <p>This class acts as a container for an {@link ApexEngine}, running it in a thread, sending it events, and receiving
72  * events from it.
73  *
74  * @author Liam Fallon (liam.fallon@ericsson.com)
75  */
76 final class EngineWorker implements EngineService {
77     // Logger for this class
78     private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineService.class);
79
80     // Recurring string constants
81     private static final String ENGINE_FOR_KEY_PREFIX = "apex engine for engine key ";
82     private static final String ENGINE_SUFFIX = " of this engine";
83     private static final String BAD_KEY_MATCH_TAG = " does not match the key";
84     private static final String ENGINE_KEY_PREFIX = "engine key ";
85
86     // The ID of this engine
87     private final AxArtifactKey engineWorkerKey;
88
89     // The Apex engine which is running the policies in this worker
90     private final ApexEngine engine;
91
92     // The event processor is an inner class, an instance of which runs as a thread that reads
93     // incoming events from a queue and forwards them to the Apex engine
94     private EventProcessor processor = null;
95
96     // Thread handling for the worker
97     private final ApplicationThreadFactory threadFactory;
98     private Thread processorThread;
99
100     // Converts ApexEvent instances to and from EnEvent instances
101     private ApexEvent2EnEventConverter apexEnEventConverter = null;
102
103     @Setter
104     private boolean isSubsequentInstance;
105
106     /**
107      * Constructor that creates an Apex engine, an event processor for events to be sent to that engine, and an
108      * {@link ApexModelReader} instance to read Apex models using JAXB.
109      *
110      * @param engineWorkerKey the engine worker key
111      * @param queue the queue on which events for this Apex worker will come
112      * @param threadFactory the thread factory to use for creating the event processing thread
113      * @throws ApexException thrown on errors on worker instantiation
114      */
115     protected EngineWorker(final AxArtifactKey engineWorkerKey, final BlockingQueue<ApexEvent> queue,
116             final ApplicationThreadFactory threadFactory) {
117         LOGGER.entry(engineWorkerKey);
118
119         this.engineWorkerKey = engineWorkerKey;
120         this.threadFactory = threadFactory;
121
122         // Create the Apex engine
123         engine = new ApexEngineFactory().createApexEngine(engineWorkerKey);
124
125         // Create and run the event processor
126         processor = new EventProcessor(queue);
127
128         // Set the Event converter up
129         apexEnEventConverter = new ApexEvent2EnEventConverter(engine);
130
131         LOGGER.exit();
132     }
133
134     /**
135      * {@inheritDoc}.
136      */
137     @Override
138     public void registerActionListener(final String listenerName, final ApexEventListener apexEventListener) {
139         engine.addEventListener(listenerName, new EnEventListenerImpl(apexEventListener, apexEnEventConverter));
140     }
141
142     /**
143      * {@inheritDoc}.
144      */
145     @Override
146     public void deregisterActionListener(final String listenerName) {
147         engine.removeEventListener(listenerName);
148     }
149
150     /**
151      * {@inheritDoc}.
152      */
153     @Override
154     public EngineServiceEventInterface getEngineServiceEventInterface() {
155         throw new UnsupportedOperationException(
156                 "getEngineServiceEventInterface() call is not allowed on an Apex Engine Worker");
157     }
158
159     /**
160      * {@inheritDoc}.
161      */
162     @Override
163     public AxArtifactKey getKey() {
164         return engineWorkerKey;
165     }
166
167     /**
168      * {@inheritDoc}.
169      */
170     @Override
171     public Collection<AxArtifactKey> getEngineKeys() {
172         return Arrays.asList(engineWorkerKey);
173     }
174
175     /**
176      * {@inheritDoc}.
177      */
178     @Override
179     public AxArtifactKey getApexModelKey() {
180         if (ModelService.existsModel(AxPolicyModel.class)) {
181             return ModelService.getModel(AxPolicyModel.class).getKey();
182         } else {
183             return null;
184         }
185     }
186
187     /**
188      * {@inheritDoc}.
189      */
190     @Override
191     public void updateModel(final AxArtifactKey engineKey, final String engineModel, final boolean forceFlag)
192             throws ApexException {
193         LOGGER.entry(engineKey);
194
195         // Read the Apex model into memory using the Apex Model Reader
196         AxPolicyModel apexPolicyModel = null;
197         try {
198             final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class);
199             apexPolicyModel = modelReader.read(new ByteArrayInputStream(engineModel.getBytes()));
200         } catch (final ApexModelException e) {
201             throw new ApexException("failed to unmarshal the apex model on engine " + engineKey.getId(), e);
202         }
203
204         // Update the Apex model in the Apex engine
205         updateModel(engineKey, apexPolicyModel, forceFlag);
206
207         LOGGER.exit();
208     }
209
210     /**
211      * {@inheritDoc}.
212      */
213     @Override
214     public void updateModel(final AxArtifactKey engineKey, final AxPolicyModel apexModel, final boolean forceFlag)
215             throws ApexException {
216         LOGGER.entry(engineKey);
217
218         // Check if the key on the update request is correct
219         if (!engineWorkerKey.equals(engineKey)) {
220             String message =
221                     ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX;
222             throw new ApexException(message);
223         }
224
225         // Check model compatibility
226         if (ModelService.existsModel(AxPolicyModel.class)) {
227             // The current policy model may or may not be defined
228             final AxPolicyModel currentModel = ModelService.getModel(AxPolicyModel.class);
229             if (!currentModel.getKey().isCompatible(apexModel.getKey())) {
230                 if (forceFlag) {
231                     LOGGER.warn(
232                             "apex model update forced, supplied model with key \"{}\" is not a compatible model update "
233                                     + "from the existing engine model with key \"{}\"",
234                             apexModel.getKey().getId(), currentModel.getKey().getId());
235                 } else {
236                     throw new ContextException(
237                             "apex model update failed, supplied model with key \"" + apexModel.getKey().getId()
238                                     + "\" is not a compatible model update from the existing engine model with key \""
239                                     + currentModel.getKey().getId() + "\"");
240                 }
241             }
242         }
243         // Update the Apex model in the Apex engine
244         engine.updateModel(apexModel, isSubsequentInstance);
245
246         LOGGER.debug("engine model {} added to the engine-{}", apexModel.getKey().getId(), engineWorkerKey);
247         LOGGER.exit();
248     }
249
250     /**
251      * {@inheritDoc}.
252      */
253     @Override
254     public AxEngineState getState() {
255         return engine.getState();
256     }
257
258     /**
259      * {@inheritDoc}.
260      */
261     @Override
262     public void startAll() throws ApexException {
263         start(this.getKey());
264     }
265
266     /**
267      * {@inheritDoc}.
268      */
269     @Override
270     public void start(final AxArtifactKey engineKey) throws ApexException {
271         LOGGER.entry(engineKey);
272
273         // Check if the key on the start request is correct
274         if (!engineWorkerKey.equals(engineKey)) {
275             throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
276                     + ENGINE_SUFFIX);
277         }
278
279         // Starts the event processing thread that handles incoming events
280         if (processorThread != null && processorThread.isAlive()) {
281             String message =
282                     ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already running with state " + getState();
283             LOGGER.error(message);
284             throw new ApexException(message);
285         }
286
287         // Start the engine
288         engine.start();
289
290         // Start a thread to process events for the engine
291         processorThread = threadFactory.newThread(processor);
292         processorThread.start();
293
294         LOGGER.exit(engineKey);
295     }
296
297     /**
298      * {@inheritDoc}.
299      */
300     @Override
301     public void stop() throws ApexException {
302         stop(this.getKey());
303     }
304
305     /**
306      * {@inheritDoc}.
307      */
308     @Override
309     public void stop(final AxArtifactKey engineKey) throws ApexException {
310         // Check if the key on the start request is correct
311         if (!engineWorkerKey.equals(engineKey)) {
312             LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
313                     + ENGINE_SUFFIX);
314             throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
315                     + ENGINE_SUFFIX);
316         }
317
318         // Interrupt the worker to stop its thread
319         if (processorThread == null || !processorThread.isAlive()) {
320             processorThread = null;
321
322             LOGGER.warn(
323                     ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already stopped with state " + getState());
324             return;
325         }
326
327         // Interrupt the thread that is handling events toward the engine
328         processorThread.interrupt();
329         processorThread = null;
330
331         // Stop the engine
332         engine.stop();
333
334         LOGGER.exit(engineKey);
335     }
336
337     /**
338      * {@inheritDoc}.
339      */
340     @Override
341     public void clear() throws ApexException {
342         clear(this.getKey());
343     }
344
345     /**
346      * {@inheritDoc}.
347      */
348     @Override
349     public void clear(final AxArtifactKey engineKey) throws ApexException {
350         // Check if the key on the start request is correct
351         if (!engineWorkerKey.equals(engineKey)) {
352             LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
353                     + ENGINE_SUFFIX);
354             throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
355                     + ENGINE_SUFFIX);
356         }
357
358         // Interrupt the worker to stop its thread
359         if (processorThread != null && !processorThread.isAlive()) {
360             LOGGER.warn(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is not stopped with state " + getState());
361             return;
362         }
363
364         // Clear the engine
365         engine.clear();
366
367         LOGGER.exit(engineKey);
368     }
369
370     /**
371      * {@inheritDoc}.
372      */
373     @Override
374     public boolean isStarted() {
375         return isStarted(this.getKey());
376     }
377
378     /**
379      * {@inheritDoc}.
380      */
381     @Override
382     public boolean isStarted(final AxArtifactKey engineKey) {
383         final AxEngineState engstate = getState();
384         switch (engstate) {
385             case STOPPED:
386             case STOPPING:
387             case UNDEFINED:
388                 return false;
389             case EXECUTING:
390             case READY:
391                 return processorThread != null && processorThread.isAlive() && !processorThread.isInterrupted();
392             default:
393                 break;
394         }
395         return false;
396     }
397
398     /**
399      * {@inheritDoc}.
400      */
401     @Override
402     public boolean isStopped() {
403         return isStopped(this.getKey());
404     }
405
406     /**
407      * {@inheritDoc}.
408      */
409     @Override
410     public boolean isStopped(final AxArtifactKey engineKey) {
411         final AxEngineState engstate = getState();
412         switch (engstate) {
413             case STOPPING:
414             case UNDEFINED:
415             case EXECUTING:
416             case READY:
417                 return false;
418             case STOPPED:
419                 return processorThread == null || !processorThread.isAlive();
420             default:
421                 break;
422         }
423         return false;
424     }
425
426     /**
427      * {@inheritDoc}.
428      */
429     @Override
430     public void startPeriodicEvents(final long period) {
431         throw new UnsupportedOperationException("startPeriodicEvents() call is not allowed on an Apex Engine Worker");
432     }
433
434     /**
435      * {@inheritDoc}.
436      */
437     @Override
438     public void stopPeriodicEvents() {
439         throw new UnsupportedOperationException("stopPeriodicEvents() call is not allowed on an Apex Engine Worker");
440     }
441
442     /**
443      * {@inheritDoc}.
444      */
445     @Override
446     public String getStatus(final AxArtifactKey engineKey) {
447         // Get the information from the engine that we want to return
448         final AxEngineModel apexEngineModel = engine.getEngineStatus();
449         apexEngineModel.getKeyInformation().generateKeyInfo(apexEngineModel);
450
451         // Convert that information into a string
452         try {
453             final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
454             final ApexModelWriter<AxEngineModel> modelWriter = new ApexModelWriter<>(AxEngineModel.class);
455             modelWriter.setJsonOutput(true);
456             modelWriter.write(apexEngineModel, baOutputStream);
457             return baOutputStream.toString();
458         } catch (final Exception e) {
459             LOGGER.warn("error outputting runtime information for engine {}", engineWorkerKey, e);
460             return null;
461         }
462     }
463
464     /**
465      * {@inheritDoc}.
466      */
467     @Override
468     public List<AxEngineModel> getEngineStats() {
469         List<AxEngineModel> engineStats = new ArrayList<>();
470         engineStats.add(engine.getEngineStatus());
471         return engineStats;
472     }
473
474     /**
475      * {@inheritDoc}.
476      */
477     @Override
478     public String getRuntimeInfo(final AxArtifactKey engineKey) {
479         // We'll build up the JSON string for runtime information bit by bit
480         final StringBuilder runtimeJsonStringBuilder = new StringBuilder();
481
482         // Get the engine information
483         final AxEngineModel engineModel = engine.getEngineStatus();
484         final Map<AxArtifactKey, Map<String, Object>> engineContextAlbums = engine.getEngineContext();
485
486         // Use GSON to convert our context information into JSON
487         final Gson gson = new GsonBuilder().setPrettyPrinting().create();
488
489         // Get context into a JSON string
490         runtimeJsonStringBuilder.append("{\"TimeStamp\":");
491         runtimeJsonStringBuilder.append(engineModel.getTimestamp());
492         runtimeJsonStringBuilder.append(",\"State\":");
493         runtimeJsonStringBuilder.append(engineModel.getState());
494         runtimeJsonStringBuilder.append(",\"Stats\":");
495         runtimeJsonStringBuilder.append(gson.toJson(engineModel.getStats()));
496
497         // Get context into a JSON string
498         runtimeJsonStringBuilder.append(",\"ContextAlbums\":[");
499
500         boolean firstAlbum = true;
501         for (final Entry<AxArtifactKey, Map<String, Object>> contextAlbumEntry : engineContextAlbums.entrySet()) {
502             if (firstAlbum) {
503                 firstAlbum = false;
504             } else {
505                 runtimeJsonStringBuilder.append(",");
506             }
507
508             runtimeJsonStringBuilder.append("{\"AlbumKey\":");
509             runtimeJsonStringBuilder.append(gson.toJson(contextAlbumEntry.getKey()));
510             runtimeJsonStringBuilder.append(",\"AlbumContent\":[");
511
512             // Get the schema helper to use to marshal context album objects to JSON
513             final AxContextAlbum axContextAlbum =
514                     ModelService.getModel(AxContextAlbums.class).get(contextAlbumEntry.getKey());
515             SchemaHelper schemaHelper = null;
516
517             try {
518                 // Get a schema helper to manage the translations between objects on the album map
519                 // for this album
520                 schemaHelper = new SchemaHelperFactory().createSchemaHelper(axContextAlbum.getKey(),
521                         axContextAlbum.getItemSchema());
522             } catch (final ContextRuntimeException e) {
523                 final String resultString =
524                         "could not find schema helper to marshal context album \"" + axContextAlbum + "\" to JSON";
525                 LOGGER.warn(resultString, e);
526
527                 // End of context album entry
528                 runtimeJsonStringBuilder.append(resultString);
529                 runtimeJsonStringBuilder.append("]}");
530
531                 continue;
532             }
533
534             boolean firstEntry = true;
535             for (final Entry<String, Object> contextEntry : contextAlbumEntry.getValue().entrySet()) {
536                 if (firstEntry) {
537                     firstEntry = false;
538                 } else {
539                     runtimeJsonStringBuilder.append(",");
540                 }
541                 runtimeJsonStringBuilder.append("{\"EntryName\":");
542                 runtimeJsonStringBuilder.append(gson.toJson(contextEntry.getKey()));
543                 runtimeJsonStringBuilder.append(",\"EntryContent\":");
544                 runtimeJsonStringBuilder.append(gson.toJson(schemaHelper.marshal2String(contextEntry.getValue())));
545
546                 // End of context entry
547                 runtimeJsonStringBuilder.append("}");
548             }
549
550             // End of context album entry
551             runtimeJsonStringBuilder.append("]}");
552         }
553
554         runtimeJsonStringBuilder.append("]}");
555
556         // Tidy up the JSON string
557         final JsonElement jsonElement = JsonParser.parseString(runtimeJsonStringBuilder.toString());
558         final String tidiedRuntimeString = gson.toJson(jsonElement);
559
560         LOGGER.debug("runtime information={}", tidiedRuntimeString);
561
562         return tidiedRuntimeString;
563     }
564
565     /**
566      * This is an event processor thread, this class decouples the events handling logic from core business logic. This
567      * class runs its own thread and continuously querying the blocking queue for the events that have been sent to the
568      * worker for processing by the Apex engine.
569      *
570      * @author Liam Fallon (liam.fallon@ericsson.com)
571      */
572     private class EventProcessor implements Runnable {
573         private final boolean debugEnabled = LOGGER.isDebugEnabled();
574         // the events queue
575         private BlockingQueue<ApexEvent> eventProcessingQueue = null;
576
577         /**
578          * Constructor accepts {@link ApexEngine} and {@link BlockingQueue} type objects.
579          *
580          * @param eventProcessingQueue is reference of {@link BlockingQueue} which contains trigger events.
581          */
582         EventProcessor(final BlockingQueue<ApexEvent> eventProcessingQueue) {
583             this.eventProcessingQueue = eventProcessingQueue;
584         }
585
586         /**
587          * {@inheritDoc}.
588          */
589         @Override
590         public void run() {
591             LOGGER.debug("Engine {} processing ... ", engineWorkerKey);
592
593             // Take events from the event processing queue of the worker and pass them to the engine
594             // for processing
595             boolean stopFlag = false;
596             while (processorThread != null && !processorThread.isInterrupted() && !stopFlag) {
597                 ApexEvent event = null;
598                 try {
599                     event = eventProcessingQueue.take();
600                 } catch (final InterruptedException e) {
601                     // restore the interrupt status
602                     Thread.currentThread().interrupt();
603                     LOGGER.debug("Engine {} processing interrupted ", engineWorkerKey);
604                     break;
605                 }
606                 boolean executedResult = false;
607                 try {
608                     if (event != null) {
609                         debugEventIfDebugEnabled(event);
610
611                         final EnEvent enevent = apexEnEventConverter.fromApexEvent(event);
612                         executedResult = engine.handleEvent(enevent);
613                     }
614                 } catch (final ApexException e) {
615                     LOGGER.warn("Engine {} failed to process event {}", engineWorkerKey, event.toString(), e);
616                 } catch (final Exception e) {
617                     LOGGER.warn("Engine {} terminated processing event {}", engineWorkerKey, event.toString(), e);
618                     stopFlag = true;
619                 }
620                 ApexPolicyStatisticsManager apexPolicyCounter = ApexPolicyStatisticsManager.getInstanceFromRegistry();
621                 if (!stopFlag && apexPolicyCounter != null) {
622                     apexPolicyCounter.updatePolicyExecutedCounter(executedResult);
623                 }
624             }
625             LOGGER.debug("Engine {} completed processing", engineWorkerKey);
626         }
627
628         /**
629          * Debug the event if debug is enabled.
630          *
631          * @param event the event to debug
632          */
633         private void debugEventIfDebugEnabled(ApexEvent event) {
634             if (debugEnabled) {
635                 LOGGER.debug("Trigger Event {} forwarded to the Apex engine", event);
636             }
637         }
638     }
639 }