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