e78f8f0e563281751b715b208e85890f43f4de4f
[so/adapters/so-cnf-adapter.git] /
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.cnfm.lcm.bpmn.flows.tasks;
22
23 import static org.onap.so.cnfm.lcm.bpmn.flows.CamundaVariableNameConstants.AS_DEPLOYMENT_ITEM_INST_ID_PARAM_NAME;
24 import static org.onap.so.cnfm.lcm.bpmn.flows.CamundaVariableNameConstants.KUBE_CONFIG_FILE_PATH_PARAM_NAME;
25 import static org.onap.so.cnfm.lcm.bpmn.flows.CamundaVariableNameConstants.KUBE_KINDS_PARAM_NAME;
26 import static org.onap.so.cnfm.lcm.bpmn.flows.CamundaVariableNameConstants.KUBE_KINDS_RESULT_PARAM_NAME;
27 import static org.onap.so.cnfm.lcm.bpmn.flows.CamundaVariableNameConstants.RELEASE_NAME_PARAM_NAME;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import org.camunda.bpm.engine.delegate.DelegateExecution;
34 import org.onap.so.cnfm.lcm.bpmn.flows.extclients.aai.AaiServiceProvider;
35 import org.onap.so.cnfm.lcm.bpmn.flows.extclients.helm.HelmClient;
36 import org.onap.so.cnfm.lcm.bpmn.flows.extclients.kubernetes.KubernetesClientProvider;
37 import org.onap.so.cnfm.lcm.bpmn.flows.extclients.kubernetes.KubernetesResource;
38 import org.onap.so.cnfm.lcm.database.beans.AsInst;
39 import org.onap.so.cnfm.lcm.database.beans.JobStatusEnum;
40 import org.onap.so.cnfm.lcm.database.beans.State;
41 import org.onap.so.cnfm.lcm.database.service.DatabaseServiceProvider;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.stereotype.Component;
46
47 /**
48  *
49  * @author Raviteja karumuri (raviteja.karumuri@est.tech)
50  *
51  */
52
53 @Component
54 public class TerminateDeploymentItemTask extends AbstractServiceTask {
55
56     private static final Logger logger = LoggerFactory.getLogger(TerminateDeploymentItemTask.class);
57
58     private static final String IS_DELETED_PARAM_NAME = "isDeleted";
59     private static final String TERMINATE_REQUEST_PARAM_NAME = "request";
60
61     private final AaiServiceProvider aaiServiceProvider;
62     private final HelmClient helmClient;
63     private final KubernetesClientProvider kubernetesClientProvider;
64
65     @Autowired
66     protected TerminateDeploymentItemTask(final DatabaseServiceProvider databaseServiceProvider,
67             final AaiServiceProvider aaiServiceProvider, final HelmClient helmClient,
68             final KubernetesClientProvider kubernetesClientProvider) {
69         super(databaseServiceProvider);
70         this.aaiServiceProvider = aaiServiceProvider;
71         this.helmClient = helmClient;
72         this.kubernetesClientProvider = kubernetesClientProvider;
73     }
74
75     public void checkIfDeploymentItemExistsInDb(final DelegateExecution execution) {
76         logger.info("Executing checkIfDeploymentItemExistsInDb");
77         final TerminateDeploymentItemRequest request =
78                 (TerminateDeploymentItemRequest) execution.getVariable(TERMINATE_REQUEST_PARAM_NAME);
79         logger.info("Terminate request: {}", request);
80
81         final String asDeploymentItemInstId = request.getAsDeploymentItemInstId();
82         addJobStatus(execution, JobStatusEnum.IN_PROGRESS,
83                 "Checking if Deployment item record exists in database for asDeploymentItemInstId: "
84                         + asDeploymentItemInstId);
85
86         if (!databaseServiceProvider.isAsDeploymentItemExists(request.getAsDeploymentItemInstId())) {
87             abortOperation(execution, "Deployment Item does not exists in database for asDeploymentItemInstId: "
88                     + asDeploymentItemInstId);
89         }
90         execution.setVariable(AS_DEPLOYMENT_ITEM_INST_ID_PARAM_NAME, request.getAsDeploymentItemInstId());
91         execution.setVariable(KUBE_CONFIG_FILE_PATH_PARAM_NAME, request.getKubeConfigFile());
92         logger.info("Finished executing checkIfDeploymentItemExistsInDb  ...");
93
94     }
95
96     public void unInstantiateHelmChart(final DelegateExecution execution) {
97         logger.info("Executing unInstantiateHelmChart");
98
99         final TerminateDeploymentItemRequest request =
100                 (TerminateDeploymentItemRequest) execution.getVariable(TERMINATE_REQUEST_PARAM_NAME);
101         final String releaseName = request.getReleaseName();
102
103         try {
104             final Path kubeConfigFilePath = Paths.get(request.getKubeConfigFile());
105             helmClient.unInstallHelmChart(releaseName, kubeConfigFilePath);
106         } catch (final Exception exception) {
107             final String message = "Failed to uninstall helm chart: " + " using kube-config file: "
108                     + request.getKubeConfigFile() + "for reason: " + exception.getMessage();
109             logger.error(message, exception);
110             abortOperation(execution, message);
111         }
112         logger.info("Finished executing unInstantiateHelmChart  ...");
113
114     }
115
116
117     public void updateDeploymentItemStatusToNotInstantiated(final DelegateExecution execution) {
118
119         logger.info("Executing updateDeploymentItemStatusToNotInstantiated");
120         final TerminateDeploymentItemRequest request =
121                 (TerminateDeploymentItemRequest) execution.getVariable(TERMINATE_REQUEST_PARAM_NAME);
122
123         updateDeploymentItemStatus(execution, request.getAsDeploymentItemInstId(), State.NOT_INSTANTIATED);
124
125         addJobStatus(execution, JobStatusEnum.FINISHED, "Successfully Terminated Deployment Item with "
126                 + "releaseName: " + request.getReleaseName() + " and will set status to " + State.NOT_INSTANTIATED);
127
128         logger.info("Finished executing updateDeploymentItemStatusToNotInstantiated  ...");
129     }
130
131     public void getKubeKindsUsingManifestCommand(final DelegateExecution execution) {
132
133         logger.info("Executing getKubeKindsFromReleaseHistory");
134
135         final TerminateDeploymentItemRequest request =
136                 (TerminateDeploymentItemRequest) execution.getVariable(TERMINATE_REQUEST_PARAM_NAME);
137         final String releaseName = request.getReleaseName();
138         final Path kubeConfigFilePath = Paths.get(request.getKubeConfigFile());
139         final Map<String, Boolean> kubeKindsMap = new HashMap<>();
140         final List<String> kinds = helmClient.getKubeKindsUsingManifestCommand(releaseName, kubeConfigFilePath);
141         if (kinds.isEmpty()) {
142             abortOperation(execution,
143                     "Unable to retrieve kinds from helm release history for releaseName: " + releaseName);
144         }
145         kinds.forEach(kind -> kubeKindsMap.put(kind, false));
146
147         execution.setVariable(RELEASE_NAME_PARAM_NAME, releaseName);
148         execution.setVariable(KUBE_KINDS_RESULT_PARAM_NAME, kubeKindsMap);
149         execution.setVariable(KUBE_KINDS_PARAM_NAME, kinds);
150     }
151
152     public void checkIfHelmUnInstallWasSuccessful(final DelegateExecution execution) {
153         logger.info("Executing checkIfHelmUnInstallWasSuccessful");
154
155         @SuppressWarnings("unchecked")
156         final Map<String, Boolean> kubeKindResult =
157                 (Map<String, Boolean>) execution.getVariable(KUBE_KINDS_RESULT_PARAM_NAME);
158
159         execution.setVariable(IS_DELETED_PARAM_NAME, true);
160
161         kubeKindResult.forEach((key, value) -> {
162             logger.info("Checking if resource type {} was deleted Status: {}", key, value);
163
164             if (Boolean.FALSE.equals(value)) {
165                 logger.error("resource type {} failed to delete", key);
166                 execution.setVariable(IS_DELETED_PARAM_NAME, false);
167             }
168         });
169
170         final String kubeConfigFile = (String) execution.getVariable(KUBE_CONFIG_FILE_PATH_PARAM_NAME);
171         kubernetesClientProvider.closeApiClient(kubeConfigFile);
172
173         logger.info("Finished executing checkIfHelmUnInstallWasSuccessful  ...");
174
175     }
176
177     public void deleteK8ResourcesinAAI(final DelegateExecution execution) {
178         logger.info("Executing deleteK8ResourcesinAai");
179         final TerminateDeploymentItemRequest request =
180                 (TerminateDeploymentItemRequest) execution.getVariable(TERMINATE_REQUEST_PARAM_NAME);
181         final List<KubernetesResource> resources =
182                 aaiServiceProvider.getK8sResources(request.getAsInstId(), request.getAsDeploymentItemInstId());
183         final AsInst asInst = getAsInst(execution);
184         resources.forEach(resource -> aaiServiceProvider.deleteK8SResource(resource.getId(), asInst.getCloudOwner(),
185                 asInst.getCloudRegion(), asInst.getTenantId()));
186     }
187
188     public void deleteVFModuleinAai(final DelegateExecution execution) {
189         logger.info("Executing deleteVFModuleinAai");
190
191         final TerminateDeploymentItemRequest request =
192                 (TerminateDeploymentItemRequest) execution.getVariable(TERMINATE_REQUEST_PARAM_NAME);
193         aaiServiceProvider.deleteVfModule(request.getAsInstId(), request.getAsDeploymentItemInstId());
194         logger.info("Delete VfModule in AAi is Done");
195
196     }
197
198 }