bddb63b42509dfb384dbb4259b592c4a4da96d16
[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                 returnValue = handleInterpreterResult();
104             }
105             /* */
106         } catch (final Exception e) {
107             LOGGER.warn("failed to execute Jython code for task " + getSubject().getKey().getId(), e);
108             throw new StateMachineException("failed to execute Jython code for task " + getSubject().getKey().getId(),
109                     e);
110         }
111
112         // Do the execution post work
113         executePost(returnValue);
114
115         // Send back the return event
116         if (returnValue) {
117             return getOutgoing();
118         } else {
119             return null;
120         }
121     }
122
123     /**
124      * Handle the result returned by the interpreter.
125      * 
126      * @return true if the result was successful
127      * @throws StateMachineException on interpreter failures
128      */
129     private boolean handleInterpreterResult() throws StateMachineException {
130         boolean returnValue = false;
131         
132         try {
133             final Object ret = interpreter.get("returnValue", java.lang.Boolean.class);
134             if (ret == null) {
135                 LOGGER.error("execute: task logic failed to set a return value for task  \""
136                         + getSubject().getKey().getId() + "\"");
137                 throw new StateMachineException("execute: task logic failed to set a return value for task  \""
138                         + getSubject().getKey().getId() + "\"");
139             }
140             returnValue = (Boolean) ret;
141         } catch (NullPointerException | ClassCastException e) {
142             LOGGER.error("execute: task selection logic failed to set a correct return value for state  \""
143                     + getSubject().getKey().getId() + "\"", e);
144             throw new StateMachineException(
145                     "execute: task selection logic failed to set a return value for state  \""
146                             + getSubject().getKey().getId() + "\"",
147                     e);
148         }
149         return returnValue;
150     }
151
152     /**
153      * Cleans up the task after processing.
154      *
155      * @throws StateMachineException thrown when a state machine execution error occurs
156      */
157     @Override
158     public void cleanUp() throws StateMachineException {
159         interpreter.cleanup();
160         LOGGER.debug("cleanUp:" + getSubject().getKey().getId() + "," + getSubject().getTaskLogic().getLogicFlavour()
161                 + "," + getSubject().getTaskLogic().getLogic());
162     }
163 }