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