34d40dd55e27c94f9db3bad222b1a766b79a34b1
[appc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2019 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) throws SvcLogicException {
114         log.debug("Received processParamKeys call with params : " + inParams);
115         String responsePrefix = inParams.get(INPUT_PARAM_RESPONSE_PREFIX);
116         try {
117             responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : "";
118             SvcLogicContext localContext = new SvcLogicContext();
119
120             localContext.setAttribute(REQUEST_ID, ctx.getAttribute(REQUEST_ID));
121             localContext.setAttribute(VNF_TYPE, ctx.getAttribute(VNF_TYPE));
122             localContext.setAttribute(REQUEST_ACTION, ctx.getAttribute(REQUEST_ACTION));
123             localContext.setAttribute(ACTION_LEVEL, ctx.getAttribute(ACTION_LEVEL));
124             localContext.setAttribute(RESPONSE_PREFIX, responsePrefix);
125             ctx.setAttribute(RESPONSE_PREFIX, responsePrefix);
126
127             dbService.getFlowReferenceData(ctx, inParams, localContext);
128
129             for (String key : localContext.getAttributeKeySet()) {
130                 log.debug("processFlow " + key + "=" + ctx.getAttribute(key));
131             }
132             processFlowSequence(inParams, ctx, localContext);
133             if (!ctx.getAttribute(responsePrefix + OUTPUT_PARAM_STATUS).equals(OUTPUT_STATUS_SUCCESS)) {
134                 throw new SvcLogicException(ctx.getAttribute(responsePrefix + OUTPUT_STATUS_MESSAGE));
135             }
136         } catch (Exception e) {
137             ctx.setAttribute(responsePrefix + OUTPUT_PARAM_STATUS, OUTPUT_STATUS_FAILURE);
138             ctx.setAttribute(responsePrefix + OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage());
139             log.error("Error occurred in processFlow ", e);
140             throw new SvcLogicException(e.getMessage());
141         }
142     }
143
144     private void processFlowSequence(Map<String, String> inParams, SvcLogicContext ctx, SvcLogicContext localContext)
145             throws Exception {
146
147         String fn = "FlowExecutorNode.processflowSequence";
148         log.debug(fn + "Received model for flow : " + localContext.toString());
149
150         localContext.getAttributeKeySet().forEach(key -> log.debug(key + "=" + ctx.getAttribute(key)));
151
152         String flowSequence = flowSequenceGenerator.getFlowSequence(inParams, ctx, localContext);
153
154         log.debug("Received Flow Sequence : " + flowSequence);
155         HashMap<Integer, Transaction> transactionMap = createTransactionMap(flowSequence, localContext);
156         executeAllTransaction(transactionMap, ctx);
157         log.info("Executed all the transaction successfully");
158     }
159
160     private void executeAllTransaction(HashMap<Integer, Transaction> transactionMap, SvcLogicContext ctx)
161             throws Exception {
162
163         String fn = "FlowExecutorNode.executeAllTransaction ";
164         int retry = 0;
165         FlowExecutorInterface flowExecutor;
166         for (int key = 1; key <= transactionMap.size(); key++) {
167             log.debug(fn + "Starting transactions ID " + key + " :)=" + retry);
168             Transaction transaction = transactionMap.get(key);
169             if (!preProcessor(transactionMap, transaction)) {
170                 log.info("Skipping Transaction ID " + transaction.getTransactionId());
171                 continue;
172             }
173             if (transaction.getExecutionType() != null) {
174                 switch (transaction.getExecutionType()) {
175                 case GRAPH:
176                     flowExecutor = new GraphExecutor();
177                     break;
178                 case NODE:
179                     flowExecutor = new NodeExecutor();
180                     break;
181                 case REST:
182                     flowExecutor = new RestExecutor();
183                     break;
184                 default:
185                     throw new Exception("No Executor found for transaction ID" + transaction.getTransactionId());
186                 }
187                 flowExecutor.execute(transaction, ctx);
188                 ResponseAction responseAction = handleResponse(transaction, ctx);
189
190                 if (responseAction.getWait() != null && Integer.parseInt(responseAction.getWait()) > 0) {
191                     log.debug(fn + "Going to Sleep .... " + responseAction.getWait());
192                     Thread.sleep(Integer.parseInt(responseAction.getWait()) * 1000L);
193                 }
194                 if (responseAction.isIntermediateMessage()) {
195                     log.debug(fn + "Sending Intermediate Message back  .... ");
196                     sendIntermediateMessage();
197                 }
198                 if (responseAction.getRetry() != null && Integer.parseInt(responseAction.getRetry()) > retry) {
199                     log.debug(fn + "Ooppss!!! We will retry again ....... ");
200                     key--;
201                     retry++;
202                     log.debug(fn + "key =" + key + "retry =" + retry);
203                 }
204                 if (responseAction.isIgnore()) {
205                     log.debug(fn + "Ignoring this Error and moving ahead  ....... ");
206                     continue;
207                 }
208                 if (responseAction.isStop()) {
209                     log.debug(fn + "Need to Stop  ....... ");
210                     break;
211                 }
212                 if (responseAction.getJump() != null && Integer.parseInt(responseAction.getJump()) > 0) {
213                     key = Integer.parseInt(responseAction.getJump());
214                     key--;
215                 }
216                 log.debug(fn + "key =" + key + "retry =" + retry);
217
218             } else {
219                 throw new Exception("Don't know how to execute transaction ID " + transaction.getTransactionId());
220             }
221         }
222     }
223
224     private void sendIntermediateMessage() {
225         // TODO Auto-generated method stub
226     }
227
228     private ResponseAction handleResponse(Transaction transaction, SvcLogicContext ctx) {
229         log.info("Handling Response for transaction Id " + transaction.getTransactionId());
230         DefaultResponseHandler defaultHandler = new DefaultResponseHandler();
231         return defaultHandler.handlerResponse(transaction, ctx);
232     }
233
234     private boolean preProcessor(HashMap<Integer, Transaction> transactionMap, Transaction transaction)
235             throws IOException {
236
237         log.debug("Starting Preprocessing Logic ");
238         boolean runThisStep = false;
239         try {
240             if (transaction.getPrecheck() != null && transaction.getPrecheck().getPrecheckOptions() != null
241                     && !transaction.getPrecheck().getPrecheckOptions().isEmpty()) {
242
243                 List<PrecheckOption> precheckOptions = transaction.getPrecheck().getPrecheckOptions();
244                 for (PrecheckOption precheck : precheckOptions) {
245                     Transaction trans = transactionMap.get(precheck.getpTransactionID());
246                     ObjectMapper mapper = new ObjectMapper();
247                     log.info("Mapper= " + mapper.writeValueAsString(trans));
248                     HashMap trmap = mapper.readValue(mapper.writeValueAsString(trans), HashMap.class);
249                     runThisStep = trmap.get(precheck.getParamName()) != null
250                             && ((String) trmap.get(precheck.getParamName())).equalsIgnoreCase(precheck.getParamValue());
251
252                     if (("any").equalsIgnoreCase(transaction.getPrecheck().getPrecheckOperator()) && runThisStep) {
253                         break;
254                     }
255                 }
256             } else {
257                 log.debug("No Pre check defined for transaction ID " + transaction.getTransactionId());
258                 runThisStep = true;
259             }
260         } catch (Exception e) {
261             log.error("Error occured when Preprocessing Logic ", e);
262             throw e;
263         }
264         log.debug("Returing process current Transaction = " + runThisStep);
265         return runThisStep;
266     }
267
268     private HashMap<Integer, Transaction> createTransactionMap(String flowSequence, SvcLogicContext localContext)
269             throws Exception {
270
271         ObjectMapper mapper = new ObjectMapper();
272         Transactions transactions = mapper.readValue(flowSequence, Transactions.class);
273         HashMap<Integer, Transaction> transMap = new HashMap<>();
274         for (Transaction transaction : transactions.getTransactions()) {
275             compileFlowDependencies(transaction, localContext);
276             // parse the Transactions Object and create records in process_flow_status table
277             // loadTransactionIntoStatus(transactions, ctx);
278             transMap.put(transaction.getTransactionId(), transaction);
279         }
280         return transMap;
281     }
282
283     private void compileFlowDependencies(Transaction transaction, SvcLogicContext localContext) throws Exception {
284
285         dbService.populateModuleAndRPC(transaction, localContext.getAttribute(VNF_TYPE));
286         ObjectMapper mapper = new ObjectMapper();
287         log.debug("Individual Transaction Details :" + transaction.toString());
288
289         if ((localContext.getAttribute(SEQUENCE_TYPE) == null) || (localContext.getAttribute(SEQUENCE_TYPE) != null
290                 && !localContext.getAttribute(SEQUENCE_TYPE).equalsIgnoreCase(DESINGTIME))) {
291
292             localContext.setAttribute("artifact-content", mapper.writeValueAsString(transaction));
293             dbService.loadSequenceIntoDB(localContext);
294         }
295         // get a field in transction class as transactionhandle interface and register
296         // the Handler here for each transactions
297     }
298
299 }