2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Copyright (C) 2019 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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.service.engine.runtime.impl;
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.Arrays;
31 import java.util.Collection;
33 import java.util.Map.Entry;
34 import java.util.concurrent.BlockingQueue;
36 import org.onap.policy.apex.context.ContextException;
37 import org.onap.policy.apex.context.ContextRuntimeException;
38 import org.onap.policy.apex.context.SchemaHelper;
39 import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory;
40 import org.onap.policy.apex.core.engine.engine.ApexEngine;
41 import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory;
42 import org.onap.policy.apex.core.engine.event.EnEvent;
43 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
44 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
45 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
46 import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
47 import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
48 import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
49 import org.onap.policy.apex.model.basicmodel.service.ModelService;
50 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
51 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums;
52 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
53 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
54 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
55 import org.onap.policy.apex.service.engine.event.ApexEvent;
56 import org.onap.policy.apex.service.engine.event.impl.enevent.ApexEvent2EnEventConverter;
57 import org.onap.policy.apex.service.engine.runtime.ApexEventListener;
58 import org.onap.policy.apex.service.engine.runtime.EngineService;
59 import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface;
60 import org.slf4j.ext.XLogger;
61 import org.slf4j.ext.XLoggerFactory;
64 * The Class EngineWorker encapsulates a core {@link ApexEngine} instance, which runs policies defined in the
65 * {@link org.onap.policy.apex.model.basicmodel.concepts.AxModelAxModel}. Each policy is triggered by an Apex event, and
66 * when the policy is triggered it runs through to completion in the ApexEngine.
68 * <p>This class acts as a container for an {@link ApexEngine}, running it in a thread, sending it events, and receiving
71 * @author Liam Fallon (liam.fallon@ericsson.com)
73 final class EngineWorker implements EngineService {
74 // Logger for this class
75 private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineService.class);
77 // Recurring string constants
78 private static final String ENGINE_FOR_KEY_PREFIX = "apex engine for engine key ";
79 private static final String ENGINE_SUFFIX = " of this engine";
80 private static final String BAD_KEY_MATCH_TAG = " does not match the key";
81 private static final String ENGINE_KEY_PREFIX = "engine key ";
83 // The ID of this engine
84 private final AxArtifactKey engineWorkerKey;
86 // The Apex engine which is running the policies in this worker
87 private final ApexEngine engine;
89 // The event processor is an inner class, an instance of which runs as a thread that reads
90 // incoming events from a queue and forwards them to the Apex engine
91 private EventProcessor processor = null;
93 // Thread handling for the worker
94 private final ApplicationThreadFactory threadFactory;
95 private Thread processorThread;
97 // Converts ApexEvent instances to and from EnEvent instances
98 private ApexEvent2EnEventConverter apexEnEventConverter = null;
101 private boolean isSubsequentInstance;
104 * Constructor that creates an Apex engine, an event processor for events to be sent to that engine, and an
105 * {@link ApexModelReader} instance to read Apex models using JAXB.
107 * @param engineWorkerKey the engine worker key
108 * @param queue the queue on which events for this Apex worker will come
109 * @param threadFactory the thread factory to use for creating the event processing thread
110 * @throws ApexException thrown on errors on worker instantiation
112 protected EngineWorker(final AxArtifactKey engineWorkerKey, final BlockingQueue<ApexEvent> queue,
113 final ApplicationThreadFactory threadFactory) {
114 LOGGER.entry(engineWorkerKey);
116 this.engineWorkerKey = engineWorkerKey;
117 this.threadFactory = threadFactory;
119 // Create the Apex engine
120 engine = new ApexEngineFactory().createApexEngine(engineWorkerKey);
122 // Create and run the event processor
123 processor = new EventProcessor(queue);
125 // Set the Event converter up
126 apexEnEventConverter = new ApexEvent2EnEventConverter(engine);
135 public void registerActionListener(final String listenerName, final ApexEventListener apexEventListener) {
136 engine.addEventListener(listenerName, new EnEventListenerImpl(apexEventListener, apexEnEventConverter));
143 public void deregisterActionListener(final String listenerName) {
144 engine.removeEventListener(listenerName);
151 public EngineServiceEventInterface getEngineServiceEventInterface() {
152 throw new UnsupportedOperationException(
153 "getEngineServiceEventInterface() call is not allowed on an Apex Engine Worker");
160 public AxArtifactKey getKey() {
161 return engineWorkerKey;
168 public Collection<AxArtifactKey> getEngineKeys() {
169 return Arrays.asList(engineWorkerKey);
176 public AxArtifactKey getApexModelKey() {
177 if (ModelService.existsModel(AxPolicyModel.class)) {
178 return ModelService.getModel(AxPolicyModel.class).getKey();
188 public void updateModel(final AxArtifactKey engineKey, final String engineModel, final boolean forceFlag)
189 throws ApexException {
190 LOGGER.entry(engineKey);
192 // Read the Apex model into memory using the Apex Model Reader
193 AxPolicyModel apexPolicyModel = null;
195 final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class);
196 apexPolicyModel = modelReader.read(new ByteArrayInputStream(engineModel.getBytes()));
197 } catch (final ApexModelException e) {
198 LOGGER.error("failed to unmarshal the apex model on engine " + engineKey.getId(), e);
199 throw new ApexException("failed to unmarshal the apex model on engine " + engineKey.getId(), e);
202 // Update the Apex model in the Apex engine
203 updateModel(engineKey, apexPolicyModel, forceFlag);
212 public void updateModel(final AxArtifactKey engineKey, final AxPolicyModel apexModel, final boolean forceFlag)
213 throws ApexException {
214 LOGGER.entry(engineKey);
216 // Check if the key on the update request is correct
217 if (!engineWorkerKey.equals(engineKey)) {
218 String message = ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
220 LOGGER.warn(message);
221 throw new ApexException(message);
224 // Check model compatibility
225 if (ModelService.existsModel(AxPolicyModel.class)) {
226 // The current policy model may or may not be defined
227 final AxPolicyModel currentModel = ModelService.getModel(AxPolicyModel.class);
228 if (!currentModel.getKey().isCompatible(apexModel.getKey())) {
230 LOGGER.warn("apex model update forced, supplied model with key \"" + apexModel.getKey().getId()
231 + "\" is not a compatible model update from the existing engine model with key \""
232 + currentModel.getKey().getId() + "\"");
234 throw new ContextException(
235 "apex model update failed, supplied model with key \"" + apexModel.getKey().getId()
236 + "\" is not a compatible model update from the existing engine model with key \""
237 + currentModel.getKey().getId() + "\"");
241 // Update the Apex model in the Apex engine
242 engine.updateModel(apexModel, isSubsequentInstance);
244 LOGGER.debug("engine model {} added to the engine-{}", apexModel.getKey().getId(), engineWorkerKey);
252 public AxEngineState getState() {
253 return engine.getState();
260 public void startAll() throws ApexException {
261 start(this.getKey());
268 public void start(final AxArtifactKey engineKey) throws ApexException {
269 LOGGER.entry(engineKey);
271 // Check if the key on the start request is correct
272 if (!engineWorkerKey.equals(engineKey)) {
274 ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
275 throw new ApexException(
276 ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
279 // Starts the event processing thread that handles incoming events
280 if (processorThread != null && processorThread.isAlive()) {
281 String message = ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already running with state "
283 LOGGER.error(message);
284 throw new ApexException(message);
290 // Start a thread to process events for the engine
291 processorThread = threadFactory.newThread(processor);
292 processorThread.start();
294 LOGGER.exit(engineKey);
301 public void stop() throws ApexException {
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)) {
313 ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
314 throw new ApexException(
315 ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
318 // Interrupt the worker to stop its thread
319 if (processorThread == null || !processorThread.isAlive()) {
320 processorThread = null;
323 .warn(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already stopped with state " + getState());
327 // Interrupt the thread that is handling events toward the engine
328 processorThread.interrupt();
329 processorThread = null;
334 LOGGER.exit(engineKey);
341 public void clear() throws ApexException {
342 clear(this.getKey());
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)) {
353 ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
354 throw new ApexException(
355 ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
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());
367 LOGGER.exit(engineKey);
374 public boolean isStarted() {
375 return isStarted(this.getKey());
382 public boolean isStarted(final AxArtifactKey engineKey) {
383 final AxEngineState engstate = getState();
391 return processorThread != null && processorThread.isAlive() && !processorThread.isInterrupted();
402 public boolean isStopped() {
403 return isStopped(this.getKey());
410 public boolean isStopped(final AxArtifactKey engineKey) {
411 final AxEngineState engstate = getState();
419 return processorThread == null || !processorThread.isAlive();
430 public void startPeriodicEvents(final long period) {
431 throw new UnsupportedOperationException("startPeriodicEvents() call is not allowed on an Apex Engine Worker");
438 public void stopPeriodicEvents() {
439 throw new UnsupportedOperationException("stopPeriodicEvents() call is not allowed on an Apex Engine Worker");
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);
451 // Convert that information into a string
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);
468 public String getRuntimeInfo(final AxArtifactKey engineKey) {
469 // We'll build up the JSON string for runtime information bit by bit
470 final StringBuilder runtimeJsonStringBuilder = new StringBuilder();
472 // Get the engine information
473 final AxEngineModel engineModel = engine.getEngineStatus();
474 final Map<AxArtifactKey, Map<String, Object>> engineContextAlbums = engine.getEngineContext();
476 // Use GSON to convert our context information into JSON
477 final Gson gson = new GsonBuilder().setPrettyPrinting().create();
479 // Get context into a JSON string
480 runtimeJsonStringBuilder.append("{\"TimeStamp\":");
481 runtimeJsonStringBuilder.append(engineModel.getTimestamp());
482 runtimeJsonStringBuilder.append(",\"State\":");
483 runtimeJsonStringBuilder.append(engineModel.getState());
484 runtimeJsonStringBuilder.append(",\"Stats\":");
485 runtimeJsonStringBuilder.append(gson.toJson(engineModel.getStats()));
487 // Get context into a JSON string
488 runtimeJsonStringBuilder.append(",\"ContextAlbums\":[");
490 boolean firstAlbum = true;
491 for (final Entry<AxArtifactKey, Map<String, Object>> contextAlbumEntry : engineContextAlbums.entrySet()) {
495 runtimeJsonStringBuilder.append(",");
498 runtimeJsonStringBuilder.append("{\"AlbumKey\":");
499 runtimeJsonStringBuilder.append(gson.toJson(contextAlbumEntry.getKey()));
500 runtimeJsonStringBuilder.append(",\"AlbumContent\":[");
502 // Get the schema helper to use to marshal context album objects to JSON
503 final AxContextAlbum axContextAlbum = ModelService.getModel(AxContextAlbums.class)
504 .get(contextAlbumEntry.getKey());
505 SchemaHelper schemaHelper = null;
508 // Get a schema helper to manage the translations between objects on the album map
510 schemaHelper = new SchemaHelperFactory().createSchemaHelper(axContextAlbum.getKey(),
511 axContextAlbum.getItemSchema());
512 } catch (final ContextRuntimeException e) {
513 final String resultString = "could not find schema helper to marshal context album \"" + axContextAlbum
515 LOGGER.warn(resultString, e);
517 // End of context album entry
518 runtimeJsonStringBuilder.append(resultString);
519 runtimeJsonStringBuilder.append("]}");
524 boolean firstEntry = true;
525 for (final Entry<String, Object> contextEntry : contextAlbumEntry.getValue().entrySet()) {
529 runtimeJsonStringBuilder.append(",");
531 runtimeJsonStringBuilder.append("{\"EntryName\":");
532 runtimeJsonStringBuilder.append(gson.toJson(contextEntry.getKey()));
533 runtimeJsonStringBuilder.append(",\"EntryContent\":");
534 runtimeJsonStringBuilder.append(gson.toJson(schemaHelper.marshal2String(contextEntry.getValue())));
536 // End of context entry
537 runtimeJsonStringBuilder.append("}");
540 // End of context album entry
541 runtimeJsonStringBuilder.append("]}");
544 runtimeJsonStringBuilder.append("]}");
546 // Tidy up the JSON string
547 final JsonParser jsonParser = new JsonParser();
548 final JsonElement jsonElement = jsonParser.parse(runtimeJsonStringBuilder.toString());
549 final String tidiedRuntimeString = gson.toJson(jsonElement);
551 LOGGER.debug("runtime information={}", tidiedRuntimeString);
553 return tidiedRuntimeString;
557 * This is an event processor thread, this class decouples the events handling logic from core business logic. This
558 * class runs its own thread and continuously querying the blocking queue for the events that have been sent to the
559 * worker for processing by the Apex engine.
561 * @author Liam Fallon (liam.fallon@ericsson.com)
563 private class EventProcessor implements Runnable {
564 private final boolean debugEnabled = LOGGER.isDebugEnabled();
566 private BlockingQueue<ApexEvent> eventProcessingQueue = null;
569 * Constructor accepts {@link ApexEngine} and {@link BlockingQueue} type objects.
571 * @param eventProcessingQueue is reference of {@link BlockingQueue} which contains trigger events.
573 EventProcessor(final BlockingQueue<ApexEvent> eventProcessingQueue) {
574 this.eventProcessingQueue = eventProcessingQueue;
582 LOGGER.debug("Engine {} processing ... ", engineWorkerKey);
584 // Take events from the event processing queue of the worker and pass them to the engine
586 boolean stopFlag = false;
587 while (processorThread != null && !processorThread.isInterrupted() && !stopFlag) {
588 ApexEvent event = null;
590 event = eventProcessingQueue.take();
591 } catch (final InterruptedException e) {
592 // restore the interrupt status
593 Thread.currentThread().interrupt();
594 LOGGER.debug("Engine {} processing interrupted ", engineWorkerKey);
600 debugEventIfDebugEnabled(event);
602 final EnEvent enevent = apexEnEventConverter.fromApexEvent(event);
603 engine.handleEvent(enevent);
605 } catch (final ApexException e) {
606 LOGGER.warn("Engine {} failed to process event {}", engineWorkerKey, event.toString(), e);
607 } catch (final Exception e) {
608 LOGGER.warn("Engine {} terminated processing event {}", engineWorkerKey, event.toString(), e);
612 LOGGER.debug("Engine {} completed processing", engineWorkerKey);
616 * Debug the event if debug is enabled.
618 * @param event the event to debug
620 private void debugEventIfDebugEnabled(ApexEvent event) {
622 LOGGER.debug("Trigger Event {} forwarded to the Apex engine", event);