4f4d38a195446762b799cd6d1eddea56fc0e0797
[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     // 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                 final String logic = getSubject().getTaskSelectionLogic().getLogic();
65                 final String filename = "<" + getSubject().getKey().toString() + ">";
66                 compiled = Py.compile_flags(logic, filename, CompileMode.exec, new CompilerFlags());
67             }
68         } catch (final PyException e) {
69             LOGGER.warn("failed to compile Jython code for task selection logic in " + getSubject().getKey().getId(),
70                     e);
71             throw new StateMachineException(
72                     "failed to compile Jython code for task selection logic in " + getSubject().getKey().getId(), 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 incomingEvent the incoming event
82      * @return The outgoing event
83      * @throws StateMachineException on an execution error
84      * @throws ContextException on context errors
85      */
86     @Override
87     public AxArtifactKey execute(final long executionID, final EnEvent incomingEvent)
88             throws StateMachineException, ContextException {
89
90         boolean returnValue = false;
91
92         // Do execution pre work
93         executePre(executionID, incomingEvent);
94
95         try {
96             // Check and execute the Jython logic
97             /* Precompiled Version */
98             synchronized (Py.class) {
99                 // Set up the Jython engine
100                 interpreter.set("executor", getExecutionContext());
101                 interpreter.exec(compiled);
102
103                 try {
104                     final Object ret = interpreter.get("returnValue", java.lang.Boolean.class);
105                     if (ret == null) {
106                         LOGGER.error("execute: task selection logic failed to set a return value for state  \""
107                                 + getSubject().getKey().getId() + "\"");
108                         throw new StateMachineException(
109                                 "execute: task selection logic failed to set a return value for state  \""
110                                         + getSubject().getKey().getId() + "\"");
111                     }
112                     returnValue = (Boolean) ret;
113                 } catch (NullPointerException | ClassCastException e) {
114                     LOGGER.error("execute: task selection logic failed to set a correct return value for state  \""
115                             + getSubject().getKey().getId() + "\"", e);
116                     throw new StateMachineException(
117                             "execute: task selection logic failed to set a return value for state  \""
118                                     + getSubject().getKey().getId() + "\"",
119                             e);
120                 }
121             }
122             /* */
123         } catch (final Exception e) {
124             LOGGER.warn("failed to execute Jython code for task selection logic in " + getSubject().getKey().getId(),
125                     e);
126             throw new StateMachineException(
127                     "failed to execute Jython code for task selection logic in " + getSubject().getKey().getId(), e);
128         }
129
130         // Do the execution post work
131         executePost(returnValue);
132
133         // Send back the return event
134         if (returnValue) {
135             return getOutgoing();
136         } else {
137             return null;
138         }
139     }
140
141     /**
142      * Cleans up the task after processing.
143      *
144      * @throws StateMachineException thrown when a state machine execution error occurs
145      */
146     @Override
147     public void cleanUp() throws StateMachineException {
148         interpreter.cleanup();
149         LOGGER.debug("cleanUp:" + getSubject().getKey().getId() + ","
150                 + getSubject().getTaskSelectionLogic().getLogicFlavour() + ","
151                 + getSubject().getTaskSelectionLogic().getLogic());
152     }
153 }