2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 Nordix Foundation.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.plugins.executor.javascript;
23 import java.util.concurrent.BlockingQueue;
24 import java.util.concurrent.CountDownLatch;
25 import java.util.concurrent.LinkedBlockingQueue;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.atomic.AtomicReference;
29 import lombok.AccessLevel;
31 import lombok.NonNull;
34 import org.apache.commons.lang3.StringUtils;
35 import org.mozilla.javascript.Context;
36 import org.mozilla.javascript.Script;
37 import org.mozilla.javascript.Scriptable;
38 import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
39 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
40 import org.slf4j.ext.XLogger;
41 import org.slf4j.ext.XLoggerFactory;
44 * The Class JavascriptExecutor is the executor for task logic written in Javascript.
46 * @author Liam Fallon (liam.fallon@ericsson.com)
48 public class JavascriptExecutor implements Runnable {
49 private static final XLogger LOGGER = XLoggerFactory.getXLogger(JavascriptExecutor.class);
51 public static final int DEFAULT_OPTIMIZATION_LEVEL = 9;
53 // Token passed to executor thread to stop execution
54 private static final Object STOP_EXECUTION_TOKEN = "*** STOP EXECUTION ***";
56 // Recurring string constants
57 private static final String WITH_MESSAGE = " with message: ";
58 private static final String JAVASCRIPT_EXECUTOR = "JavascriptExecutor ";
60 @Setter(AccessLevel.PROTECTED)
61 private static TimeUnit timeunit4Latches = TimeUnit.SECONDS;
62 @Setter(AccessLevel.PROTECTED)
63 private static int intializationLatchTimeout = 60;
64 @Setter(AccessLevel.PROTECTED)
65 private static int cleanupLatchTimeout = 60;
67 // The key of the subject that wants to execute Javascript code
68 final AxKey subjectKey;
70 private String javascriptCode;
71 private Context javascriptContext;
72 private Script script;
74 private final BlockingQueue<Object> executionQueue = new LinkedBlockingQueue<>();
75 private final BlockingQueue<Boolean> resultQueue = new LinkedBlockingQueue<>();
77 @Getter(AccessLevel.PROTECTED)
78 private Thread executorThread;
79 private CountDownLatch intializationLatch;
80 private CountDownLatch cleanupLatch;
81 private AtomicReference<StateMachineException> executorException = new AtomicReference<>(null);
84 * Initializes the Javascript executor.
86 * @param subjectKey the key of the subject that is requesting Javascript execution
88 public JavascriptExecutor(final AxKey subjectKey) {
89 this.subjectKey = subjectKey;
93 * Prepares the executor for processing and compiles the Javascript code.
95 * @param javascriptCode the Javascript code to execute
96 * @throws StateMachineException thrown when instantiation of the executor fails
98 public synchronized void init(@NonNull final String javascriptCode) throws StateMachineException {
99 LOGGER.debug("JavascriptExecutor {} starting ... ", subjectKey.getId());
101 if (executorThread != null) {
102 throw new StateMachineException("initiation failed, executor " + subjectKey.getId()
103 + " already initialized, run cleanUp to clear executor");
106 if (StringUtils.isBlank(javascriptCode)) {
107 throw new StateMachineException("initiation failed, no logic specified for executor " + subjectKey.getId());
110 this.javascriptCode = javascriptCode;
112 executorThread = new Thread(this);
113 executorThread.setName(this.getClass().getSimpleName() + ":" + subjectKey.getId());
114 intializationLatch = new CountDownLatch(1);
115 cleanupLatch = new CountDownLatch(1);
118 executorThread.start();
119 } catch (IllegalThreadStateException e) {
120 throw new StateMachineException("initiation failed, executor " + subjectKey.getId() + " failed to start",
125 if (!intializationLatch.await(intializationLatchTimeout, timeunit4Latches)) {
126 executorThread.interrupt();
127 throw new StateMachineException(JAVASCRIPT_EXECUTOR + subjectKey.getId()
128 + " initiation timed out after " + intializationLatchTimeout + " " + timeunit4Latches);
130 } catch (InterruptedException e) {
131 LOGGER.debug("JavascriptExecutor {} interrupted on execution thread startup", subjectKey.getId(), e);
132 Thread.currentThread().interrupt();
135 checkAndThrowExecutorException();
137 LOGGER.debug("JavascriptExecutor {} started ... ", subjectKey.getId());
141 * Execute a Javascript script.
143 * @param executionContext the execution context to use for script execution
144 * @return true if execution was successful, false otherwise
145 * @throws StateMachineException on execution errors
147 public synchronized boolean execute(final Object executionContext) throws StateMachineException {
148 if (executorThread == null) {
149 throw new StateMachineException("execution failed, executor " + subjectKey.getId() + " is not initialized");
152 if (!executorThread.isAlive()) {
153 throw new StateMachineException("execution failed, executor " + subjectKey.getId()
154 + " is not running, run cleanUp to clear executor and init to restart executor");
157 executionQueue.add(executionContext);
159 boolean result = false;
162 result = resultQueue.take();
163 } catch (final InterruptedException e) {
164 executorThread.interrupt();
165 Thread.currentThread().interrupt();
166 throw new StateMachineException(
167 JAVASCRIPT_EXECUTOR + subjectKey.getId() + "interrupted on execution result wait", e);
170 checkAndThrowExecutorException();
176 * Cleans up the executor after processing.
178 * @throws StateMachineException thrown when cleanup of the executor fails
180 public synchronized void cleanUp() throws StateMachineException {
181 if (executorThread == null) {
182 throw new StateMachineException("cleanup failed, executor " + subjectKey.getId() + " is not initialized");
185 if (executorThread.isAlive()) {
186 executionQueue.add(STOP_EXECUTION_TOKEN);
189 if (!cleanupLatch.await(cleanupLatchTimeout, timeunit4Latches)) {
190 executorException.set(new StateMachineException(JAVASCRIPT_EXECUTOR + subjectKey.getId()
191 + " cleanup timed out after " + cleanupLatchTimeout + " " + timeunit4Latches));
193 } catch (InterruptedException e) {
194 LOGGER.debug("JavascriptExecutor {} interrupted on execution cleanup wait", subjectKey.getId(), e);
195 Thread.currentThread().interrupt();
199 executorThread = null;
200 executionQueue.clear();
203 checkAndThrowExecutorException();
208 LOGGER.debug("JavascriptExecutor {} initializing ... ", subjectKey.getId());
212 } catch (StateMachineException sme) {
213 LOGGER.warn("JavascriptExecutor {} initialization failed", subjectKey.getId(), sme);
214 executorException.set(sme);
215 intializationLatch.countDown();
216 cleanupLatch.countDown();
220 intializationLatch.countDown();
222 LOGGER.debug("JavascriptExecutor {} executing ... ", subjectKey.getId());
224 // Take jobs from the execution queue of the worker and execute them
225 while (!Thread.currentThread().isInterrupted()) {
227 Object contextObject = executionQueue.take();
228 if (STOP_EXECUTION_TOKEN.equals(contextObject)) {
229 LOGGER.debug("execution close was ordered for " + subjectKey.getId());
232 resultQueue.add(executeScript(contextObject));
233 } catch (final InterruptedException e) {
234 LOGGER.debug("execution was interruped for " + subjectKey.getId() + WITH_MESSAGE + e.getMessage(), e);
235 executionQueue.add(STOP_EXECUTION_TOKEN);
236 Thread.currentThread().interrupt();
237 } catch (StateMachineException sme) {
238 executorException.set(sme);
239 resultQueue.add(false);
243 resultQueue.add(false);
247 } catch (final Exception e) {
248 executorException.set(new StateMachineException(
249 "executor close failed to close for " + subjectKey.getId() + WITH_MESSAGE + e.getMessage(), e));
252 cleanupLatch.countDown();
254 LOGGER.debug("JavascriptExecutor {} completed processing", subjectKey.getId());
257 private void initExecutor() throws StateMachineException {
259 // Create a Javascript context for this thread
260 javascriptContext = Context.enter();
262 // Set up the default values of the context
263 javascriptContext.setOptimizationLevel(DEFAULT_OPTIMIZATION_LEVEL);
264 javascriptContext.setLanguageVersion(Context.VERSION_1_8);
266 script = javascriptContext.compileString(javascriptCode, subjectKey.getId(), 1, null);
267 } catch (Exception e) {
269 throw new StateMachineException(
270 "logic failed to compile for " + subjectKey.getId() + WITH_MESSAGE + e.getMessage(), e);
274 private boolean executeScript(final Object executionContext) throws StateMachineException {
275 Object returnObject = null;
278 // Pass the subject context to the Javascript engine
279 Scriptable javascriptScope = javascriptContext.initStandardObjects();
280 javascriptScope.put("executor", javascriptScope, executionContext);
283 returnObject = script.exec(javascriptContext, javascriptScope);
284 } catch (final Exception e) {
285 throw new StateMachineException(
286 "logic failed to run for " + subjectKey.getId() + WITH_MESSAGE + e.getMessage(), e);
289 if (!(returnObject instanceof Boolean)) {
290 throw new StateMachineException(
291 "execute: logic for " + subjectKey.getId() + " returned a non-boolean value " + returnObject);
294 return (boolean) returnObject;
297 private void checkAndThrowExecutorException() throws StateMachineException {
298 StateMachineException exceptionToThrow = executorException.getAndSet(null);
299 if (exceptionToThrow != null) {
300 throw exceptionToThrow;