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