Adding namespace support
[so.git] / bpmn / so-bpmn-tasks / src / main / java / org / onap / so / bpmn / infrastructure / adapter / cnfm / tasks / CnfInstantiateTask.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2023 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
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.adapter.cnfm.tasks;
22
23 import static java.util.Objects.isNull;
24 import static org.onap.so.cnfm.lcm.model.utils.AdditionalParamsConstants.CLOUD_OWNER_PARAM_KEY;
25 import static org.onap.so.cnfm.lcm.model.utils.AdditionalParamsConstants.CLOUD_REGION_PARAM_KEY;
26 import static org.onap.so.cnfm.lcm.model.utils.AdditionalParamsConstants.NAMESPACE_KEY;
27 import static org.onap.so.cnfm.lcm.model.utils.AdditionalParamsConstants.RESOURCE_ID_KEY;
28 import static org.onap.so.cnfm.lcm.model.utils.AdditionalParamsConstants.SERVICE_INSTANCE_ID_PARAM_KEY;
29 import static org.onap.so.cnfm.lcm.model.utils.AdditionalParamsConstants.SERVICE_INSTANCE_NAME_PARAM_KEY;
30 import static org.onap.so.cnfm.lcm.model.utils.AdditionalParamsConstants.TENANT_ID_PARAM_KEY;
31 import java.net.URI;
32 import java.util.ArrayList;
33 import java.util.Collections;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.NoSuchElementException;
37 import java.util.Optional;
38 import org.onap.logging.filter.base.ONAPComponents;
39 import org.onap.so.bpmn.common.BuildingBlockExecution;
40 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
41 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
42 import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
43 import org.onap.so.client.exception.ExceptionBuilder;
44 import org.onap.so.cnfm.lcm.model.AsInfoModificationRequestDeploymentItems;
45 import org.onap.so.cnfm.lcm.model.AsInstance;
46 import org.onap.so.cnfm.lcm.model.CreateAsRequest;
47 import org.onap.so.cnfm.lcm.model.InstantiateAsRequest;
48 import org.onap.so.serviceinstancebeans.CloudConfiguration;
49 import org.onap.so.serviceinstancebeans.ModelInfo;
50 import org.onap.so.serviceinstancebeans.RequestDetails;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.stereotype.Component;
55
56
57 /**
58  * This class performs CNF Instantiation
59  *
60  * @author sagar.shetty@est.tech
61  * @author Waqas Ikram (waqas.ikram@est.tech)
62  * @author Raviteja Karumuri (raviteja.karumuri@est.tech)
63  */
64 @Component
65 public class CnfInstantiateTask {
66     private static final String DEPLOYMENT_ITEMS_KEY = "deploymentItems";
67     private static final String CREATE_AS_REQUEST_OBJECT = "CreateAsRequestObject";
68     private static final String INSTANTIATE_AS_REQUEST_OBJECT = "InstantiateAsRequest";
69     private static final String CNFM_REQUEST_STATUS_CHECK_URL = "CnfmStatusCheckUrl";
70     private static final String MONITOR_JOB_NAME = "MonitorJobName";
71     private static final String AS_INSTANCE_ID = "asInstanceid";
72     private static final Logger LOGGER = LoggerFactory.getLogger(CnfInstantiateTask.class);
73     private final ExceptionBuilder exceptionUtil;
74     private final CnfmHttpServiceProvider cnfmHttpServiceProvider;
75
76     @Autowired
77     public CnfInstantiateTask(final CnfmHttpServiceProvider cnfmHttpServiceProvider,
78             final ExceptionBuilder exceptionUtil) {
79         this.cnfmHttpServiceProvider = cnfmHttpServiceProvider;
80         this.exceptionUtil = exceptionUtil;
81     }
82
83     public void createCreateAsRequest(final BuildingBlockExecution execution) {
84         try {
85             LOGGER.debug("Executing createAsRequest task  ...");
86             final ExecuteBuildingBlock executeBuildingBlock =
87                     (ExecuteBuildingBlock) execution.getVariable("buildingBlock");
88
89             final GeneralBuildingBlock generalBuildingBlock = execution.getGeneralBuildingBlock();
90
91             final RequestDetails requestDetails = executeBuildingBlock.getRequestDetails();
92             LOGGER.debug("RequestDetails: {}", requestDetails);
93
94             if (isNull(requestDetails) || isNull(requestDetails.getModelInfo())
95                     || isNull(requestDetails.getRequestInfo())
96                     || isNull(requestDetails.getCloudConfiguration()) && isNull(generalBuildingBlock)) {
97                 LOGGER.error("Missing Mandatory attribute from RequestDetails: {} or GeneralBuildingBlock: {}",
98                         requestDetails, generalBuildingBlock);
99                 exceptionUtil.buildAndThrowWorkflowException(execution, 2000,
100                         "Missing Mandatory attribute from RequestDetails or GeneralBuildingBlock", ONAPComponents.SO);
101             }
102
103             final ModelInfo modelInfo = requestDetails.getModelInfo();
104             final CloudConfiguration cloudConfiguration = requestDetails.getCloudConfiguration();
105             final ServiceInstance serviceInstance = generalBuildingBlock.getServiceInstance();
106             final String resourceId = executeBuildingBlock.getResourceId();
107
108             final CreateAsRequest createAsRequest = new CreateAsRequest().asdId(modelInfo.getModelVersionId())
109                     .asInstanceName(requestDetails.getRequestInfo().getInstanceName())
110                     .putAdditionalParamsItem(CLOUD_OWNER_PARAM_KEY, cloudConfiguration.getCloudOwner())
111                     .putAdditionalParamsItem(CLOUD_REGION_PARAM_KEY, cloudConfiguration.getLcpCloudRegionId())
112                     .putAdditionalParamsItem(TENANT_ID_PARAM_KEY, cloudConfiguration.getTenantId())
113                     .putAdditionalParamsItem(SERVICE_INSTANCE_ID_PARAM_KEY, serviceInstance.getServiceInstanceId())
114                     .putAdditionalParamsItem(SERVICE_INSTANCE_NAME_PARAM_KEY, serviceInstance.getServiceInstanceName())
115                     .putAdditionalParamsItem(RESOURCE_ID_KEY, resourceId);
116
117             final List<Map<String, Object>> userParams = requestDetails.getRequestParameters().getUserParams();
118             if (userParams != null) {
119                 userParams.stream().filter(entry -> entry.containsKey(NAMESPACE_KEY)).findAny()
120                         .ifPresent(userParam -> createAsRequest.putAdditionalParamsItem(NAMESPACE_KEY,
121                                 userParam.get(NAMESPACE_KEY)));
122             }
123
124             LOGGER.debug("Adding CreateAsRequest to execution {}", createAsRequest);
125
126             execution.setVariable(CREATE_AS_REQUEST_OBJECT, createAsRequest);
127             LOGGER.debug("Finished executing createAsRequest task ...");
128
129         } catch (final Exception exception) {
130             LOGGER.error("Unable to create CreateAsRequest", exception);
131             exceptionUtil.buildAndThrowWorkflowException(execution, 2001, exception);
132         }
133     }
134
135     public void invokeCnfmWithCreateAsRequest(final BuildingBlockExecution execution) {
136         try {
137             final CreateAsRequest createAsRequest = execution.getVariable(CREATE_AS_REQUEST_OBJECT);
138
139             final Optional<AsInstance> optional = cnfmHttpServiceProvider.invokeCreateAsRequest(createAsRequest);
140
141             if (optional.isEmpty()) {
142                 LOGGER.error("Unable to invoke CNFM for CreateAsRequest : {}", createAsRequest);
143                 exceptionUtil.buildAndThrowWorkflowException(execution, 2003,
144                         "Unable to invoke CNFM for CreateAsRequest", ONAPComponents.SO);
145             }
146
147             final AsInstance asInstance =
148                     optional.orElseThrow(() -> new NoSuchElementException("AsInstance object is empty"));
149             execution.setVariable(AS_INSTANCE_ID, asInstance.getAsInstanceid());
150             LOGGER.debug("Successfully invoked CNFM response: {}", asInstance);
151
152         } catch (final Exception exception) {
153             LOGGER.error("Unable to invoke CNFM AsCreateRequest", exception);
154             exceptionUtil.buildAndThrowWorkflowException(execution, 2004, exception);
155         }
156     }
157
158     public void createAsInstanceRequest(final BuildingBlockExecution execution) {
159         try {
160             LOGGER.debug("Executing createAsInstanceRequest task  ...");
161             final ExecuteBuildingBlock executeBuildingBlock =
162                     (ExecuteBuildingBlock) execution.getVariable("buildingBlock");
163             final RequestDetails requestDetails = executeBuildingBlock.getRequestDetails();
164             final InstantiateAsRequest instantiateAsRequest = new InstantiateAsRequest();
165
166             if (requestDetails != null && requestDetails.getRequestParameters() != null) {
167                 final List<Map<String, Object>> userParams = requestDetails.getRequestParameters().getUserParams();
168                 if (userParams != null && !userParams.isEmpty()) {
169                     final List<Object> deploymentItems = getDeploymentItems(userParams);
170                     final List<AsInfoModificationRequestDeploymentItems> deploymentItemsReq = new ArrayList<>();
171                     for (final Object deploymentItem : deploymentItems) {
172                         final Map<String, Object> deploymentItemMap = (Map<String, Object>) deploymentItem;
173                         final AsInfoModificationRequestDeploymentItems item =
174                                 new AsInfoModificationRequestDeploymentItems();
175                         item.setDeploymentItemsId(deploymentItemMap.get("deploymentItemsId").toString());
176                         item.setLifecycleParameterKeyValues(deploymentItemMap.get("lifecycleParameterKeyValues"));
177                         deploymentItemsReq.add(item);
178                     }
179                     instantiateAsRequest.setDeploymentItems(deploymentItemsReq);
180                 }
181             }
182             LOGGER.debug("Adding InstantiateAsRequest to execution {}", instantiateAsRequest);
183
184             execution.setVariable(INSTANTIATE_AS_REQUEST_OBJECT, instantiateAsRequest);
185             LOGGER.debug("Finished executing createAsInstanceRequest task ...");
186
187         } catch (final Exception exception) {
188             LOGGER.error("Unable to create CreateAsInstanceRequest", exception);
189             exceptionUtil.buildAndThrowWorkflowException(execution, 2002, exception);
190         }
191     }
192
193     public void invokeCnfmWithInstantiateAsRequest(final BuildingBlockExecution execution) {
194         try {
195             final InstantiateAsRequest instantiateAsRequest = execution.getVariable(INSTANTIATE_AS_REQUEST_OBJECT);
196             final String asInstanceId = execution.getVariable(AS_INSTANCE_ID);
197             final Optional<URI> cnfStatusCheckURL =
198                     cnfmHttpServiceProvider.invokeInstantiateAsRequest(instantiateAsRequest, asInstanceId);
199             execution.setVariable(CNFM_REQUEST_STATUS_CHECK_URL, cnfStatusCheckURL.orElseThrow());
200             execution.setVariable(MONITOR_JOB_NAME, "Instantiate");
201             LOGGER.debug("Successfully invoked CNFM instantiate AS request: {}", asInstanceId);
202         } catch (final Exception exception) {
203             LOGGER.error("Unable to invoke CNFM InstantiateAsRequest", exception);
204             exceptionUtil.buildAndThrowWorkflowException(execution, 2005, exception);
205         }
206     }
207
208     private List<Object> getDeploymentItems(final List<Map<String, Object>> userParams) {
209         for (final Map<String, Object> userParam : userParams) {
210             if (userParam.containsKey(DEPLOYMENT_ITEMS_KEY)) {
211                 return (ArrayList<Object>) userParam.get(DEPLOYMENT_ITEMS_KEY);
212             }
213         }
214         return Collections.emptyList();
215     }
216 }