3080459291a58713b9d43696ebe2dd3bc5e15e0e
[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.notFound;
26 import static com.github.tomakehurst.wiremock.client.WireMock.ok;
27 import static com.github.tomakehurst.wiremock.client.WireMock.put;
28 import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
29 import static org.junit.Assert.assertEquals;
30 import static org.junit.Assert.assertNotNull;
31 import static org.junit.Assert.assertThrows;
32 import static org.junit.Assert.assertTrue;
33 import static org.onap.aaiclient.client.aai.AAIVersion.V19;
34 import static org.springframework.http.HttpHeaders.ACCEPT;
35 import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
36 import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE;
37 import java.io.File;
38 import java.io.IOException;
39 import java.nio.file.Files;
40 import java.nio.file.Path;
41 import java.nio.file.Paths;
42 import java.time.LocalDateTime;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Optional;
46 import java.util.UUID;
47 import org.camunda.bpm.engine.history.HistoricProcessInstance;
48 import org.junit.After;
49 import org.junit.Before;
50 import org.junit.Test;
51 import org.onap.so.cnfm.lcm.bpmn.flows.BaseTest;
52 import org.onap.so.cnfm.lcm.bpmn.flows.GsonProvider;
53 import org.onap.so.cnfm.lcm.bpmn.flows.exceptions.AsRequestProcessingException;
54 import org.onap.so.cnfm.lcm.bpmn.flows.service.JobExecutorService;
55 import org.onap.so.cnfm.lcm.database.beans.AsDeploymentItem;
56 import org.onap.so.cnfm.lcm.database.beans.AsInst;
57 import org.onap.so.cnfm.lcm.database.beans.AsLcmOpOcc;
58 import org.onap.so.cnfm.lcm.database.beans.AsLifecycleParam;
59 import org.onap.so.cnfm.lcm.database.beans.Job;
60 import org.onap.so.cnfm.lcm.database.beans.JobStatusEnum;
61 import org.onap.so.cnfm.lcm.database.beans.OperationStateEnum;
62 import org.onap.so.cnfm.lcm.database.beans.State;
63 import org.onap.so.cnfm.lcm.model.AsInfoModificationRequestDeploymentItems;
64 import org.onap.so.cnfm.lcm.model.InstantiateAsRequest;
65 import org.springframework.beans.factory.annotation.Autowired;
66 import org.springframework.beans.factory.annotation.Value;
67 import com.fasterxml.jackson.core.JsonProcessingException;
68 import com.google.gson.Gson;
69 import io.kubernetes.client.custom.IntOrString;
70 import io.kubernetes.client.openapi.models.V1DaemonSet;
71 import io.kubernetes.client.openapi.models.V1DaemonSetList;
72 import io.kubernetes.client.openapi.models.V1DaemonSetSpec;
73 import io.kubernetes.client.openapi.models.V1DaemonSetStatus;
74 import io.kubernetes.client.openapi.models.V1DaemonSetUpdateStrategy;
75 import io.kubernetes.client.openapi.models.V1Deployment;
76 import io.kubernetes.client.openapi.models.V1DeploymentList;
77 import io.kubernetes.client.openapi.models.V1DeploymentSpec;
78 import io.kubernetes.client.openapi.models.V1DeploymentStatus;
79 import io.kubernetes.client.openapi.models.V1Job;
80 import io.kubernetes.client.openapi.models.V1JobCondition;
81 import io.kubernetes.client.openapi.models.V1JobList;
82 import io.kubernetes.client.openapi.models.V1JobStatus;
83 import io.kubernetes.client.openapi.models.V1ObjectMeta;
84 import io.kubernetes.client.openapi.models.V1Pod;
85 import io.kubernetes.client.openapi.models.V1PodCondition;
86 import io.kubernetes.client.openapi.models.V1PodList;
87 import io.kubernetes.client.openapi.models.V1PodStatus;
88 import io.kubernetes.client.openapi.models.V1ReplicaSet;
89 import io.kubernetes.client.openapi.models.V1ReplicaSetList;
90 import io.kubernetes.client.openapi.models.V1ReplicaSetSpec;
91 import io.kubernetes.client.openapi.models.V1ReplicaSetStatus;
92 import io.kubernetes.client.openapi.models.V1RollingUpdateDaemonSet;
93 import io.kubernetes.client.openapi.models.V1RollingUpdateStatefulSetStrategy;
94 import io.kubernetes.client.openapi.models.V1Service;
95 import io.kubernetes.client.openapi.models.V1ServiceList;
96 import io.kubernetes.client.openapi.models.V1StatefulSet;
97 import io.kubernetes.client.openapi.models.V1StatefulSetList;
98 import io.kubernetes.client.openapi.models.V1StatefulSetSpec;
99 import io.kubernetes.client.openapi.models.V1StatefulSetStatus;
100 import io.kubernetes.client.openapi.models.V1StatefulSetUpdateStrategy;
101 import io.kubernetes.client.util.Watch;
102
103 /**
104  * @author Waqas Ikram (waqas.ikram@est.tech)
105  */
106 public class InstantiateAsTaskTest extends BaseTest {
107     private static final String BATCH_V1 = "batch/v1";
108     private static final String V1 = "v1";
109     private static final String APPS_V1 = "apps/v1";
110     private static final String RESPONSE_TYPE_ADDED = "ADDED";
111     private static final String DEPLOYMENT_ITEM_1_RELEASE_NAME = "testOne";
112     private static final String DEPLOYMENT_ITEM_2_RELEASE_NAME = "testTwo";
113     private static final String DEPLOYMENT_ITEM_1_LIFECYCLE_PARAM_1 = ".Values.primary.service.ports.mysql";
114     private static final String DEPLOYMENT_ITEM_1_LIFECYCLE_PARAM_2 = ".Values.primary.service.nodePorts.mysql";
115
116     private static final String DEPLOYMENT_ITEM_2_LIFECYCLE_PARAM_1 = ".Values.service.ports.http";
117     private static final String DEPLOYMENT_ITEM_2_LIFECYCLE_PARAM_2 = ".Values.service.ports.https";
118     private static final String DEPLOYMENT_ITEM_2_LIFECYCLE_PARAM_3 = ".Values.service.nodePorts";
119
120     private static final String DEPLOYMENT_ITEM_LIFECYCLE_PARAM_VALUE = "dummy";
121     private static final String RANDOM_UUID = UUID.randomUUID().toString();
122     private static final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString();
123     private static final String AS_INST_ID = SERVICE_INSTANCE_ID;
124
125     private static final String SERVICE_INSTANCE_ID2 = UUID.randomUUID().toString();
126     private static final String AS_INST_ID2 = SERVICE_INSTANCE_ID2;
127     private static final String ASD_NAME = "InstantiateCnfService";
128     private static final String AS_INST_NAME = ASD_NAME + "-" + System.currentTimeMillis();
129     private static final String ASD_ID = AS_INST_ID;
130     private static final String SRC_TEST_DIR = "src/test/resources";
131
132     private static final String RESOURCE_ASD_PACKAGE_CSAR_PATH =
133             SRC_TEST_DIR + "/resource-Generatedasdpackage-csar.csar";
134
135     private static final String AS_DEPLOYMENT_ITEM_1_INST_ID = UUID.randomUUID().toString();
136     private static final String AS_DEPLOYMENT_ITEM_2_INST_ID = UUID.randomUUID().toString();
137     private static final String AS_DEPLOYMENT_ITEM_1_INST_ID2 = UUID.randomUUID().toString();
138     private static final String AS_DEPLOYMENT_ITEM_2_INST_ID2 = UUID.randomUUID().toString();
139
140     @Value("${cnfm.csar.dir}")
141     private String dir;
142
143     @Value("${cnfm.kube-configs-dir}")
144     private String kubeConfigsDir;
145
146     @Autowired
147     private JobExecutorService objUnderTest;
148
149     @Autowired
150     private MockedHelmClient mockedHelmClient;
151
152     @Autowired
153     private MockedKubernetesClientProvider kubernetesClientProvider;
154
155     @Autowired
156     private GsonProvider gsonProvider;
157     private Gson gson;
158
159     @Before
160     public void before() {
161         wireMockServer.resetAll();
162         try {
163             deleteFoldersAndFiles(Paths.get(kubeConfigsDir));
164             Files.createDirectory(Paths.get(kubeConfigsDir));
165         } catch (final IOException ioException) {
166             throw new RuntimeException(
167                     "Failed to create/Delete Directory in InstantiateAsTaskTest due to: " + ioException.getMessage());
168         }
169         kubernetesClientProvider.setWireMockServer(wireMockServer);
170
171         gson = gsonProvider.getGson();
172         mockedHelmClient.clear();
173     }
174
175     @After
176     public void after() {
177         wireMockServer.resetAll();
178         final Path path = Paths.get(dir, AS_INST_ID);
179         try {
180             deleteFoldersAndFiles(path);
181             deleteFoldersAndFiles(Paths.get(kubeConfigsDir));
182         } catch (final IOException ioException) {
183             logger.debug("Exception occurred while deleting folder and files: {}", ioException.getMessage());
184         }
185     }
186
187     @Test
188     public void testInstantiateAsWorkflow_JustUpdateStatus_SuccessfullCase() throws InterruptedException, IOException {
189
190         mockKubernetesClientEndpoint();
191
192         mockAAIEndpoints();
193
194         mockSdcPackageDownloadEndpoint();
195
196         final AsInst asInst = createAsInst(AS_INST_ID, AS_DEPLOYMENT_ITEM_1_INST_ID, AS_DEPLOYMENT_ITEM_2_INST_ID);
197
198         databaseServiceProvider.saveAsInst(asInst);
199
200         createKubeConfigFile(asInst);
201
202         final String asLcmOpOccId = objUnderTest.runInstantiateAsJob(asInst.getAsInstId(), getInstantiateAsRequest());
203
204         final Optional<Job> optional = getJobByResourceId(asInst.getAsInstId());
205         assertTrue(optional.isPresent());
206         final Job job = optional.get();
207
208
209         assertTrue(waitForProcessInstanceToFinish(job.getProcessInstanceId()));
210
211         final HistoricProcessInstance historicProcessInstance = getHistoricProcessInstance(job.getProcessInstanceId());
212         assertNotNull(historicProcessInstance);
213         assertEquals(HistoricProcessInstance.STATE_COMPLETED, historicProcessInstance.getState());
214
215         final Optional<AsInst> asInstOptional = databaseServiceProvider.getAsInst(asInst.getAsInstId());
216         final AsInst actualAsInst = asInstOptional.get();
217         assertEquals(State.INSTANTIATED, actualAsInst.getStatus());
218
219         final Optional<AsLcmOpOcc> asLcmOpOccOptional = databaseServiceProvider.getAsLcmOpOcc(asLcmOpOccId);
220         assertTrue(asLcmOpOccOptional.isPresent());
221         assertEquals(OperationStateEnum.COMPLETED, asLcmOpOccOptional.get().getOperationState());
222
223         final List<AsDeploymentItem> actualAsDeploymentItems =
224                 databaseServiceProvider.getAsDeploymentItemByAsInstId(actualAsInst.getAsInstId());
225         assertEquals(2, actualAsDeploymentItems.size());
226
227         actualAsDeploymentItems.forEach(asDeploymentItem -> {
228             assertEquals(State.INSTANTIATED, asDeploymentItem.getStatus());
229         });
230
231         final Map<String, Integer> counter = mockedHelmClient.getCounter();
232         assertEquals(2, counter.size());
233         assertEquals(Integer.valueOf(3), counter.get(asInst.getAsdeploymentItems().get(0).getReleaseName()));
234         assertEquals(Integer.valueOf(3), counter.get(asInst.getAsdeploymentItems().get(1).getReleaseName()));
235
236
237     }
238
239     @Test
240     public void testInstantiateAsWorkflow_JobResourceFailedToStartUp() throws InterruptedException, IOException {
241
242         final String asInstId = UUID.randomUUID().toString();
243         final String asDeploymentItem1InstId = UUID.randomUUID().toString();
244         final String asDeploymentItem2InstId = UUID.randomUUID().toString();
245         final String release_name_3 = "testThree";
246         final String release_name_4 = "testFour";
247
248         final String jobResourceResponse = gson.toJson(new Watch.Response<V1Job>(RESPONSE_TYPE_ADDED,
249                 new V1Job().apiVersion(BATCH_V1).metadata(getV1ObjectMeta())
250                         .status(new V1JobStatus().addConditionsItem(new V1JobCondition().type("Failed")
251                                 .status(Boolean.TRUE.toString()).reason("Image not found")))));
252
253         final AsInst asInst = createAsInst(asInstId, asDeploymentItem1InstId, asDeploymentItem2InstId, release_name_3,
254                 release_name_4, asInstId);
255         databaseServiceProvider.saveAsInst(asInst);
256
257         wireMockServer.stubFor(get(urlMatching("/apis/batch/v1/jobs\\?labelSelector.*(" + release_name_3 + "|"
258                 + release_name_4 + ")&timeoutSeconds=1&watch=true")).willReturn(
259                         aResponse().withBody(jobResourceResponse).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
260
261         mockAAIEndpoints(asInstId, asDeploymentItem1InstId, asDeploymentItem2InstId);
262         mockSdcPackageDownloadEndpoint(asInstId);
263
264         createKubeConfigFile(asInst);
265
266         try {
267             objUnderTest.runInstantiateAsJob(asInst.getAsInstId(), getInstantiateAsRequest());
268         } catch (final Exception exception) {
269             assertEquals(AsRequestProcessingException.class, exception.getClass());
270         }
271
272         final Optional<Job> optional = getJobByResourceId(asInst.getAsInstId());
273         assertTrue(optional.isPresent());
274         final Job job = optional.get();
275
276
277         assertTrue(waitForProcessInstanceToFinish(job.getProcessInstanceId()));
278
279         final HistoricProcessInstance historicProcessInstance = getHistoricProcessInstance(job.getProcessInstanceId());
280         assertNotNull(historicProcessInstance);
281         assertEquals(HistoricProcessInstance.STATE_COMPLETED, historicProcessInstance.getState());
282
283         final Optional<AsInst> asInstOptional = databaseServiceProvider.getAsInst(asInst.getAsInstId());
284         final AsInst actualAsInst = asInstOptional.get();
285         assertEquals(State.FAILED, actualAsInst.getStatus());
286
287
288     }
289
290     @Test(expected = AsRequestProcessingException.class)
291     public void testInstantiateAsWorkflow_LifecycleParametersMissing_Fail() throws InterruptedException, IOException {
292
293         mockSdcPackageDownloadEndpoint();
294
295         final AsLifecycleParam lcp3 = new AsLifecycleParam().asLifecycleParam(".Values.extra.missing");
296         final AsInst asInst1 = createAsInst(AS_INST_ID2, AS_DEPLOYMENT_ITEM_1_INST_ID2, AS_DEPLOYMENT_ITEM_2_INST_ID2);
297         asInst1.getAsdeploymentItems().get(0).asLifecycleParams(lcp3);
298
299         databaseServiceProvider.saveAsInst(asInst1);
300
301         createKubeConfigFile(asInst1);
302
303         objUnderTest.runInstantiateAsJob(asInst1.getAsInstId(), getInstantiateAsRequest());
304
305     }
306
307     @Test
308     public void testInstantiateAsWorkflow_UpdateAsInstState_ExceptionCase() {
309
310         final AsInst asInst = new AsInst().asInstId(UUID.randomUUID().toString()).name(AS_INST_NAME).asdId(ASD_ID)
311                 .asdInvariantId(AS_INST_ID).status(State.NOT_INSTANTIATED).statusUpdatedTime(LocalDateTime.now())
312                 .asApplicationName("asApplicationName").asApplicationVersion("asApplicationVersion")
313                 .asProvider("asProvider").serviceInstanceId(SERVICE_INSTANCE_ID)
314                 .serviceInstanceName("serviceInstanceName").cloudOwner("cloudOwner").cloudRegion("cloudRegion")
315                 .tenantId("tenantId");
316
317         databaseServiceProvider.saveAsInst(asInst);
318
319         assertThrows(AsRequestProcessingException.class,
320                 () -> objUnderTest.runInstantiateAsJob(asInst.getAsInstId(), getInstantiateAsRequest()));
321
322         final Optional<Job> optional = getJobByResourceId(asInst.getAsInstId());
323         final Job job = optional.get();
324
325         final Optional<AsInst> asInstOptional = databaseServiceProvider.getAsInst(asInst.getAsInstId());
326
327         assertEquals(JobStatusEnum.ERROR, job.getStatus());
328         assertEquals(State.FAILED, asInstOptional.get().getStatus());
329     }
330
331     private void mockSdcPackageDownloadEndpoint() throws IOException {
332         mockSdcPackageDownloadEndpoint(ASD_ID);
333     }
334
335     private void mockSdcPackageDownloadEndpoint(final String asdId) throws IOException {
336         wireMockServer.stubFor(get("/sdc/v1/catalog/resources/" + asdId + "/toscaModel")
337                 .willReturn(aResponse().withBody(getFileContent(getAbsolutePath(RESOURCE_ASD_PACKAGE_CSAR_PATH)))
338                         .withHeader(ACCEPT, APPLICATION_OCTET_STREAM_VALUE)));
339     }
340
341     private void mockKubernetesClientEndpoint() {
342         wireMockServer.stubFor(get(urlMatching("/apis/batch/v1/jobs\\?labelSelector.*(" + DEPLOYMENT_ITEM_1_RELEASE_NAME
343                 + "|" + DEPLOYMENT_ITEM_2_RELEASE_NAME + ")&timeoutSeconds=1&watch=true"))
344                         .willReturn(aResponse().withBody(getJobResponse()).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
345         wireMockServer.stubFor(get(urlMatching("/apis/batch/v1/jobs\\?labelSelector.*&watch=false"))
346                 .willReturn(aResponse().withBody(getJobList()).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
347
348         wireMockServer.stubFor(get(urlMatching("/api/v1/pods\\?labelSelector.*(" + DEPLOYMENT_ITEM_1_RELEASE_NAME + "|"
349                 + DEPLOYMENT_ITEM_2_RELEASE_NAME + ")&timeoutSeconds=1&watch=true"))
350                         .willReturn(aResponse().withBody(getPodResponse()).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
351         wireMockServer.stubFor(get(urlMatching("/api/v1/pods\\?labelSelector.*&watch=false"))
352                 .willReturn(aResponse().withBody(getPodList()).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
353
354         wireMockServer.stubFor(get(urlMatching("/api/v1/services\\?labelSelector.*(" + DEPLOYMENT_ITEM_1_RELEASE_NAME
355                 + "|" + DEPLOYMENT_ITEM_2_RELEASE_NAME + ")&timeoutSeconds=1&watch=true")).willReturn(
356                         aResponse().withBody(getServiceResponse()).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
357         wireMockServer.stubFor(get(urlMatching("/api/v1/services\\?labelSelector.*&watch=false"))
358                 .willReturn(aResponse().withBody(getServiceList()).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
359
360         wireMockServer
361                 .stubFor(get(urlMatching("/apis/apps/v1/deployments\\?labelSelector.*(" + DEPLOYMENT_ITEM_1_RELEASE_NAME
362                         + "|" + DEPLOYMENT_ITEM_2_RELEASE_NAME + ")&timeoutSeconds=1&watch=true"))
363                                 .willReturn(aResponse().withBody(getDeploymentResponse()).withHeader(ACCEPT,
364                                         APPLICATION_JSON_VALUE)));
365         wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/deployments\\?labelSelector.*&watch=false"))
366                 .willReturn(aResponse().withBody(getDeploymentList()).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
367
368         wireMockServer
369                 .stubFor(get(urlMatching("/apis/apps/v1/replicasets\\?labelSelector.*(" + DEPLOYMENT_ITEM_1_RELEASE_NAME
370                         + "|" + DEPLOYMENT_ITEM_2_RELEASE_NAME + ")&timeoutSeconds=1&watch=true"))
371                                 .willReturn(aResponse().withBody(getReplicaSetResponse()).withHeader(ACCEPT,
372                                         APPLICATION_JSON_VALUE)));
373         wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/replicasets\\?labelSelector.*&watch=false"))
374                 .willReturn(aResponse().withBody(getReplicaSetList()).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
375
376         wireMockServer
377                 .stubFor(get(urlMatching("/apis/apps/v1/daemonsets\\?labelSelector.*(" + DEPLOYMENT_ITEM_1_RELEASE_NAME
378                         + "|" + DEPLOYMENT_ITEM_2_RELEASE_NAME + ")&timeoutSeconds=1&watch=true"))
379                                 .willReturn(aResponse().withBody(getDaemonSetResponse()).withHeader(ACCEPT,
380                                         APPLICATION_JSON_VALUE)));
381         wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/daemonsets\\?labelSelector.*&watch=false"))
382                 .willReturn(aResponse().withBody(getDaemonSetList()).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
383
384         wireMockServer.stubFor(
385                 get(urlMatching("/apis/apps/v1/statefulsets\\?labelSelector.*(" + DEPLOYMENT_ITEM_1_RELEASE_NAME + "|"
386                         + DEPLOYMENT_ITEM_2_RELEASE_NAME + ")&timeoutSeconds=1&watch=true"))
387                                 .willReturn(aResponse().withBody(getStatefulSetResponse()).withHeader(ACCEPT,
388                                         APPLICATION_JSON_VALUE)));
389         wireMockServer.stubFor(get(urlMatching("/apis/apps/v1/statefulsets\\?labelSelector.*&watch=false"))
390                 .willReturn(aResponse().withBody(getStatefulSetList()).withHeader(ACCEPT, APPLICATION_JSON_VALUE)));
391     }
392
393     private String getStatefulSetResponse() {
394         return gson.toJson(new Watch.Response<V1StatefulSet>(RESPONSE_TYPE_ADDED, getStatefulSet()));
395     }
396
397     private String getStatefulSetList() {
398         final V1StatefulSetList v1StatefulSetList = new V1StatefulSetList();
399         v1StatefulSetList.addItemsItem(getStatefulSet());
400         return gson.toJson(v1StatefulSetList);
401     }
402
403     private V1StatefulSet getStatefulSet() {
404         return new V1StatefulSet()
405                 .apiVersion(
406                         APPS_V1)
407                 .metadata(getV1ObjectMeta())
408                 .spec(new V1StatefulSetSpec()
409                         .updateStrategy(new V1StatefulSetUpdateStrategy().type("RollingUpdate")
410                                 .rollingUpdate(new V1RollingUpdateStatefulSetStrategy().partition(Integer.valueOf(0))))
411                         .replicas(Integer.valueOf(2)))
412                 .status(new V1StatefulSetStatus().updatedReplicas(Integer.valueOf(2))
413                         .readyReplicas(Integer.valueOf(2)));
414     }
415
416     private String getDaemonSetResponse() {
417         return gson.toJson(new Watch.Response<V1DaemonSet>(RESPONSE_TYPE_ADDED, getDaemonSet()));
418     }
419
420     private String getDaemonSetList() {
421         final V1DaemonSetList v1DaemonSetList = new V1DaemonSetList();
422         v1DaemonSetList.addItemsItem(getDaemonSet());
423         return gson.toJson(v1DaemonSetList);
424     }
425
426     private V1DaemonSet getDaemonSet() {
427         return new V1DaemonSet().apiVersion(APPS_V1).metadata(getV1ObjectMeta())
428                 .spec(new V1DaemonSetSpec().updateStrategy(new V1DaemonSetUpdateStrategy().type("RollingUpdate")
429                         .rollingUpdate(new V1RollingUpdateDaemonSet().maxUnavailable(new IntOrString("50%")))))
430                 .status(new V1DaemonSetStatus().desiredNumberScheduled(Integer.valueOf(2))
431                         .numberReady(Integer.valueOf(2)).updatedNumberScheduled(Integer.valueOf(2)));
432     }
433
434     private String getReplicaSetResponse() {
435         return gson.toJson(new Watch.Response<V1ReplicaSet>(RESPONSE_TYPE_ADDED, getReplicaSet()));
436     }
437
438     private String getReplicaSetList() {
439         final V1ReplicaSetList v1ReplicaSetList = new V1ReplicaSetList();
440         v1ReplicaSetList.addItemsItem(getReplicaSet());
441         return gson.toJson(v1ReplicaSetList);
442     }
443
444     private V1ReplicaSet getReplicaSet() {
445         return new V1ReplicaSet().apiVersion(APPS_V1).metadata(getV1ObjectMeta())
446                 .status(new V1ReplicaSetStatus().readyReplicas(Integer.valueOf(1)))
447                 .spec(new V1ReplicaSetSpec().replicas(Integer.valueOf(1)));
448     }
449
450     private V1ObjectMeta getV1ObjectMeta() {
451         return new V1ObjectMeta().name("job-name").namespace("job-namespace").uid(RANDOM_UUID)
452                 .resourceVersion(RANDOM_UUID).labels(Map.of("label-key", "label-value"));
453     }
454
455     private String getDeploymentResponse() {
456         return gson.toJson(new Watch.Response<V1Deployment>(RESPONSE_TYPE_ADDED, getDeployment()));
457     }
458
459     private String getDeploymentList() {
460         final V1DeploymentList v1DeploymentList = new V1DeploymentList();
461         v1DeploymentList.addItemsItem(getDeployment());
462         return gson.toJson(v1DeploymentList);
463     }
464
465     private V1Deployment getDeployment() {
466         return new V1Deployment().apiVersion(APPS_V1).metadata(getV1ObjectMeta())
467                 .status(new V1DeploymentStatus().replicas(Integer.valueOf(1)).availableReplicas(Integer.valueOf(1)))
468                 .spec(new V1DeploymentSpec().replicas(Integer.valueOf(1)));
469     }
470
471     private String getServiceResponse() {
472         return gson.toJson(new Watch.Response<V1Service>(RESPONSE_TYPE_ADDED, getService()));
473
474     }
475
476     private String getServiceList() {
477         final V1ServiceList v1ServiceList = new V1ServiceList();
478         v1ServiceList.addItemsItem(getService());
479         return gson.toJson(v1ServiceList);
480     }
481
482     private V1Service getService() {
483         return new V1Service().apiVersion(V1).metadata(getV1ObjectMeta());
484     }
485
486     private String getPodList() {
487         final V1PodList v1Podlist = new V1PodList();
488         v1Podlist.addItemsItem(getPod());
489         return gson.toJson(v1Podlist);
490     }
491
492     private String getPodResponse() {
493         return gson.toJson(new Watch.Response<V1Pod>(RESPONSE_TYPE_ADDED, getPod()));
494     }
495
496     private V1Pod getPod() {
497         return new V1Pod().apiVersion(V1).metadata(getV1ObjectMeta()).status(new V1PodStatus()
498                 .addConditionsItem(new V1PodCondition().type("Ready").status(Boolean.TRUE.toString())));
499     }
500
501     private String getJobResponse() {
502         return gson.toJson(new Watch.Response<V1Job>(RESPONSE_TYPE_ADDED, getJob()));
503     }
504
505     private String getJobList() {
506         final V1JobList v1JobList = new V1JobList();
507         v1JobList.addItemsItem(getJob());
508         return gson.toJson(v1JobList);
509     }
510
511     private V1Job getJob() {
512         return new V1Job().apiVersion(BATCH_V1).metadata(getV1ObjectMeta()).status(new V1JobStatus()
513                 .addConditionsItem(new V1JobCondition().type("Complete").status(Boolean.TRUE.toString())));
514     }
515
516     private void mockAAIEndpoints() throws JsonProcessingException {
517         mockAAIEndpoints(AS_INST_ID, AS_DEPLOYMENT_ITEM_1_INST_ID, AS_DEPLOYMENT_ITEM_2_INST_ID);
518     }
519
520     private void mockAAIEndpoints(final String as_inst_id, final String as_deployment_item_1_id,
521             final String as_deployment_item_2_id) throws JsonProcessingException {
522         final String vfModule1EndPoint = "/aai/" + V19 + "/network/generic-vnfs/generic-vnf/" + as_inst_id
523                 + "/vf-modules/vf-module/" + as_deployment_item_1_id;
524
525         wireMockServer.stubFor(get(urlMatching(vfModule1EndPoint + "\\?resultIndex=0&resultSize=1&format=count"))
526                 .willReturn(notFound()));
527
528         final String vfModule2EndPoint = "/aai/" + V19 + "/network/generic-vnfs/generic-vnf/" + as_inst_id
529                 + "/vf-modules/vf-module/" + as_deployment_item_2_id;
530
531         wireMockServer.stubFor(get(urlMatching(vfModule2EndPoint + "\\?resultIndex=0&resultSize=1&format=count"))
532                 .willReturn(notFound()));
533
534         wireMockServer.stubFor(put(urlMatching(vfModule1EndPoint)).willReturn(ok()));
535         wireMockServer.stubFor(put(urlMatching(vfModule2EndPoint)).willReturn(ok()));
536
537         final String k8sResourcesEndpoint = "/aai/" + V19
538                 + "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/cloudRegion/tenants/tenant/tenantId/"
539                 + "k8s-resources/.*";
540         wireMockServer.stubFor(get(urlMatching(k8sResourcesEndpoint)).willReturn(notFound()));
541         wireMockServer.stubFor(put(urlMatching(k8sResourcesEndpoint)).willReturn(ok()));
542         wireMockServer
543                 .stubFor(put(urlMatching(k8sResourcesEndpoint + "/relationship-list/relationship")).willReturn(ok()));
544
545
546     }
547
548     private AsInst createAsInst(final String as_inst_id, final String as_deployment_item_1_id,
549             final String as_deployment_item_2_id) {
550         return createAsInst(as_inst_id, as_deployment_item_1_id, as_deployment_item_2_id,
551                 DEPLOYMENT_ITEM_1_RELEASE_NAME, DEPLOYMENT_ITEM_2_RELEASE_NAME, ASD_ID);
552     }
553
554     private AsInst createAsInst(final String as_inst_id, final String as_deployment_item_1_id,
555             final String as_deployment_item_2_id, final String as_deployment_item_1_release_name,
556             final String as_deployment_item_2_release_name, final String asdId) {
557         final AsInst asInst = new AsInst().asInstId(as_inst_id).name(AS_INST_NAME).asdId(asdId)
558                 .asdInvariantId(as_inst_id).status(State.NOT_INSTANTIATED).statusUpdatedTime(LocalDateTime.now())
559                 .asApplicationName("asApplicationName").asApplicationVersion("asApplicationVersion")
560                 .asProvider("asProvider").serviceInstanceId(as_inst_id).serviceInstanceName("serviceInstanceName")
561                 .cloudOwner("cloudOwner").cloudRegion("cloudRegion").tenantId("tenantId");
562
563         final String helmFile1 = "Artifacts/Deployment/HELM/sampleapp-db-operator-helm.tgz";
564         final AsLifecycleParam lcp1 = new AsLifecycleParam().asLifecycleParam(DEPLOYMENT_ITEM_1_LIFECYCLE_PARAM_1);
565         final AsLifecycleParam lcp2 = new AsLifecycleParam().asLifecycleParam(DEPLOYMENT_ITEM_1_LIFECYCLE_PARAM_2);
566
567         final AsDeploymentItem item1 = new AsDeploymentItem().asDeploymentItemInstId(as_deployment_item_1_id)
568                 .asInst(asInst).status(State.NOT_INSTANTIATED).name("sampleapp-db").itemId("1").deploymentOrder(1)
569                 .artifactFilePath(helmFile1).createTime(LocalDateTime.now()).lastUpdateTime(LocalDateTime.now())
570                 .releaseName(as_deployment_item_1_release_name).asLifecycleParams(lcp1).asLifecycleParams(lcp2);
571
572         final String helmFile2 = "Artifacts/Deployment/HELM/sampleapp-services-helm.tgz";
573         final AsLifecycleParam lcpitem2_1 =
574                 new AsLifecycleParam().asLifecycleParam(DEPLOYMENT_ITEM_2_LIFECYCLE_PARAM_1);
575         final AsLifecycleParam lcpitem2_2 =
576                 new AsLifecycleParam().asLifecycleParam(DEPLOYMENT_ITEM_2_LIFECYCLE_PARAM_2);
577         final AsLifecycleParam lcpitem2_3 =
578                 new AsLifecycleParam().asLifecycleParam(DEPLOYMENT_ITEM_2_LIFECYCLE_PARAM_3);
579
580         final AsDeploymentItem item2 = new AsDeploymentItem().asDeploymentItemInstId(as_deployment_item_2_id)
581                 .asInst(asInst).status(State.NOT_INSTANTIATED).name("sampleapp-services").itemId("2").deploymentOrder(2)
582                 .artifactFilePath(helmFile2).createTime(LocalDateTime.now()).lastUpdateTime(LocalDateTime.now())
583                 .releaseName(as_deployment_item_2_release_name).asLifecycleParams(lcpitem2_1)
584                 .asLifecycleParams(lcpitem2_2).asLifecycleParams(lcpitem2_3);
585
586         asInst.asdeploymentItems(item1);
587         asInst.asdeploymentItems(item2);
588         return asInst;
589     }
590
591     private InstantiateAsRequest getInstantiateAsRequest() {
592         final AsInfoModificationRequestDeploymentItems lifecycleParams_1 =
593                 new AsInfoModificationRequestDeploymentItems().deploymentItemsId("1").lifecycleParameterKeyValues(
594                         Map.of(DEPLOYMENT_ITEM_1_LIFECYCLE_PARAM_1, DEPLOYMENT_ITEM_LIFECYCLE_PARAM_VALUE,
595                                 DEPLOYMENT_ITEM_1_LIFECYCLE_PARAM_2, DEPLOYMENT_ITEM_LIFECYCLE_PARAM_VALUE));
596
597         final AsInfoModificationRequestDeploymentItems lifecycleParams_2 =
598                 new AsInfoModificationRequestDeploymentItems().deploymentItemsId("2").lifecycleParameterKeyValues(
599                         Map.of(DEPLOYMENT_ITEM_2_LIFECYCLE_PARAM_1, DEPLOYMENT_ITEM_LIFECYCLE_PARAM_VALUE,
600                                 DEPLOYMENT_ITEM_2_LIFECYCLE_PARAM_2, DEPLOYMENT_ITEM_LIFECYCLE_PARAM_VALUE,
601                                 DEPLOYMENT_ITEM_2_LIFECYCLE_PARAM_3, DEPLOYMENT_ITEM_LIFECYCLE_PARAM_VALUE));
602
603         return new InstantiateAsRequest().addDeploymentItemsItem(lifecycleParams_1)
604                 .addDeploymentItemsItem(lifecycleParams_2);
605     }
606
607     private Path getAbsolutePath(final String path) {
608         final File file = new File(path);
609         return file.toPath();
610     }
611
612     private byte[] getFileContent(final Path path) throws IOException {
613         return Files.readAllBytes(path);
614     }
615
616 }