Merge "Implementation of HealthCheckBB"
[so.git] / bpmn / so-bpmn-tasks / src / main / java / org / onap / so / bpmn / infrastructure / adapter / cnf / tasks / CnfAdapterCreateTasks.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
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  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.adapter.cnf.tasks;
24
25 import java.io.IOException;
26 import java.util.HashMap;
27 import java.util.Map;
28 import org.onap.so.bpmn.common.BuildingBlockExecution;
29 import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
30 import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
31 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
32 import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
33 import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
34 import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
35 import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
36 import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB;
37 import org.onap.so.client.adapter.cnf.CnfAdapterClient;
38 import org.onap.so.client.adapter.cnf.entities.CnfAaiUpdateRequest;
39 import org.onap.so.client.adapter.cnf.entities.CnfAaiUpdateResponse;
40 import org.onap.so.client.adapter.cnf.entities.InstanceRequest;
41 import org.onap.so.client.adapter.cnf.entities.InstanceResponse;
42 import org.onap.so.client.adapter.vnf.mapper.AttributeNameValue;
43 import org.onap.so.client.adapter.vnf.mapper.Attributes;
44 import org.onap.so.client.adapter.vnf.mapper.VnfAdapterVfModuleObjectMapper;
45 import org.onap.so.client.exception.ExceptionBuilder;
46 import org.onap.so.openstack.utils.MsoMulticloudUtils;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.stereotype.Component;
51 import com.fasterxml.jackson.core.JsonParseException;
52 import com.fasterxml.jackson.core.JsonProcessingException;
53 import com.fasterxml.jackson.databind.JsonMappingException;
54 import com.fasterxml.jackson.databind.ObjectMapper;
55
56 @Component
57 public class CnfAdapterCreateTasks {
58     private static final Logger logger = LoggerFactory.getLogger(CnfAdapterCreateTasks.class);
59     public static final String SDNCQUERY_RESPONSE = "SDNCQueryResponse_";
60     private static final String CNF_ADAPTER_MESSAGE_TYPE = "CNFCallback";
61     private static final String CNF_ADAPTER_CALLBACK_TIMEOUT = "PT30M";
62
63     @Autowired
64     private ExtractPojosForBB extractPojosForBB;
65     @Autowired
66     private ExceptionBuilder exceptionUtil;
67     @Autowired
68     private CnfAdapterClient cnfAdapterClient;
69     @Autowired
70     private VnfAdapterVfModuleObjectMapper vfModuleMapper;
71
72     private ObjectMapper mapper = new ObjectMapper();
73
74     /**
75      * This method is used for creating the request for an Instance in Multicloud K8s Plugin.
76      *
77      * @param execution
78      * @return
79      */
80     public void createInstance(BuildingBlockExecution execution) {
81         try {
82             GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
83             ServiceInstance serviceInstance =
84                     gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0);
85             GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
86             VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
87             RequestContext requestContext = gBBInput.getRequestContext();
88             CloudRegion cloudRegion = gBBInput.getCloudRegion();
89             String sdncVfModuleQueryResponse = execution.getVariable(SDNCQUERY_RESPONSE + vfModule.getVfModuleId());
90             String sdncVnfQueryResponse = execution.getVariable(SDNCQUERY_RESPONSE + genericVnf.getVnfId());
91             Map<String, Object> paramsMap = vfModuleMapper.buildVfModuleParamsMap(requestContext, serviceInstance,
92                     genericVnf, vfModule, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
93             Map<String, String> sdncDirectives = getSdncDirectives(paramsMap);
94             InstanceRequest createInstanceRequest = createInstanceRequest(vfModule, cloudRegion, sdncDirectives);
95             InstanceResponse response = cnfAdapterClient.createVfModule(createInstanceRequest);
96             execution.setVariable("heatStackId", response.getId());
97         } catch (Exception ex) {
98             logger.error("Exception occurred", ex);
99             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
100         }
101     }
102
103     protected Map<String, String> getSdncDirectives(Map<String, Object> paramsMap)
104             throws JsonParseException, JsonMappingException, IOException {
105         Map<String, String> sdncDirectivesMap = new HashMap<>();
106         String sdncDirectivesString = (String) paramsMap.get(MsoMulticloudUtils.SDNC_DIRECTIVES);
107         Attributes sdncDirectives = mapper.readValue(sdncDirectivesString, Attributes.class);
108         for (AttributeNameValue nameVal : sdncDirectives.getAttributes()) {
109             sdncDirectivesMap.put(nameVal.getAttributeName(), (String) nameVal.getAttributeValue());
110         }
111         return sdncDirectivesMap;
112     }
113
114     protected InstanceRequest createInstanceRequest(VfModule vfModule, CloudRegion cloudRegion,
115             Map<String, String> sdncDirectives) {
116         InstanceRequest request = new InstanceRequest();
117         request.setModelInvariantId(vfModule.getModelInfoVfModule().getModelInvariantUUID());
118         request.setModelVersionId(vfModule.getModelInfoVfModule().getModelUUID());
119         request.setModelCustomizationId(vfModule.getModelInfoVfModule().getModelCustomizationUUID());
120         request.setCloudRegion(cloudRegion.getLcpCloudRegionId());
121         request.setVfModuleUUID(vfModule.getVfModuleId());
122         request.setProfileName(sdncDirectives.get("k8s-rb-profile-name"));
123         request.setReleaseName(sdncDirectives.get("k8s-rb-instance-release-name"));
124         if (sdncDirectives.containsKey("k8s-rb-instance-status-check"))
125             request.setStatusCheck(sdncDirectives.get("k8s-rb-instance-status-check").equalsIgnoreCase("true"));
126         request.setOverrideValues(sdncDirectives);
127         return request;
128     }
129
130     public void prepareForCnfUpdateOrDelete(BuildingBlockExecution execution) {
131
132         GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
133
134         String heatStackId = execution.getVariable("heatStackId");
135
136         logger.debug("heatStackId: {}", heatStackId);
137         CloudRegion cloudRegion = gBBInput.getCloudRegion();
138         String requestId = execution.getVariable("mso-request-id");
139
140         String callbackUrl =
141                 "http://so-bpmn-infra.onap:8081/mso/WorkflowMessage/" + CNF_ADAPTER_MESSAGE_TYPE + "/" + requestId;
142
143         CnfAaiUpdateRequest aaiRequest = createCnfAaiUpdateRequest(heatStackId, cloudRegion, callbackUrl);
144         logger.debug("aaiRequest: {}", aaiRequest);
145
146         String cnfRequestPayload = "";
147         try {
148             cnfRequestPayload = mapper.writeValueAsString(aaiRequest);
149         } catch (JsonProcessingException e) {
150             logger.error("Exception occurred", e);
151             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e);
152         }
153
154         // Prepare values to pass in execution variable for CNF Adapter async Handling
155         execution.setVariable("messageType", CNF_ADAPTER_MESSAGE_TYPE);
156         execution.setVariable("correlator", requestId);
157         execution.setVariable("timeout", CNF_ADAPTER_CALLBACK_TIMEOUT);
158
159         String currentFlow = execution.getFlowToBeCalled();
160         logger.debug("currentFlow: {}", currentFlow);
161
162         String apiPath = "http://so-cnf-adapter:8090";
163         if ("CreateVfModuleBB".equals(currentFlow)) {
164             apiPath = apiPath + "/api/cnf-adapter/v1/aai-update/";
165         } else if ("DeleteVfModuleBB".equals(currentFlow)) {
166             apiPath = apiPath + "/api/cnf-adapter/v1/aai-delete/";
167         }
168
169         // Set variables in execution variable\
170         execution.setVariable("apiPath", apiPath);
171         execution.setVariable("cnfRequestPayload", cnfRequestPayload);
172     }
173
174     public void processCnfUpdateOrDeleteAsyncResponse(BuildingBlockExecution execution) {
175
176         String asyncResponse = execution.getVariable("asyncCallbackResponse");
177
178         CnfAaiUpdateResponse response = new CnfAaiUpdateResponse();
179
180         logger.debug("asyncResponse: {}", asyncResponse);
181
182         try {
183             response = mapper.readValue(asyncResponse, CnfAaiUpdateResponse.class);
184         } catch (JsonProcessingException e) {
185             logger.error("Error in parsing Cnf AAI update Response");
186             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e);
187         }
188
189         if (!"COMPLETED".equalsIgnoreCase(response.getStatus())) {
190             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, new RuntimeException("Cannot update in AAI"));
191         }
192     }
193
194     protected CnfAaiUpdateRequest createCnfAaiUpdateRequest(String heatStackId, CloudRegion cloudRegion,
195             String callbackUrl) {
196         CnfAaiUpdateRequest request = new CnfAaiUpdateRequest();
197         request.setCallbackUrl(callbackUrl);
198         request.setCloudOwner(cloudRegion.getCloudOwner());
199         request.setCloudRegion(cloudRegion.getLcpCloudRegionId());
200         request.setTenantId(cloudRegion.getTenantId());
201         request.setInstanceId(heatStackId);
202
203         return request;
204     }
205
206 }