4fd48f2e7a372bcf20edefe568b8e8059c090a59
[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.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 JythonTaskSelectExecutor is the task selection executor for task selection logic written in Jython It is
38  * unlikely that this is thread safe.
39  *
40  * @author Liam Fallon (liam.fallon@ericsson.com)
41  */
42 public class JythonTaskSelectExecutor extends TaskSelectExecutor {
43     private static final XLogger LOGGER = XLoggerFactory.getXLogger(JythonTaskSelectExecutor.class);
44
45     // The Jython interpreter
46     private final PythonInterpreter interpreter = new PythonInterpreter();
47     private PyCode compiled = null;
48
49     /**
50      * Prepares the task for processing.
51      *
52      * @throws StateMachineException thrown when a state machine execution error occurs
53      */
54     @Override
55     public void prepare() throws StateMachineException {
56         interpreter.setErr(System.err);
57         interpreter.setOut(System.out);
58
59         // Call generic prepare logic
60         super.prepare();
61         try {
62             synchronized (Py.class) {
63                 compiled = Py.compile_flags(getSubject().getTaskSelectionLogic().getLogic(),
64                         "<" + getSubject().getKey().toString() + ">", CompileMode.exec, null);
65             }
66         } catch (final PyException e) {
67             LOGGER.warn("failed to compile Jython code for task selection logic in " + getSubject().getKey().getID(),
68                     e);
69             throw new StateMachineException(
70                     "failed to compile Jython code for task selection logic in " + getSubject().getKey().getID(), 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 incomingEvent the incoming event
80      * @return The outgoing event
81      * @throws StateMachineException on an execution error
82      * @throws ContextException on context errors
83      */
84     @Override
85     public AxArtifactKey execute(final long executionID, final EnEvent incomingEvent)
86             throws StateMachineException, ContextException {
87
88         boolean returnValue = false;
89
90         // Do execution pre work
91         executePre(executionID, incomingEvent);
92
93         try {
94             // Check and execute the Jython logic
95             /* Precompiled Version */
96             synchronized (Py.class) {
97                 // Set up the Jython engine
98                 interpreter.set("executor", getExecutionContext());
99                 interpreter.exec(compiled);
100
101                 try {
102                     final Object ret = interpreter.get("returnValue", java.lang.Boolean.class);
103                     if (ret == null) {
104                         LOGGER.error("execute: task selection logic failed to set a return value for state  \""
105                                 + getSubject().getKey().getID() + "\"");
106                         throw new StateMachineException(
107                                 "execute: task selection logic failed to set a return value for state  \""
108                                         + getSubject().getKey().getID() + "\"");
109                     }
110                     returnValue = (Boolean) ret;
111                 } catch (NullPointerException | ClassCastException e) {
112                     LOGGER.error("execute: task selection logic failed to set a correct return value for state  \""
113                             + getSubject().getKey().getID() + "\"", e);
114                     throw new StateMachineException(
115                             "execute: task selection logic failed to set a return value for state  \""
116                                     + getSubject().getKey().getID() + "\"",
117                             e);
118                 }
119             }
120             /* */
121         } catch (final Exception e) {
122             LOGGER.warn("failed to execute Jython code for task selection logic in " + getSubject().getKey().getID(),
123                     e);
124             throw new StateMachineException(
125                     "failed to execute Jython code for task selection logic in " + getSubject().getKey().getID(), 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() + ","
148                 + getSubject().getTaskSelectionLogic().getLogicFlavour() + ","
149                 + getSubject().getTaskSelectionLogic().getLogic());
150     }
151 }