e298967d04c240120a8640f7f532213796baee57
[appc.git] / appc-config / appc-flow-controller / provider / src / main / java / org / onap / appc / flow / controller / node / FlowControlNode.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * =============================================================================
7  * Modifications Copyright (C) 2019 Ericsson
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.flow.controller.node;
25
26 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.ACTION_LEVEL;
27 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.DESINGTIME;
28 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.GRAPH;
29 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.INPUT_PARAM_RESPONSE_PREFIX;
30 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.NODE;
31 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.OUTPUT_PARAM_ERROR_MESSAGE;
32 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.OUTPUT_PARAM_STATUS;
33 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.OUTPUT_STATUS_FAILURE;
34 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.OUTPUT_STATUS_MESSAGE;
35 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.OUTPUT_STATUS_SUCCESS;
36 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.REQUEST_ACTION;
37 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.REQUEST_ID;
38 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.RESPONSE_PREFIX;
39 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.REST;
40 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.SEQUENCE_TYPE;
41 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.VNF_TYPE;
42 import java.io.IOException;
43 import java.util.HashMap;
44 import java.util.List;
45 import java.util.Map;
46 import org.apache.commons.lang3.StringUtils;
47 import org.onap.appc.flow.controller.ResponseHandlerImpl.DefaultResponseHandler;
48 import org.onap.appc.flow.controller.data.PrecheckOption;
49 import org.onap.appc.flow.controller.data.ResponseAction;
50 import org.onap.appc.flow.controller.data.Transaction;
51 import org.onap.appc.flow.controller.data.Transactions;
52 import org.onap.appc.flow.controller.dbervices.FlowControlDBService;
53 import org.onap.appc.flow.controller.executorImpl.GraphExecutor;
54 import org.onap.appc.flow.controller.executorImpl.NodeExecutor;
55 import org.onap.appc.flow.controller.executorImpl.RestExecutor;
56 import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface;
57 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
58 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
59 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
60 import com.att.eelf.configuration.EELFLogger;
61 import com.att.eelf.configuration.EELFManager;
62 import com.fasterxml.jackson.databind.ObjectMapper;
63
64 public class FlowControlNode implements SvcLogicJavaPlugin {
65
66     private static final EELFLogger log = EELFManager.getInstance().getLogger(FlowControlNode.class);
67
68     private final FlowControlDBService dbService;
69     private final FlowSequenceGenerator flowSequenceGenerator;
70
71     public FlowControlNode() {
72         this.dbService = FlowControlDBService.initialise();
73         this.flowSequenceGenerator = new FlowSequenceGenerator();
74     }
75
76     FlowControlNode(FlowControlDBService dbService, FlowSequenceGenerator flowSequenceGenerator) {
77         this.dbService = dbService;
78         this.flowSequenceGenerator = flowSequenceGenerator;
79     }
80
81     public void processFlow(Map<String, String> inParams, SvcLogicContext ctx) throws SvcLogicException {
82         log.debug("Received processParamKeys call with params : " + inParams);
83         String responsePrefix = inParams.get(INPUT_PARAM_RESPONSE_PREFIX);
84         try {
85             responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : "";
86             SvcLogicContext localContext = new SvcLogicContext();
87
88             localContext.setAttribute(REQUEST_ID, ctx.getAttribute(REQUEST_ID));
89             localContext.setAttribute(VNF_TYPE, ctx.getAttribute(VNF_TYPE));
90             localContext.setAttribute(REQUEST_ACTION, ctx.getAttribute(REQUEST_ACTION));
91             localContext.setAttribute(ACTION_LEVEL, ctx.getAttribute(ACTION_LEVEL));
92             localContext.setAttribute(RESPONSE_PREFIX, responsePrefix);
93             ctx.setAttribute(RESPONSE_PREFIX, responsePrefix);
94
95             dbService.getFlowReferenceData(ctx, inParams, localContext);
96
97             for (String key : localContext.getAttributeKeySet()) {
98                 log.debug("processFlow " + key + "=" + ctx.getAttribute(key));
99             }
100             processFlowSequence(inParams, ctx, localContext);
101             if (!ctx.getAttribute(responsePrefix + OUTPUT_PARAM_STATUS).equals(OUTPUT_STATUS_SUCCESS)) {
102                 throw new SvcLogicException(ctx.getAttribute(responsePrefix + OUTPUT_STATUS_MESSAGE));
103             }
104         } catch (Exception e) {
105             ctx.setAttribute(responsePrefix + OUTPUT_PARAM_STATUS, OUTPUT_STATUS_FAILURE);
106             ctx.setAttribute(responsePrefix + OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage());
107             log.error("Error occurred in processFlow ", e);
108             throw new SvcLogicException(e.getMessage());
109         }
110     }
111
112     private void processFlowSequence(Map<String, String> inParams, SvcLogicContext ctx, SvcLogicContext localContext)
113             throws Exception {
114
115         String fn = "FlowExecutorNode.processflowSequence";
116         log.debug(fn + "Received model for flow : " + localContext.toString());
117
118         localContext.getAttributeKeySet().forEach(key -> log.debug(key + "=" + ctx.getAttribute(key)));
119
120         String flowSequence = flowSequenceGenerator.getFlowSequence(inParams, ctx, localContext);
121
122         log.debug("Received Flow Sequence : " + flowSequence);
123         HashMap<Integer, Transaction> transactionMap = createTransactionMap(flowSequence, localContext);
124         executeAllTransaction(transactionMap, ctx);
125         log.info("Executed all the transaction successfully");
126     }
127
128     private void executeAllTransaction(HashMap<Integer, Transaction> transactionMap, SvcLogicContext ctx)
129             throws Exception {
130
131         String fn = "FlowExecutorNode.executeAllTransaction ";
132         int retry = 0;
133         FlowExecutorInterface flowExecutor;
134         for (int key = 1; key <= transactionMap.size(); key++) {
135             log.debug(fn + "Starting transactions ID " + key + " :)=" + retry);
136             Transaction transaction = transactionMap.get(key);
137             if (!preProcessor(transactionMap, transaction)) {
138                 log.info("Skipping Transaction ID " + transaction.getTransactionId());
139                 continue;
140             }
141             if (transaction.getExecutionType() != null) {
142                 switch (transaction.getExecutionType()) {
143                 case GRAPH:
144                     flowExecutor = new GraphExecutor();
145                     break;
146                 case NODE:
147                     flowExecutor = new NodeExecutor();
148                     break;
149                 case REST:
150                     flowExecutor = new RestExecutor();
151                     break;
152                 default:
153                     throw new Exception("No Executor found for transaction ID" + transaction.getTransactionId());
154                 }
155                 flowExecutor.execute(transaction, ctx);
156                 ResponseAction responseAction = handleResponse(transaction, ctx);
157
158                 if (responseAction.getWait() != null && Integer.parseInt(responseAction.getWait()) > 0) {
159                     log.debug(fn + "Going to Sleep .... " + responseAction.getWait());
160                     Thread.sleep(Integer.parseInt(responseAction.getWait()) * 1000L);
161                 }
162                 if (responseAction.isIntermediateMessage()) {
163                     log.debug(fn + "Sending Intermediate Message back  .... ");
164                     sendIntermediateMessage();
165                 }
166                 if (responseAction.getRetry() != null && Integer.parseInt(responseAction.getRetry()) > retry) {
167                     log.debug(fn + "Ooppss!!! We will retry again ....... ");
168                     key--;
169                     retry++;
170                     log.debug(fn + "key =" + key + "retry =" + retry);
171                 }
172                 if (responseAction.isIgnore()) {
173                     log.debug(fn + "Ignoring this Error and moving ahead  ....... ");
174                     continue;
175                 }
176                 if (responseAction.isStop()) {
177                     log.debug(fn + "Need to Stop  ....... ");
178                     break;
179                 }
180                 if (responseAction.getJump() != null && Integer.parseInt(responseAction.getJump()) > 0) {
181                     key = Integer.parseInt(responseAction.getJump());
182                     key--;
183                 }
184                 log.debug(fn + "key =" + key + "retry =" + retry);
185
186             } else {
187                 throw new Exception("Don't know how to execute transaction ID " + transaction.getTransactionId());
188             }
189         }
190     }
191
192     protected void sendIntermediateMessage() {
193         // TODO Auto-generated method stub
194     }
195
196     protected ResponseAction handleResponse(Transaction transaction, SvcLogicContext ctx) {
197         log.info("Handling Response for transaction Id " + transaction.getTransactionId());
198         DefaultResponseHandler defaultHandler = new DefaultResponseHandler();
199         return defaultHandler.handlerResponse(transaction, ctx);
200     }
201
202     private boolean preProcessor(HashMap<Integer, Transaction> transactionMap, Transaction transaction)
203             throws IOException {
204
205         log.debug("Starting Preprocessing Logic ");
206         boolean runThisStep = false;
207         try {
208             if (transaction.getPrecheck() != null && transaction.getPrecheck().getPrecheckOptions() != null
209                     && !transaction.getPrecheck().getPrecheckOptions().isEmpty()) {
210
211                 List<PrecheckOption> precheckOptions = transaction.getPrecheck().getPrecheckOptions();
212                 for (PrecheckOption precheck : precheckOptions) {
213                     Transaction trans = transactionMap.get(precheck.getpTransactionID());
214                     ObjectMapper mapper = new ObjectMapper();
215                     log.info("Mapper= " + mapper.writeValueAsString(trans));
216                     HashMap trmap = mapper.readValue(mapper.writeValueAsString(trans), HashMap.class);
217                     runThisStep = trmap.get(precheck.getParamName()) != null
218                             && ((String) trmap.get(precheck.getParamName())).equalsIgnoreCase(precheck.getParamValue());
219
220                     if (("any").equalsIgnoreCase(transaction.getPrecheck().getPrecheckOperator()) && runThisStep) {
221                         break;
222                     }
223                 }
224             } else {
225                 log.debug("No Pre check defined for transaction ID " + transaction.getTransactionId());
226                 runThisStep = true;
227             }
228         } catch (Exception e) {
229             log.error("Error occured when Preprocessing Logic ", e);
230             throw e;
231         }
232         log.debug("Returing process current Transaction = " + runThisStep);
233         return runThisStep;
234     }
235
236     private HashMap<Integer, Transaction> createTransactionMap(String flowSequence, SvcLogicContext localContext)
237             throws Exception {
238
239         ObjectMapper mapper = new ObjectMapper();
240         Transactions transactions = mapper.readValue(flowSequence, Transactions.class);
241         HashMap<Integer, Transaction> transMap = new HashMap<>();
242         for (Transaction transaction : transactions.getTransactions()) {
243             compileFlowDependencies(transaction, localContext);
244             // parse the Transactions Object and create records in process_flow_status table
245             // loadTransactionIntoStatus(transactions, ctx);
246             transMap.put(transaction.getTransactionId(), transaction);
247         }
248         return transMap;
249     }
250
251     private void compileFlowDependencies(Transaction transaction, SvcLogicContext localContext) throws Exception {
252
253         dbService.populateModuleAndRPC(transaction, localContext.getAttribute(VNF_TYPE));
254         ObjectMapper mapper = new ObjectMapper();
255         log.debug("Individual Transaction Details :" + transaction.toString());
256
257         if ((localContext.getAttribute(SEQUENCE_TYPE) == null) || (localContext.getAttribute(SEQUENCE_TYPE) != null
258                 && !localContext.getAttribute(SEQUENCE_TYPE).equalsIgnoreCase(DESINGTIME))) {
259
260             localContext.setAttribute("artifact-content", mapper.writeValueAsString(transaction));
261             dbService.loadSequenceIntoDB(localContext);
262         }
263         // get a field in transction class as transactionhandle interface and register
264         // the Handler here for each transactions
265     }
266
267 }