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
9 * 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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.so.cnfm.lcm.bpmn.flows.tasks;
23 import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
24 import static com.github.tomakehurst.wiremock.client.WireMock.get;
25 import static com.github.tomakehurst.wiremock.client.WireMock.ok;
26 import static com.github.tomakehurst.wiremock.client.WireMock.post;
27 import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertNotNull;
30 import static org.junit.Assert.assertTrue;
31 import static org.onap.aaiclient.client.aai.AAIVersion.V19;
32 import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
33 import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
35 import com.google.gson.Gson;
36 import io.kubernetes.client.openapi.models.V1DaemonSetList;
37 import io.kubernetes.client.openapi.models.V1DeploymentList;
38 import io.kubernetes.client.openapi.models.V1JobList;
39 import io.kubernetes.client.openapi.models.V1PodList;
40 import io.kubernetes.client.openapi.models.V1ReplicaSetList;
41 import io.kubernetes.client.openapi.models.V1ServiceList;
42 import io.kubernetes.client.openapi.models.V1StatefulSetList;
43 import java.io.IOException;
44 import java.nio.file.Files;
45 import java.nio.file.Paths;
46 import java.time.LocalDateTime;
48 import java.util.Optional;
49 import java.util.UUID;
50 import org.camunda.bpm.engine.history.HistoricProcessInstance;
51 import org.junit.After;
52 import org.junit.Before;
53 import org.junit.Test;
54 import org.onap.aai.domain.yang.GenericVnf;
55 import org.onap.so.beans.nsmf.OrchestrationStatusEnum;
56 import org.onap.so.cnfm.lcm.bpmn.flows.BaseTest;
57 import org.onap.so.cnfm.lcm.bpmn.flows.GsonProvider;
58 import org.onap.so.cnfm.lcm.bpmn.flows.service.JobExecutorService;
59 import org.onap.so.cnfm.lcm.database.beans.AsDeploymentItem;
60 import org.onap.so.cnfm.lcm.database.beans.AsInst;
61 import org.onap.so.cnfm.lcm.database.beans.AsLcmOpOcc;
62 import org.onap.so.cnfm.lcm.database.beans.Job;
63 import org.onap.so.cnfm.lcm.database.beans.OperationStateEnum;
64 import org.onap.so.cnfm.lcm.database.beans.State;
65 import org.onap.so.cnfm.lcm.model.TerminateAsRequest;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.springframework.beans.factory.annotation.Value;
71 * @author Waqas Ikram (waqas.ikram@est.tech)
74 public class TerminateAsTaskTest extends BaseTest {
76 private static final String AS_INST_ID = UUID.randomUUID().toString();
77 private static final String AS_DEPLOYMENT_ITEM_ONE_INST_ID = UUID.randomUUID().toString();
78 private static final String AS_DEPLOYMENT_ITEM_TWO_INST_ID = UUID.randomUUID().toString();
80 @Value("${cnfm.kube-configs-dir}")
81 private String kubeConfigsDir;
84 private JobExecutorService objUnderTest;
87 private MockedHelmClient mockedHelmClient;
90 private MockedKubernetesClientProvider kubernetesClientProvider;
93 private GsonProvider gsonProvider;
98 public void before() {
100 wireMockServer.resetAll();
102 deleteFoldersAndFiles(Paths.get(kubeConfigsDir));
103 Files.createDirectory(Paths.get(kubeConfigsDir));
104 } catch (final IOException ioException) {
105 throw new RuntimeException(
106 "Failed to create/Delete Directory in TerminateAsTaskTest due to: " + ioException.getMessage());
108 kubernetesClientProvider.setWireMockServer(wireMockServer);
110 gson = gsonProvider.getGson();
114 public void after() {
115 wireMockServer.resetAll();
119 public void testTerminateAsTask_SuccessfulCase() throws InterruptedException, IOException {
121 mockKubernetesClientEndpoint();
123 addDummyAsToDatabase(AS_INST_ID);
125 final String asLcmOpOccId = objUnderTest.runTerminateAsJob(AS_INST_ID, new TerminateAsRequest());
127 final Optional<Job> optional = getJobByResourceId(AS_INST_ID);
128 assertTrue(optional.isPresent());
129 final Job job = optional.get();
130 assertTrue(waitForProcessInstanceToFinish(job.getProcessInstanceId()));
132 final HistoricProcessInstance historicProcessInstance = getHistoricProcessInstance(job.getProcessInstanceId());
133 assertNotNull(historicProcessInstance);
134 assertEquals(HistoricProcessInstance.STATE_COMPLETED, historicProcessInstance.getState());
136 final Optional<AsInst> optionalAsInst = databaseServiceProvider.getAsInst(AS_INST_ID);
137 assertTrue(optionalAsInst.isPresent());
138 final AsInst updatedAsInst = optionalAsInst.get();
139 assertEquals(State.NOT_INSTANTIATED, updatedAsInst.getStatus());
141 final Optional<AsLcmOpOcc> optionalAsLcmOpOcc = databaseServiceProvider.getAsLcmOpOcc(asLcmOpOccId);
142 assertTrue(optionalAsLcmOpOcc.isPresent());
143 final AsLcmOpOcc asLcmOpOcc = optionalAsLcmOpOcc.get();
144 assertEquals(OperationStateEnum.COMPLETED, asLcmOpOcc.getOperationState());
146 final Map<String, Integer> counter = mockedHelmClient.getUnInstallCounter();
147 assertEquals(2, counter.size());
150 private void addDummyAsToDatabase(final String asInstanceId) throws IOException {
151 final String asInstName = "TerminateCnfService-" + System.currentTimeMillis();
152 final AsInst asInst = new AsInst().asInstId(asInstanceId).name(asInstName).asdId(asInstanceId)
153 .asdInvariantId(asInstanceId).status(State.INSTANTIATED).statusUpdatedTime(LocalDateTime.now())
154 .asApplicationName("asApplicationName").asApplicationVersion("asApplicationVersion")
155 .asProvider("asProvider").serviceInstanceId(SERVICE_INSTANCE_ID)
156 .serviceInstanceName(SERVICE_INSTANCE_NAME).cloudOwner("cloudOwner").cloudRegion("cloudRegion")
157 .tenantId("tenantId");
159 final String helmFile1 = "Artifacts/Deployment/HELM/sampleapp-db-operator-helm.tgz";
160 final AsDeploymentItem dItemOne = new AsDeploymentItem().asDeploymentItemInstId(AS_DEPLOYMENT_ITEM_ONE_INST_ID)
161 .asInst(asInst).status(State.INSTANTIATED).name("sampleapp-db").itemId("1").deploymentOrder(1)
162 .artifactFilePath(helmFile1).createTime(LocalDateTime.now()).lastUpdateTime(LocalDateTime.now())
163 .releaseName("testOne");
165 final String helmFile2 = "Artifacts/Deployment/HELM/sampleapp-services-helm.tgz";
166 final AsDeploymentItem dItemTwo = new AsDeploymentItem().asDeploymentItemInstId(AS_DEPLOYMENT_ITEM_TWO_INST_ID)
167 .asInst(asInst).status(State.INSTANTIATED).name("sampleapp-services").itemId("2").deploymentOrder(2)
168 .artifactFilePath(helmFile2).createTime(LocalDateTime.now()).lastUpdateTime(LocalDateTime.now())
169 .releaseName("testTwo");
171 asInst.asdeploymentItems(dItemOne);
172 asInst.asdeploymentItems(dItemTwo);
173 databaseServiceProvider.saveAsInst(asInst);
174 createKubeConfigFile(asInst);
177 private void mockKubernetesClientEndpoint() {
179 wireMockServer.stubFor(get(urlMatching("/apis/batch/v1/jobs\\?labelSelector.*&watch=false"))
180 .willReturn(aResponse().withBody(getJobList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
182 wireMockServer.stubFor(get(urlMatching("/api/v1/pods\\?labelSelector.*&watch=false"))
183 .willReturn(aResponse().withBody(getPodList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
185 wireMockServer.stubFor(get(urlMatching("/api/v1/services\\?labelSelector.*&watch=false"))
186 .willReturn(aResponse().withBody(getServiceList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
188 wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/deployments\\?labelSelector.*&watch=false")).willReturn(
189 aResponse().withBody(getDeploymentList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
191 wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/daemonsets\\?labelSelector.*&watch=false"))
192 .willReturn(aResponse().withBody(getDaemonList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
194 wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/replicasets\\?labelSelector.*&watch=false")).willReturn(
195 aResponse().withBody(getReplicaSetList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
197 wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/statefulsets\\?labelSelector.*&watch=false")).willReturn(
198 aResponse().withBody(getStatefulSetList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
201 private void mockAAIEndPoints() {
203 final String vnfEndPoint = "/aai/" + V19 + "/network/generic-vnfs/generic-vnf/" + AS_INST_ID;
205 wireMockServer.stubFor(get(urlMatching(vnfEndPoint)).willReturn(
206 aResponse().withBody(gson.toJson(getGenericVnf())).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
207 wireMockServer.stubFor(post(urlMatching(vnfEndPoint)).willReturn(ok()));
210 private String getServiceList() {
211 final V1ServiceList v1SeviceList = new V1ServiceList();
212 v1SeviceList.setApiVersion("v1");
213 v1SeviceList.setKind("ServiceList");
214 return gson.toJson(v1SeviceList);
217 private String getPodList() {
218 final V1PodList v1PodList = new V1PodList();
219 v1PodList.setApiVersion("v1");
220 v1PodList.setKind("PodList");
221 return gson.toJson(v1PodList);
224 private String getJobList() {
225 final V1JobList v1JobList = new V1JobList();
226 v1JobList.setApiVersion("v1");
227 v1JobList.setKind("JobList");
228 return gson.toJson(v1JobList);
231 private String getDeploymentList() {
232 final V1DeploymentList v1DeploymentList = new V1DeploymentList();
233 v1DeploymentList.setApiVersion("v1");
234 v1DeploymentList.setKind("DeploymentList");
235 return gson.toJson(v1DeploymentList);
238 private String getDaemonList() {
239 final V1DaemonSetList v1DaemonSetList = new V1DaemonSetList();
240 v1DaemonSetList.setApiVersion("v1");
241 v1DaemonSetList.setKind("DeploymentList");
242 return gson.toJson(v1DaemonSetList);
245 private String getStatefulSetList() {
246 final V1StatefulSetList v1StatefulSetList = new V1StatefulSetList();
247 v1StatefulSetList.setApiVersion("v1");
248 v1StatefulSetList.setKind("DeploymentList");
249 return gson.toJson(v1StatefulSetList);
252 private String getReplicaSetList() {
253 final V1ReplicaSetList v1ReplicaSetList = new V1ReplicaSetList();
254 v1ReplicaSetList.setApiVersion("v1");
255 v1ReplicaSetList.setKind("DeploymentList");
256 return gson.toJson(v1ReplicaSetList);
259 private GenericVnf getGenericVnf() {
260 final GenericVnf vnf = new GenericVnf();
261 vnf.setVnfId(AS_INST_ID);
262 vnf.setOrchestrationStatus(OrchestrationStatusEnum.ACTIVATED.getValue());
263 vnf.setResourceVersion("12345");