ea3405d423960a9943dde1b9a70b345b447b3091
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix
4  *  Modifications Copyright (C) 2020 Huawei Technologies Co., Ltd.
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
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.so.bpmn.infrastructure.decisionpoint.impl.camunda.controller.sdnc;
22
23 import java.util.List;
24 import java.util.UUID;
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import org.springframework.stereotype.Component;
28 import org.camunda.bpm.engine.delegate.DelegateExecution;
29 import org.onap.so.bpmn.infrastructure.decisionpoint.api.ControllerContext;
30 import org.onap.so.bpmn.infrastructure.decisionpoint.impl.camunda.controller.common.SoPropertyConstants;
31 import org.onap.so.bpmn.infrastructure.decisionpoint.impl.camunda.controller.LcmControllerDE;
32 import org.onap.so.client.exception.BadResponseException;
33 import org.onap.so.client.exception.PayloadGenerationException;
34 import org.onap.so.client.sdnc.common.SDNCConstants;
35 import org.onap.so.client.sdnc.lcm.*;
36 import org.onap.so.client.sdnc.lcm.beans.*;
37 import org.onap.so.client.sdnc.lcm.beans.payload.*;
38 import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.REQUEST_ID;
39 import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID;
40 import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.REQUEST_PAYLOAD;
41
42 @Component
43 public class SdncControllerDE extends LcmControllerDE {
44
45     private static final int SDNC_DELEGATE_EXECUTION_ERROR_CODE = 1103;
46
47     @Override
48     public Boolean understand(ControllerContext<DelegateExecution> context) {
49         return context.getControllerActor().equalsIgnoreCase("sdnc");
50     }
51
52     @Override
53     public Boolean ready(ControllerContext<DelegateExecution> context) {
54         return true;
55     }
56
57     @Override
58     protected int callLcmClient(ControllerContext<DelegateExecution> context) {
59         DelegateExecution execution = context.getExecution();
60
61         logger.debug("Running activity for id: {}, name: {}", execution.getCurrentActivityId(),
62                 execution.getCurrentActivityName());
63
64         try {
65             LcmInput lcmInput = buildLcmInput(execution);
66             sendLcmRequest(execution, lcmInput);
67
68             execution.setVariable(SoPropertyConstants.CONTROLLER_STATUS, "Success");
69         } catch (Exception e) {
70             execution.setVariable(SoPropertyConstants.CONTROLLER_STATUS, "Failure");
71
72             exceptionUtil.buildAndThrowWorkflowException(execution, SDNC_DELEGATE_EXECUTION_ERROR_CODE, e);
73         }
74
75         logger.debug("Finish activity for id: {}, name: {}", execution.getCurrentActivityId(),
76                 execution.getCurrentActivityName());
77
78         return 0;
79     }
80
81     @Override
82     protected int getErrorCode() {
83         return SDNC_DELEGATE_EXECUTION_ERROR_CODE;
84     }
85
86     private LcmOutput sendSyncRequest(String operation, LcmInput lcmInput) throws BadResponseException {
87         SDNCLcmClientBuilder sdncLcmClientBuilder = new SDNCLcmClientBuilder();
88         SDNCLcmRestClient sdncLcmRestClient;
89         try {
90             sdncLcmRestClient = sdncLcmClientBuilder.newSDNCLcmRestClient(operation);
91         } catch (SDNCLcmClientBuilderException e) {
92             logger.error("Create SDNCLcmRestClient error: ", e);
93             throw new BadResponseException("Can not send request to SDNC.");
94         }
95
96         LcmOutput lcmOutput;
97         try {
98             lcmOutput = sdncLcmRestClient.sendRequest(lcmInput);
99         } catch (Exception e) {
100             logger.error("SDNCLcmRestClient sends request failure: ", e);
101             throw new BadResponseException("Send request to SDNC failure.");
102         }
103         return lcmOutput;
104     }
105
106     private LcmOutput selectLcmOutputFromDmaapResponses(List<LcmDmaapResponse> lcmDmaapResponses, LcmInput lcmInput) {
107         String requestId = lcmInput.getCommonHeader().getRequestId();
108         String subRequestId = lcmInput.getCommonHeader().getSubRequestId();
109
110         for (LcmDmaapResponse lcmDmaapResponse : lcmDmaapResponses) {
111             LcmOutput lcmOutput = lcmDmaapResponse.getBody().getOutput();
112             if (requestId.equals(lcmOutput.getCommonHeader().getRequestId())
113                     && subRequestId.equals(lcmOutput.getCommonHeader().getSubRequestId())) {
114                 return lcmOutput;
115             }
116         }
117
118         return null;
119     }
120
121     private LcmOutput sendAsyncRequest(String operation, LcmInput lcmInput) throws BadResponseException {
122         SDNCLcmClientBuilder sdncLcmClientBuilder = new SDNCLcmClientBuilder();
123         SDNCLcmDmaapClient sdncLcmDmaapClient;
124         try {
125             sdncLcmDmaapClient = sdncLcmClientBuilder.newSDNCLcmDmaapClient();
126         } catch (SDNCLcmClientBuilderException e) {
127             logger.error("Create SDNCLcmDmaapClient error: ", e);
128             throw new BadResponseException("Can not send request to SDNC.");
129         }
130
131         LcmDmaapRequest lcmDmaapRequest = SDNCLcmMessageBuilder.buildLcmDmaapRequest(operation, lcmInput);
132         try {
133             sdncLcmDmaapClient.sendRequest(lcmDmaapRequest);
134         } catch (Exception e) {
135             logger.error("SDNCLcmDmaapClient sends request failure: ", e);
136             throw new BadResponseException("Send request to SDNC failure.");
137         }
138
139         long timeout = sdncLcmClientBuilder.getSDNCLcmProperties().getActionTimeout();
140         long startTime = System.currentTimeMillis();
141         while (true) {
142             List<LcmDmaapResponse> lcmDmaapResponses = sdncLcmDmaapClient.getResponse();
143             if (lcmDmaapResponses.size() > 0) {
144                 LcmOutput lcmOutput = selectLcmOutputFromDmaapResponses(lcmDmaapResponses, lcmInput);
145                 if (lcmOutput != null) {
146                     return lcmOutput;
147                 }
148             }
149
150             long stopTime = System.currentTimeMillis();
151             if ((stopTime - startTime) > timeout) {
152                 String msg = "Timeout for SDNC LCM action " + lcmInput.getAction();
153                 logger.error(msg);
154                 throw new BadResponseException(msg);
155             }
156         }
157     }
158
159     public static String toLowerHyphen(String lcmAction) {
160         String regex = "([a-z0-9A-Z])(?=[A-Z])";
161         String replacement = "$1-";
162         return lcmAction.replaceAll(regex, replacement).toLowerCase();
163     }
164
165     private String convertToSting(Object msgObject) throws PayloadGenerationException {
166         try {
167             return SDNCLcmPayloadBuilder.convertToSting(msgObject);
168         } catch (JsonProcessingException e) {
169             throw new PayloadGenerationException(e.getMessage());
170         }
171     }
172
173     private LcmInput buildLcmInput(DelegateExecution execution) throws PayloadGenerationException {
174         String requestId = String.valueOf(execution.getVariable(REQUEST_ID));
175         String requestAction = String.valueOf(execution.getVariable(SoPropertyConstants.SO_ACTION));
176         String pnfName = String.valueOf(execution.getVariable(PNF_CORRELATION_ID));
177         logger.debug(String.format("requestId: %s, action: %s, pnfName: %s", requestId, requestAction, pnfName));
178
179         String requestPayload = String.valueOf(execution.getVariable(REQUEST_PAYLOAD));
180         logger.debug("SO request payload: " + requestPayload);
181
182         String lcmAction;
183         String lcmPayload;
184
185         switch (requestAction) {
186             case SoPropertyConstants.ACTION_PRE_CHECK:
187                 lcmAction = SDNCLcmActionConstants.UPGRADE_PRE_CHECK;
188
189                 UpgradePreCheckPayload upgradePreCheckPayload;
190                 upgradePreCheckPayload = SDNCLcmPayloadBuilder.buildUpgradePreCheckPayload(execution);
191                 lcmPayload = convertToSting(upgradePreCheckPayload);
192                 break;
193             case SoPropertyConstants.ACTION_DOWNLOAD_N_E_SW:
194                 lcmAction = SDNCLcmActionConstants.DOWNLOAD_N_E_SW;
195
196                 DownloadNESwPayload downloadNESwPayload;
197                 downloadNESwPayload = SDNCLcmPayloadBuilder.buildDownloadNESwPayload(execution);
198                 lcmPayload = convertToSting(downloadNESwPayload);
199                 break;
200             case SoPropertyConstants.ACTION_ACTIVATE_N_E_SW:
201                 lcmAction = SDNCLcmActionConstants.ACTIVATE_N_E_SW;
202
203                 ActivateNESwPayload activateNESwPayload;
204                 activateNESwPayload = SDNCLcmPayloadBuilder.buildActivateNESwPayload(execution);
205                 lcmPayload = convertToSting(activateNESwPayload);
206                 break;
207             case SoPropertyConstants.ACTION_POST_CHECK:
208                 lcmAction = SDNCLcmActionConstants.UPGRADE_POST_CHECK;
209
210                 UpgradePostCheckPayload upgradePostCheckPayload;
211                 upgradePostCheckPayload = SDNCLcmPayloadBuilder.buildUpgradePostCheckPayload(execution);
212                 lcmPayload = convertToSting(upgradePostCheckPayload);
213                 break;
214             default:
215                 String msg = "Unsupported SO Action: " + requestAction;
216                 logger.error(msg);
217                 throw new PayloadGenerationException(msg);
218         }
219
220         String subRequestId = UUID.randomUUID().toString();
221         LcmInput lcmInput =
222                 SDNCLcmMessageBuilder.buildLcmInputForPnf(requestId, subRequestId, pnfName, lcmAction, lcmPayload);
223
224         ObjectMapper mapper = new ObjectMapper();
225         try {
226             String lcmInputMsg = mapper.writeValueAsString(lcmInput);
227             logger.debug("SDNC input message for {}: {}", lcmAction, lcmInputMsg);
228         } catch (JsonProcessingException e) {
229             throw new PayloadGenerationException(e.getMessage());
230         }
231
232         return lcmInput;
233     }
234
235     private void parseLcmOutput(LcmOutput lcmOutput, String lcmAction) throws BadResponseException {
236         LcmStatus lcmStatus = lcmOutput.getStatus();
237         int lcmStatusCode = lcmStatus.getCode();
238         String outputPayload = lcmOutput.getPayload();
239
240         if (lcmStatusCode == SDNCConstants.LCM_OUTPUT_SUCCESS_CODE) {
241             logger.debug("Call SDNC LCM API for {} success, code: {}, message: {}, payload: {}", lcmAction,
242                     lcmStatusCode, lcmStatus.getMessage(), outputPayload);
243         } else {
244             String msg = String.format("Call SDNC LCM API for %s failure, code: %d, message: %s, payload: %s",
245                     lcmAction, lcmStatusCode, lcmStatus.getMessage(), outputPayload);
246             logger.error(msg);
247             throw new BadResponseException(msg);
248         }
249     }
250
251     private void sendLcmRequest(DelegateExecution execution, LcmInput lcmInput) throws BadResponseException {
252         String actionMode = String.valueOf(execution.getVariable(SoPropertyConstants.SO_ACTION_MODE));
253         String lcmOperation = toLowerHyphen(lcmInput.getAction());
254
255         LcmOutput lcmOutput;
256         if ("async".equals(actionMode)) {
257             lcmOutput = sendAsyncRequest(lcmOperation, lcmInput);
258         } else {
259             lcmOutput = sendSyncRequest(lcmOperation, lcmInput);
260         }
261
262         parseLcmOutput(lcmOutput, lcmInput.getAction());
263     }
264 }