832d67535a6645564e9f4ecad2119605d73c2c4a
[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 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;
34
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;
47 import java.util.Map;
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;
68
69 /**
70  *
71  * @author Waqas Ikram (waqas.ikram@est.tech)
72  *
73  */
74 public class TerminateAsTaskTest extends BaseTest {
75
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();
79
80     @Value("${cnfm.kube-configs-dir}")
81     private String kubeConfigsDir;
82
83     @Autowired
84     private JobExecutorService objUnderTest;
85
86     @Autowired
87     private MockedHelmClient mockedHelmClient;
88
89     @Autowired
90     private MockedKubernetesClientProvider kubernetesClientProvider;
91
92     @Autowired
93     private GsonProvider gsonProvider;
94
95     private Gson gson;
96
97     @Before
98     public void before() {
99
100         wireMockServer.resetAll();
101         try {
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());
107         }
108         kubernetesClientProvider.setWireMockServer(wireMockServer);
109
110         gson = gsonProvider.getGson();
111     }
112
113     @After
114     public void after() {
115         wireMockServer.resetAll();
116     }
117
118     @Test
119     public void testTerminateAsTask_SuccessfulCase() throws InterruptedException, IOException {
120
121         mockKubernetesClientEndpoint();
122         mockAAIEndPoints();
123         addDummyAsToDatabase(AS_INST_ID);
124
125         final String asLcmOpOccId = objUnderTest.runTerminateAsJob(AS_INST_ID, new TerminateAsRequest());
126
127         final Optional<Job> optional = getJobByResourceId(AS_INST_ID);
128         assertTrue(optional.isPresent());
129         final Job job = optional.get();
130         assertTrue(waitForProcessInstanceToFinish(job.getProcessInstanceId()));
131
132         final HistoricProcessInstance historicProcessInstance = getHistoricProcessInstance(job.getProcessInstanceId());
133         assertNotNull(historicProcessInstance);
134         assertEquals(HistoricProcessInstance.STATE_COMPLETED, historicProcessInstance.getState());
135
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());
140
141         final Optional<AsLcmOpOcc> optionalAsLcmOpOcc = databaseServiceProvider.getAsLcmOpOcc(asLcmOpOccId);
142         assertTrue(optionalAsLcmOpOcc.isPresent());
143         final AsLcmOpOcc asLcmOpOcc = optionalAsLcmOpOcc.get();
144         assertEquals(OperationStateEnum.COMPLETED, asLcmOpOcc.getOperationState());
145
146         final Map<String, Integer> counter = mockedHelmClient.getUnInstallCounter();
147         assertEquals(2, counter.size());
148     }
149
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");
158
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");
164
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");
170
171         asInst.asdeploymentItems(dItemOne);
172         asInst.asdeploymentItems(dItemTwo);
173         databaseServiceProvider.saveAsInst(asInst);
174         createKubeConfigFile(asInst);
175     }
176
177     private void mockKubernetesClientEndpoint() {
178
179         wireMockServer.stubFor(get(urlMatching("/apis/batch/v1/jobs\\?labelSelector.*&watch=false"))
180                 .willReturn(aResponse().withBody(getJobList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
181
182         wireMockServer.stubFor(get(urlMatching("/api/v1/pods\\?labelSelector.*&watch=false"))
183                 .willReturn(aResponse().withBody(getPodList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
184
185         wireMockServer.stubFor(get(urlMatching("/api/v1/services\\?labelSelector.*&watch=false"))
186                 .willReturn(aResponse().withBody(getServiceList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
187
188         wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/deployments\\?labelSelector.*&watch=false")).willReturn(
189                 aResponse().withBody(getDeploymentList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
190
191         wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/daemonsets\\?labelSelector.*&watch=false"))
192                 .willReturn(aResponse().withBody(getDaemonList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
193
194         wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/replicasets\\?labelSelector.*&watch=false")).willReturn(
195                 aResponse().withBody(getReplicaSetList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
196
197         wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/statefulsets\\?labelSelector.*&watch=false")).willReturn(
198                 aResponse().withBody(getStatefulSetList()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
199     }
200
201     private void mockAAIEndPoints() {
202
203         final String vnfEndPoint = "/aai/" + V19 + "/network/generic-vnfs/generic-vnf/" + AS_INST_ID;
204
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()));
208     }
209
210     private String getServiceList() {
211         final V1ServiceList v1SeviceList = new V1ServiceList();
212         v1SeviceList.setApiVersion("v1");
213         v1SeviceList.setKind("ServiceList");
214         return gson.toJson(v1SeviceList);
215     }
216
217     private String getPodList() {
218         final V1PodList v1PodList = new V1PodList();
219         v1PodList.setApiVersion("v1");
220         v1PodList.setKind("PodList");
221         return gson.toJson(v1PodList);
222     }
223
224     private String getJobList() {
225         final V1JobList v1JobList = new V1JobList();
226         v1JobList.setApiVersion("v1");
227         v1JobList.setKind("JobList");
228         return gson.toJson(v1JobList);
229     }
230
231     private String getDeploymentList() {
232         final V1DeploymentList v1DeploymentList = new V1DeploymentList();
233         v1DeploymentList.setApiVersion("v1");
234         v1DeploymentList.setKind("DeploymentList");
235         return gson.toJson(v1DeploymentList);
236     }
237
238     private String getDaemonList() {
239         final V1DaemonSetList v1DaemonSetList = new V1DaemonSetList();
240         v1DaemonSetList.setApiVersion("v1");
241         v1DaemonSetList.setKind("DeploymentList");
242         return gson.toJson(v1DaemonSetList);
243     }
244
245     private String getStatefulSetList() {
246         final V1StatefulSetList v1StatefulSetList = new V1StatefulSetList();
247         v1StatefulSetList.setApiVersion("v1");
248         v1StatefulSetList.setKind("DeploymentList");
249         return gson.toJson(v1StatefulSetList);
250     }
251
252     private String getReplicaSetList() {
253         final V1ReplicaSetList v1ReplicaSetList = new V1ReplicaSetList();
254         v1ReplicaSetList.setApiVersion("v1");
255         v1ReplicaSetList.setKind("DeploymentList");
256         return gson.toJson(v1ReplicaSetList);
257     }
258
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");
264         return vnf;
265     }
266
267 }