b0dd9c5c90021e196339d671917e7f6805a8fafd
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
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
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.plugins.executor.jython;
22
23 import java.util.Map;
24
25 import org.onap.policy.apex.context.ContextException;
26 import org.onap.policy.apex.core.engine.executor.TaskExecutor;
27 import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
28 import org.python.core.CompileMode;
29 import org.python.core.Py;
30 import org.python.core.PyCode;
31 import org.python.core.PyException;
32 import org.python.util.PythonInterpreter;
33 import org.slf4j.ext.XLogger;
34 import org.slf4j.ext.XLoggerFactory;
35
36 /**
37  * The Class JythonTaskExecutor is the task executor for task logic written in Jython It is unlikely that this is thread
38  * safe.
39  *
40  * @author Liam Fallon (liam.fallon@ericsson.com)
41  */
42 public class JythonTaskExecutor extends TaskExecutor {
43     // Logger for this class
44     private static final XLogger LOGGER = XLoggerFactory.getXLogger(JythonTaskExecutor.class);
45
46     // The Jython interpreter
47     private final PythonInterpreter interpreter = new PythonInterpreter();
48     private PyCode compiled = null;
49
50     /**
51      * Prepares the task for processing.
52      *
53      * @throws StateMachineException thrown when a state machine execution error occurs
54      */
55     @Override
56     public void prepare() throws StateMachineException {
57         interpreter.setErr(System.err);
58         interpreter.setOut(System.out);
59
60         // Call generic prepare logic
61         super.prepare();
62         try {
63             synchronized (Py.class) {
64                 compiled = Py.compile_flags(getSubject().getTaskLogic().getLogic(),
65                         "<" + getSubject().getKey().toString() + ">", CompileMode.exec, null);
66             }
67         } catch (final PyException e) {
68             LOGGER.warn("failed to compile Jython code for task " + getSubject().getKey().getID(), e);
69             throw new StateMachineException("failed to compile Jython code for task " + getSubject().getKey().getID(),
70                     e);
71         }
72
73     }
74
75     /**
76      * Executes the executor for the task in a sequential manner.
77      *
78      * @param executionID the execution ID for the current APEX policy execution
79      * @param incomingFields the incoming fields
80      * @return The outgoing fields
81      * @throws StateMachineException on an execution error
82      * @throws ContextException on context errors
83      */
84     @Override
85     public Map<String, Object> execute(final long executionID, final Map<String, Object> incomingFields)
86             throws StateMachineException, ContextException {
87
88         boolean returnValue = false;
89
90         // Do execution pre work
91         executePre(executionID, incomingFields);
92
93         try {
94
95             // Check and execute the Jython logic
96             /* Precompiled Version */
97             synchronized (Py.class) {
98                 // Set up the Jython engine
99                 interpreter.set("executor", getExecutionContext());
100                 interpreter.exec(compiled);
101                 try {
102                     final Object ret = interpreter.get("returnValue", java.lang.Boolean.class);
103                     if (ret == null) {
104                         LOGGER.error("execute: task logic failed to set a return value for task  \""
105                                 + getSubject().getKey().getID() + "\"");
106                         throw new StateMachineException("execute: task logic failed to set a return value for task  \""
107                                 + getSubject().getKey().getID() + "\"");
108                     }
109                     returnValue = (Boolean) ret;
110                 } catch (NullPointerException | ClassCastException e) {
111                     LOGGER.error("execute: task selection logic failed to set a correct return value for state  \""
112                             + getSubject().getKey().getID() + "\"", e);
113                     throw new StateMachineException(
114                             "execute: task selection logic failed to set a return value for state  \""
115                                     + getSubject().getKey().getID() + "\"",
116                             e);
117                 }
118             }
119             /* */
120         } catch (final Exception e) {
121             LOGGER.warn("failed to execute Jython code for task " + getSubject().getKey().getID(), e);
122             throw new StateMachineException("failed to execute Jython code for task " + getSubject().getKey().getID(),
123                     e);
124         }
125
126         // Do the execution post work
127         executePost(returnValue);
128
129         // Send back the return event
130         if (returnValue) {
131             return getOutgoing();
132         } else {
133             return null;
134         }
135     }
136
137     /**
138      * Cleans up the task after processing.
139      *
140      * @throws StateMachineException thrown when a state machine execution error occurs
141      */
142     @Override
143     public void cleanUp() throws StateMachineException {
144         interpreter.cleanup();
145         LOGGER.debug("cleanUp:" + getSubject().getKey().getID() + "," + getSubject().getTaskLogic().getLogicFlavour()
146                 + "," + getSubject().getTaskLogic().getLogic());
147     }
148 }