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