Code & Workflow Enhancements for CNF - Upgrade
[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         GenericVnf genericVnfId = null;
134         VfModule vfModuleId = null;
135         try {
136             genericVnfId = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
137             vfModuleId = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
138         } catch (Exception ex) {
139             logger.error("Exception occurred", ex);
140         }
141
142         String heatStackId = execution.getVariable("heatStackId");
143
144         logger.debug("heatStackId: {}", heatStackId);
145         CloudRegion cloudRegion = gBBInput.getCloudRegion();
146         String requestId = execution.getVariable("mso-request-id");
147
148         String callbackUrl =
149                 "http://so-bpmn-infra.onap:8081/mso/WorkflowMessage/" + CNF_ADAPTER_MESSAGE_TYPE + "/" + requestId;
150
151         CnfAaiUpdateRequest aaiRequest =
152                 createCnfAaiUpdateRequest(heatStackId, cloudRegion, callbackUrl, genericVnfId, vfModuleId);
153
154         logger.debug("aaiRequest: {}", aaiRequest);
155
156         String cnfRequestPayload = "";
157         try {
158             cnfRequestPayload = mapper.writeValueAsString(aaiRequest);
159         } catch (JsonProcessingException e) {
160             logger.error("Exception occurred", e);
161             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e);
162         }
163
164         // Prepare values to pass in execution variable for CNF Adapter async Handling
165         execution.setVariable("messageType", CNF_ADAPTER_MESSAGE_TYPE);
166         execution.setVariable("correlator", requestId);
167         execution.setVariable("timeout", CNF_ADAPTER_CALLBACK_TIMEOUT);
168
169         String currentFlow = execution.getFlowToBeCalled();
170         logger.debug("currentFlow: {}", currentFlow);
171
172         String apiPath = "http://so-cnf-adapter:8090";
173         if ("CreateVfModuleBB".equals(currentFlow) || ("UpgradeVfModuleBB".equals(currentFlow))) {
174             apiPath = apiPath + "/api/cnf-adapter/v1/aai-update/";
175         } else if ("DeleteVfModuleBB".equals(currentFlow)) {
176             apiPath = apiPath + "/api/cnf-adapter/v1/aai-delete/";
177         }
178
179         // Set variables in execution variable\
180         execution.setVariable("apiPath", apiPath);
181         execution.setVariable("cnfRequestPayload", cnfRequestPayload);
182     }
183
184     public void processCnfUpdateOrDeleteAsyncResponse(BuildingBlockExecution execution) {
185
186         String asyncResponse = execution.getVariable("asyncCallbackResponse");
187
188         CnfAaiUpdateResponse response = new CnfAaiUpdateResponse();
189
190         logger.debug("asyncResponse: {}", asyncResponse);
191
192         try {
193             response = mapper.readValue(asyncResponse, CnfAaiUpdateResponse.class);
194         } catch (JsonProcessingException e) {
195             logger.error("Error in parsing Cnf AAI update Response");
196             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e);
197         }
198
199         if (!"COMPLETED".equalsIgnoreCase(response.getStatus())) {
200             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, new RuntimeException("Cannot update in AAI"));
201         }
202     }
203
204     protected CnfAaiUpdateRequest createCnfAaiUpdateRequest(String heatStackId, CloudRegion cloudRegion,
205             String callbackUrl, GenericVnf genericVnfId, VfModule vfModuleId) {
206         CnfAaiUpdateRequest request = new CnfAaiUpdateRequest();
207         request.setCallbackUrl(callbackUrl);
208         request.setCloudOwner(cloudRegion.getCloudOwner());
209         request.setCloudRegion(cloudRegion.getLcpCloudRegionId());
210         request.setTenantId(cloudRegion.getTenantId());
211         request.setInstanceId(heatStackId);
212         request.setGenericVnfId(genericVnfId.getVnfId());
213         request.setVfModuleId(vfModuleId.getVfModuleId());
214         return request;
215     }
216
217 }