2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.vid.services;
23 import static com.google.common.collect.Maps.newHashMap;
24 import static org.hamcrest.MatcherAssert.assertThat;
25 import static org.hamcrest.Matchers.contains;
26 import static org.hamcrest.Matchers.hasItem;
27 import static org.hamcrest.Matchers.hasItems;
28 import static org.hamcrest.Matchers.hasProperty;
29 import static org.hamcrest.Matchers.is;
30 import static org.hamcrest.Matchers.matchesPattern;
31 import static org.hamcrest.Matchers.not;
32 import static org.hamcrest.core.Every.everyItem;
33 import static org.hamcrest.core.IsEqual.equalTo;
34 import static org.mockito.Matchers.any;
35 import static org.mockito.Mockito.anyInt;
36 import static org.mockito.Mockito.anyString;
37 import static org.mockito.Mockito.doNothing;
38 import static org.mockito.Mockito.doThrow;
39 import static org.mockito.Mockito.eq;
40 import static org.mockito.Mockito.mock;
41 import static org.mockito.Mockito.times;
42 import static org.mockito.Mockito.verify;
43 import static org.mockito.Mockito.when;
44 import static org.onap.vid.job.Job.JobStatus.COMPLETED;
45 import static org.onap.vid.job.Job.JobStatus.FAILED;
46 import static org.onap.vid.job.Job.JobStatus.IN_PROGRESS;
47 import static org.onap.vid.job.Job.JobStatus.PAUSE;
48 import static org.onap.vid.job.Job.JobStatus.PENDING;
49 import static org.onap.vid.job.Job.JobStatus.STOPPED;
50 import static org.testng.Assert.assertEquals;
51 import static org.testng.Assert.assertFalse;
52 import static org.testng.Assert.assertNotNull;
53 import static org.testng.Assert.assertNull;
54 import static org.testng.Assert.assertTrue;
56 import com.fasterxml.jackson.databind.JsonNode;
57 import com.fasterxml.jackson.databind.ObjectMapper;
58 import com.google.common.collect.ImmutableList;
59 import com.google.common.collect.ImmutableMap;
60 import java.io.IOException;
61 import java.lang.reflect.Method;
63 import java.time.Instant;
64 import java.time.LocalDateTime;
65 import java.time.ZoneId;
66 import java.util.ArrayList;
67 import java.util.Arrays;
68 import java.util.Collections;
69 import java.util.Comparator;
70 import java.util.Date;
71 import java.util.HashMap;
72 import java.util.List;
74 import java.util.Optional;
76 import java.util.UUID;
77 import java.util.concurrent.Callable;
78 import java.util.concurrent.ExecutorService;
79 import java.util.concurrent.Executors;
80 import java.util.stream.Collectors;
81 import java.util.stream.IntStream;
82 import javax.inject.Inject;
83 import net.javacrumbs.jsonunit.JsonAssert;
84 import org.apache.commons.io.IOUtils;
85 import org.hibernate.SessionFactory;
86 import org.json.JSONException;
87 import org.mockito.ArgumentCaptor;
88 import org.mockito.Mock;
89 import org.mockito.Mockito;
90 import org.mockito.MockitoAnnotations;
91 import org.mockito.stubbing.Answer;
92 import org.onap.portalsdk.core.domain.FusionObject;
93 import org.onap.portalsdk.core.service.DataAccessService;
94 import org.onap.portalsdk.core.util.SystemProperties;
95 import org.onap.vid.aai.ExceptionWithRequestInfo;
96 import org.onap.vid.aai.model.ResourceType;
97 import org.onap.vid.changeManagement.RequestDetailsWrapper;
98 import org.onap.vid.config.DataSourceConfig;
99 import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig;
100 import org.onap.vid.exceptions.GenericUncheckedException;
101 import org.onap.vid.exceptions.MaxRetriesException;
102 import org.onap.vid.exceptions.OperationNotAllowedException;
103 import org.onap.vid.job.Job;
104 import org.onap.vid.job.Job.JobStatus;
105 import org.onap.vid.job.JobAdapter;
106 import org.onap.vid.job.JobType;
107 import org.onap.vid.job.JobsBrokerService;
108 import org.onap.vid.job.impl.JobDaoImpl;
109 import org.onap.vid.job.impl.JobSharedData;
110 import org.onap.vid.model.Action;
111 import org.onap.vid.model.JobAuditStatus;
112 import org.onap.vid.model.JobAuditStatus.SourceStatus;
113 import org.onap.vid.model.NameCounter;
114 import org.onap.vid.model.ServiceInfo;
115 import org.onap.vid.model.serviceInstantiation.InstanceGroup;
116 import org.onap.vid.model.serviceInstantiation.Network;
117 import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
118 import org.onap.vid.model.serviceInstantiation.VfModule;
119 import org.onap.vid.model.serviceInstantiation.Vnf;
120 import org.onap.vid.mso.MsoOperationalEnvironmentTest;
121 import org.onap.vid.mso.model.InstanceGroupInstantiationRequestDetails;
122 import org.onap.vid.mso.model.ModelInfo;
123 import org.onap.vid.mso.model.NetworkInstantiationRequestDetails;
124 import org.onap.vid.mso.model.ServiceDeletionRequestDetails;
125 import org.onap.vid.mso.model.ServiceInstantiationRequestDetails;
126 import org.onap.vid.mso.model.VfModuleInstantiationRequestDetails;
127 import org.onap.vid.mso.model.VfModuleMacro;
128 import org.onap.vid.mso.model.VnfInstantiationRequestDetails;
129 import org.onap.vid.mso.model.VolumeGroupRequestDetails;
130 import org.onap.vid.mso.rest.AsyncRequestStatus;
131 import org.onap.vid.properties.Features;
132 import org.onap.vid.testUtils.TestUtils;
133 import org.onap.vid.utils.DaoUtils;
134 import org.springframework.beans.factory.annotation.Autowired;
135 import org.springframework.test.context.ContextConfiguration;
136 import org.testng.Assert;
137 import org.testng.annotations.AfterMethod;
138 import org.testng.annotations.BeforeClass;
139 import org.testng.annotations.BeforeMethod;
140 import org.testng.annotations.DataProvider;
141 import org.testng.annotations.Test;
143 @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class})
144 public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest {
147 private DataAccessService dataAccessService;
150 private JobAdapter jobAdapterMock;
153 private JobsBrokerService jobsBrokerServiceMock;
157 private SessionFactory sessionFactory;
159 private AsyncInstantiationBusinessLogicImpl asyncInstantiationBL;
161 private int serviceCount = 0;
163 private static final String UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE =
164 "Failed to retrieve job with uuid .* from ServiceInfo table. Instances found: .*";
166 private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE =
167 "Service status does not allow deletion from the queue";
170 void initServicesInfoService() {
171 MockitoAnnotations.initMocks(this);
172 asyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapterMock, jobsBrokerServiceMock, sessionFactory, aaiClient, featureManager, cloudOwnerService);
173 createInstanceParamsMaps();
178 Mockito.reset(aaiClient);
179 Mockito.reset(jobAdapterMock);
180 Mockito.reset(jobsBrokerServiceMock);
181 mockAaiClientAnyNameFree();
182 enableAddCloudOwnerOnMsoRequest();
185 private void enableAddCloudOwnerOnMsoRequest() {
186 enableAddCloudOwnerOnMsoRequest(true);
189 private void enableAddCloudOwnerOnMsoRequest(boolean isActive) {
190 // always turn on the feature flag
191 when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(isActive);
192 when(aaiClient.getCloudOwnerByCloudRegionId(anyString())).thenReturn("att-aic");
196 void resetServiceCount() {
202 dataAccessService.deleteDomainObjects(JobDaoImpl.class, "1=1", getPropsMap());
203 dataAccessService.deleteDomainObjects(ServiceInfo.class, "1=1", getPropsMap());
204 dataAccessService.deleteDomainObjects(JobAuditStatus.class, "1=1", getPropsMap());
205 dataAccessService.deleteDomainObjects(NameCounter.class, "1=1", getPropsMap());
209 private void createNewTestServicesInfoForFilter(String userId) {
210 LocalDateTime createdDate, modifiedDate;
211 LocalDateTime NOW = LocalDateTime.now();
215 uuid = UUID.randomUUID();
217 createdDate = NOW.minusYears(1);
218 addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false);
220 uuid = UUID.randomUUID();
222 createdDate = NOW.minusDays(20);
223 modifiedDate = NOW.minusDays(19);
224 addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true);
226 createNewTestServicesInfo(String.valueOf(userId));
229 private void createNewTestServicesInfo(String userId) {
231 LocalDateTime createdDate, modifiedDate;
232 LocalDateTime NOW = LocalDateTime.now();
235 uuid = UUID.randomUUID();
238 createdDate = NOW.minusDays(40);
239 addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false);
240 addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false);
242 uuid = UUID.randomUUID();
245 createdDate = NOW.minusDays(20);
246 modifiedDate = NOW.minusDays(10);
247 addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false);
248 addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false);
249 addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false);
251 modifiedDate = NOW.minusDays(19);
252 addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false);
255 // Job to a different user
256 uuid = UUID.randomUUID();
259 createdDate = NOW.minusMonths(2);
260 addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false);
264 private UUID createServicesInfoWithDefaultValues(Job.JobStatus status) {
266 LocalDateTime NOW = LocalDateTime.now();
269 uuid = UUID.randomUUID();
270 addNewJob(uuid, status);
272 addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false);
278 private List<ServiceInfo> getFullList() {
279 List<ServiceInfo> expectedOrderServiceInfo = dataAccessService.getList(ServiceInfo.class, getPropsMap());
280 assertThat("Failed to retrieve all predefined services", expectedOrderServiceInfo.size(), equalTo(serviceCount));
281 expectedOrderServiceInfo.sort(new ServiceInfoComparator());
282 return expectedOrderServiceInfo;
285 private static Date toDate(LocalDateTime localDateTime) {
286 return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
289 private LocalDateTime fromDate(Date date) {
290 return Instant.ofEpochMilli(date.getTime())
291 .atZone(ZoneId.systemDefault())
295 private void addNewServiceInfo(UUID uuid, String userId, String serviceName, LocalDateTime createDate, LocalDateTime statusModifiedDate, Job.JobStatus status, boolean isHidden) {
296 ServiceInfo serviceInfo = new ServiceInfo();
297 serviceInfo.setJobId(uuid);
298 serviceInfo.setUserId(userId);
299 serviceInfo.setServiceInstanceName(serviceName);
300 serviceInfo.setStatusModifiedDate(toDate(statusModifiedDate));
301 serviceInfo.setJobStatus(status);
302 serviceInfo.setPause(false);
303 serviceInfo.setOwningEntityId("1234");
304 serviceInfo.setCreatedBulkDate(toDate(createDate));
306 serviceInfo.setHidden(isHidden);
307 dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
308 setCreateDateToServiceInfo(uuid, createDate);
313 private void setCreateDateToServiceInfo(UUID jobUuid, LocalDateTime createDate) {
314 List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
315 DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
316 serviceInfoList.stream()
317 .filter(serviceInfo -> jobUuid.equals(serviceInfo.getJobId()))
318 .forEach(serviceInfo -> {
319 serviceInfo.setCreated(toDate(createDate));
320 session.saveOrUpdate(serviceInfo);
326 private void addNewJob(UUID uuid) {
327 addNewJob(uuid, null);
330 private void addNewJob(UUID uuid, Job.JobStatus status) {
331 JobDaoImpl jobDao = new JobDaoImpl();
332 jobDao.setUuid(uuid);
333 jobDao.setStatus(status);
334 dataAccessService.saveDomainObject(jobDao, getPropsMap());
338 public void testServiceInfoAreOrderedAsExpected() {
340 createNewTestServicesInfo(String.valueOf(userId));
341 List<ServiceInfo> expectedOrderServiceInfo = getFullList();
342 List<ServiceInfo> serviceInfoListResult = asyncInstantiationBL.getAllServicesInfo();
343 assertThat("Services aren't ordered as expected", serviceInfoListResult, equalTo(expectedOrderServiceInfo));
347 public void testServiceInfoAreFilteredAsExpected() {
349 createNewTestServicesInfoForFilter(String.valueOf(userId));
350 List<ServiceInfo> expectedOrderServiceInfo = getFullList();
352 List<ServiceInfo> expectedFilterByUser = expectedOrderServiceInfo.stream().filter(x ->
353 !x.getServiceInstanceName().equals("Old") && !x.getServiceInstanceName().equals("Hidden")
355 ).collect(Collectors.toList());
358 List<ServiceInfo> serviceInfoFilteredByUser = asyncInstantiationBL.getAllServicesInfo();
359 assertThat("Services aren't ordered filtered as expected", serviceInfoFilteredByUser, equalTo(expectedFilterByUser));
362 @Test(dataProvider = "pauseAndInstanceParams")
363 public void createMacroServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
365 ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true), 2, true, PROJECT_NAME, false);
366 final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request_unique_names.json");
367 when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), anyString(), any())).thenAnswer(invocation -> {
368 Object[] args = invocation.getArguments();
369 return new MockedJob((String)args[4]);
372 when(jobsBrokerServiceMock.add(any(MockedJob.class))).thenAnswer((Answer<UUID>) invocation -> {
373 Object[] args = invocation.getArguments();
374 MockedJob job = (MockedJob) args[0];
375 MockedJob.putJob(job.uuid, job);
376 return job.getUuid();
379 when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true);
381 List<UUID> uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiationPayload, "az2016");
382 for (int i = 0; i < 2; i++) {
383 UUID currentUuid = uuids.get(i);
384 RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
385 asyncInstantiationBL.generateMacroServiceInstantiationRequest(currentUuid, serviceInstantiationPayload,
386 MockedJob.getJob(currentUuid).getOptimisticUniqueServiceInstanceName(), "az2016");
387 String unique = i==0 ? "" : String.format("_00%s", i);
388 String expected = IOUtils.toString(resource, "UTF-8")
389 .replace("{SERVICE_UNIQENESS}", unique)
390 .replace("{VNF_UNIQENESS}", unique)
391 .replace("{VF_MODULE_UNIQENESS}", unique)
392 .replace("{VF_MODULE_2_UNIQENESS}", unique)
393 .replace("{VG_UNIQUENESS}", unique);
394 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
395 Optional<ServiceInfo> optionalServiceInfo = getJobById(currentUuid);
396 assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo("vPE_Service" + unique));
397 verifySearchNodeTypeByName(unique, "vPE_Service", ResourceType.SERVICE_INSTANCE);
398 verifySearchNodeTypeByName(unique, VNF_NAME, ResourceType.GENERIC_VNF);
399 verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vPE_BV_base", ResourceType.VF_MODULE);
400 verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vRE_BV_expansion", ResourceType.VF_MODULE);
401 verifySearchNodeTypeByName(unique, "myVgName", ResourceType.VOLUME_GROUP);
405 protected void verifySearchNodeTypeByName(String unique, String resourceName, ResourceType serviceInstance) {
406 verify(aaiClient, times(1)).isNodeTypeExistsByName(resourceName + unique, serviceInstance);
409 private HashMap<String, Object> getPropsMap() {
410 HashMap<String, Object> props = new HashMap<>();
411 props.put(FusionObject.Parameters.PARAM_USERID, 0);
417 public static Object[][] dataProviderForInstanceNames() {
418 return new Object[][]{
419 {true, ImmutableList.of("vPE_Service", "vPE_Service_001", "vPE_Service_002")},
420 {false, ImmutableList.of("", "", "")},
424 @Test(dataProvider="dataProviderForInstanceNames")
425 public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected(boolean isUserProvidedNaming, List<String> expectedNames) {
428 final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
430 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
431 bulkSize, isUserProvidedNaming, PROJECT_NAME, true
434 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
435 configureMockitoWithMockedJob();
438 asyncInstantiationBL.pushBulkJob(request, "myUserId");
440 List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
441 assertEquals(serviceInfoList.stream().map(ServiceInfo::getServiceInstanceName).collect(Collectors.toList()), expectedNames);
444 @Test(dataProvider = "aLaCarteAndMacroPayload")
445 public void generateMockServiceInstantiationPayload_serializeBackAndForth_sourceShouldBeTheSame(ServiceInstantiation serviceInstantiationPayload) throws IOException {
446 ObjectMapper mapper = new ObjectMapper();
447 final String asString = mapper.writeValueAsString(serviceInstantiationPayload);
449 final ServiceInstantiation asObject = mapper.readValue(asString, ServiceInstantiation.class);
450 final String asString2 = mapper.writeValueAsString(asObject);
452 JsonAssert.assertJsonEquals(asString, asString2);
456 public Object[][] aLaCarteAndMacroPayload() {
457 ServiceInstantiation macroPayload = generateMockMacroServiceInstantiationPayload(
459 createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true),
460 2, false,PROJECT_NAME, false);
461 ServiceInstantiation aLaCartePayload = generateALaCarteServiceInstantiationPayload();
463 return new Object[][]{
469 public static class ServiceInfoComparator implements Comparator<ServiceInfo> {
472 public int compare(ServiceInfo o1, ServiceInfo o2) {
475 compare = o1.getCreatedBulkDate().compareTo(o2.getCreatedBulkDate());
480 // check jobStatus priority
481 int o1Priority = getPriority(o1);
482 int o2Priority = getPriority(o2);
483 compare = o1Priority - o2Priority;
488 // check statusModifiedDate
489 return o1.getStatusModifiedDate().compareTo(o2.getStatusModifiedDate());
492 private int getPriority(ServiceInfo o) throws JSONException {
493 Job.JobStatus status = o.getJobStatus();
512 public Object[][] pauseAndInstanceParams() {
513 return new Object[][]{
514 {Boolean.TRUE, instanceParamsMapWithoutParams, Collections.EMPTY_LIST},
515 {Boolean.FALSE, instanceParamsMapWithoutParams, Collections.EMPTY_LIST},
516 {Boolean.TRUE, vfModuleInstanceParamsMapWithParamsToRemove, Collections.singletonList(vnfInstanceParamsMapWithParamsToRemove)}
520 private ServiceInstantiation generateMacroMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs) {
521 return generateMockMacroServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false);
525 public void testUpdateServiceInfo_WithExistingServiceInfo_ServiceInfoIsUpdated() {
526 UUID uuid = createFakedJobAndServiceInfo();
527 final String STEPH_CURRY = "Steph Curry";
528 asyncInstantiationBL.updateServiceInfo(uuid, x -> {
529 x.setServiceInstanceName(STEPH_CURRY);
530 x.setJobStatus(Job.JobStatus.IN_PROGRESS);
532 Optional<ServiceInfo> optionalServiceInfo = getJobById(uuid);
533 assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo(STEPH_CURRY));
534 assertThat(optionalServiceInfo.get().getJobStatus(), equalTo(Job.JobStatus.IN_PROGRESS));
537 private Optional<ServiceInfo> getJobById(UUID jobId) {
538 List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, null);
539 return serviceInfoList.stream().filter(x -> jobId.equals(x.getJobId())).findFirst();
542 private UUID createFakedJobAndServiceInfo() {
543 UUID uuid = UUID.randomUUID();
545 ServiceInfo serviceInfo = new ServiceInfo();
546 serviceInfo.setServiceInstanceName("Lebron James");
547 serviceInfo.setJobId(uuid);
548 serviceInfo.setJobStatus(Job.JobStatus.PENDING);
549 dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
553 @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
554 public void testUpdateServiceInfo_WithNonExisting_ThrowException() {
555 asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter"));
558 @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
559 public void testUpdateServiceInfo_WithDoubleServiceWithSameJobUuid_ThrowException() {
560 UUID uuid = createFakedJobAndServiceInfo();
561 ServiceInfo serviceInfo = new ServiceInfo();
562 serviceInfo.setJobId(uuid);
563 dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
564 asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter"));
569 public static Object[][] isPauseAndPropertyDataProvider() {
570 return new Object[][]{
571 {true, "mso.restapi.serviceInstanceAssign"},
572 {false, "mso.restapi.serviceInstanceCreate"},
577 @Test(dataProvider = "isPauseAndPropertyDataProvider")
578 public void testServiceInstantiationPath_RequestPathIsAsExpected(boolean isPause, String expectedProperty) {
579 ServiceInstantiation serviceInstantiationPauseFlagTrue = generateMacroMockServiceInstantiationPayload(isPause, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true));
580 String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagTrue);
581 Assert.assertEquals(path, SystemProperties.getProperty(expectedProperty));
585 public void testCreateVnfEndpoint_useProvidedInstanceId() {
586 String path = asyncInstantiationBL.getVnfInstantiationPath("myGreatId");
587 assertThat(path, matchesPattern("/serviceInstances/v./myGreatId/vnfs"));
591 public void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected() throws IOException {
592 createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(true);
596 public void createServiceInfo_WithUserProvidedNamingFalseAndNoVfmodules_ServiceInfoIsAsExpected() throws IOException {
597 createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(false);
600 private void createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules) throws IOException {
601 when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true);
603 ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
604 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
606 false, PROJECT_NAME, true);
609 resource = this.getClass().getResource("/payload_jsons/bulk_service_request_ecomp_naming.json");
611 // remove the vf modules
612 serviceInstantiationPayload.getVnfs().values().forEach(vnf -> vnf.getVfModules().clear());
613 resource = this.getClass().getResource("/payload_jsons/bulk_service_request_no_vfmodule_ecomp_naming.json");
616 RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
617 asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
619 String expected = IOUtils.toString(resource, "UTF-8");
620 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
624 public void createALaCarteService_WithUserProvidedNamingFalse_RequestDetailsIsAsExpected() throws IOException {
625 ServiceInstantiation serviceInstantiationPayload = generateMockALaCarteServiceInstantiationPayload(false,
630 false, PROJECT_NAME, true, null);
632 RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
633 asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
635 URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request_naming_false.json");
636 String expected = IOUtils.toString(resource, "UTF-8");
637 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
641 public void generateALaCarteServiceInstantiationRequest_withVnfList_HappyFllow() throws IOException {
642 ServiceInstantiation serviceInstantiationPayload = generateALaCarteWithVnfsServiceInstantiationPayload();
643 RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
644 asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
646 String serviceExpected = IOUtils.toString(this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json"), "UTF-8");
647 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(serviceExpected, result);
650 @Test(dataProvider = "createVnfParameters")
651 public void createVnfRequestDetails_detailsAreAsExpected(boolean isFlagAddCloudOwnerActive, boolean isUserProvidedNaming, String file) throws IOException {
653 final List<Vnf> vnfList = new ArrayList<>(createVnfList(new HashMap<>(), null, isUserProvidedNaming, true).values());
654 ModelInfo siModelInfo = createServiceModelInfo();
655 String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
657 //we validate that the asyncInstantiationBL call to getUniqueName by simulate that aai retrun that original
658 //vnf name is used, and only next picked name is free.
659 Mockito.reset(aaiClient);
660 mockAaiClientAaiStatusOK();
661 when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME), eq(ResourceType.GENERIC_VNF))).thenReturn(true);
662 when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME+"_001"), eq(ResourceType.GENERIC_VNF))).thenReturn(false);
663 enableAddCloudOwnerOnMsoRequest(isFlagAddCloudOwnerActive);
665 String expected = IOUtils.toString(this.getClass().getResource(file), "UTF-8");
666 final RequestDetailsWrapper<VnfInstantiationRequestDetails> result = asyncInstantiationBL.generateVnfInstantiationRequest(vnfList.get(0), siModelInfo, serviceInstanceId, "pa0916");
667 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
671 public static Object[][] createVnfParameters() {
672 return new Object[][]{
673 {true, true, "/payload_jsons/bulk_vnf_request.json"},
674 {false, true, "/payload_jsons/bulk_vnf_request_without_cloud_owner.json"},
675 {true, false, "/payload_jsons/bulk_vnf_request_without_instance_name.json"},
680 public static Object[][] vfModuleRequestDetails(Method test) {
681 return new Object[][]{
682 {"cc3514e3-5a33-55df-13ab-12abad84e7cc", true, "/payload_jsons/vfmodule_instantiation_request.json"},
683 {null, true, "/payload_jsons/vfmodule_instantiation_request_without_volume_group.json"},
684 {null, false, "/payload_jsons/vfmodule_instantiation_request_without_instance_name.json"}
688 @Test(dataProvider = "vfModuleRequestDetails")
689 public void createVfModuleRequestDetails_detailsAreAsExpected(String volumeGroupInstanceId, boolean isUserProvidedNaming, String fileName) throws IOException {
691 ModelInfo siModelInfo = createServiceModelInfo();
692 ModelInfo vnfModelInfo = createVnfModelInfo(true);
693 List<Map<String, String>> instanceParams = ImmutableList.of(ImmutableMap.of("vmx_int_net_len", "24",
694 "vre_a_volume_size_0" , "120"));
695 Map<String, String> supplementaryParams = ImmutableMap.of("vre_a_volume_size_0" , "100",
696 "availability_zone_0" , "mtpocdv-kvm-az01");
697 VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", "56e2b103-637c-4d1a-adc8-3a7f4a6c3240",
698 "72d9d1cd-f46d-447a-abdb-451d6fb05fa8", instanceParams, supplementaryParams,
699 (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vRE_BV_expansion": null), "myVgName", true);
701 String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
702 String vnfInstanceId = "bb3514e3-5a33-55df-13ab-12abad84e7bb";
704 Mockito.reset(aaiClient);
705 mockAaiClientAaiStatusOK();
706 enableAddCloudOwnerOnMsoRequest();
707 when(aaiClient.isNodeTypeExistsByName(eq("vmxnjr001_AVPN_base_vRE_BV_expansion"), eq(ResourceType.VF_MODULE))).thenReturn(false);
709 String expected = IOUtils.toString(this.getClass().getResource(fileName), "UTF-8");
710 final RequestDetailsWrapper<VfModuleInstantiationRequestDetails> result = asyncInstantiationBL.generateVfModuleInstantiationRequest(
711 vfModule, siModelInfo, serviceInstanceId,
712 vnfModelInfo, vnfInstanceId, volumeGroupInstanceId, "pa0916");
713 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
717 public static Object[][] expectedAggregatedParams() {
718 return new Object[][]{
719 {ImmutableMap.of("a", "b", "c", "d"), ImmutableMap.of("e", "f", "g", "h"), ImmutableList.of(ImmutableMap.of("c", "d", "a", "b", "e", "f", "g", "h"))},
720 {ImmutableMap.of("a", "b", "c", "g"), ImmutableMap.of("c", "d", "e", "f"), ImmutableList.of(ImmutableMap.of("a", "b", "c", "d", "e", "f"))},
721 {ImmutableMap.of(), ImmutableMap.of("c", "d", "e", "f"), ImmutableList.of(ImmutableMap.of("c", "d", "e", "f"))},
722 {ImmutableMap.of("a", "b", "c", "g"), ImmutableMap.of(), ImmutableList.of(ImmutableMap.of("a", "b", "c", "g"))},
723 {ImmutableMap.of(), ImmutableMap.of(), ImmutableList.of()},
724 {null, ImmutableMap.of(), ImmutableList.of()},
725 {ImmutableMap.of(), null, ImmutableList.of()},
729 @Test(dataProvider = "expectedAggregatedParams")
730 public void testAggregateInstanceParamsAndSuppFile(Map<String, String> instanceParams, Map<String, String> suppParams, List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> expected) {
731 List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> aggParams = ((AsyncInstantiationBusinessLogicImpl)asyncInstantiationBL).aggregateAllInstanceParams(instanceParams, suppParams);
732 assertThat("Aggregated params are not as expected", aggParams, equalTo(expected));
736 public static Object[][] expectedNetworkRequestDetailsParameters() {
737 return new Object[][]{
738 {true, "/payload_jsons/network_instantiation_request.json"},
739 {false, "/payload_jsons/network_instantiation_request_without_instance_name.json"}
743 @Test(dataProvider = "expectedNetworkRequestDetailsParameters")
744 public void createNetworkRequestDetails_detailsAreAsExpected(boolean isUserProvidedNaming, String filePath) throws IOException {
746 final List<Network> networksList = new ArrayList<>(createNetworkList(null, isUserProvidedNaming, true).values());
747 ModelInfo siModelInfo = createServiceModelInfo();
748 String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
750 Mockito.reset(aaiClient);
751 mockAaiClientAaiStatusOK();
752 enableAddCloudOwnerOnMsoRequest();
753 when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME), eq(ResourceType.L3_NETWORK))).thenReturn(true);
754 when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME+"_001"), eq(ResourceType.L3_NETWORK))).thenReturn(false);
756 String expected = IOUtils.toString(this.getClass().getResource(filePath), "UTF-8");
757 final RequestDetailsWrapper<NetworkInstantiationRequestDetails> result = asyncInstantiationBL.generateNetworkInstantiationRequest(networksList.get(0), siModelInfo, serviceInstanceId, "pa0916");
758 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
762 public void createInstanceGroupRequestDetails_detailsAreAsExpected() throws IOException {
764 final InstanceGroup instanceGroup = createInstanceGroup(true, Action.Create);
765 ModelInfo siModelInfo = createServiceModelInfo();
766 String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
768 Mockito.reset(aaiClient);
769 mockAaiClientAaiStatusOK();
770 enableAddCloudOwnerOnMsoRequest();
771 when(aaiClient.isNodeTypeExistsByName(eq(VNF_GROUP_NAME), eq(ResourceType.INSTANCE_GROUP))).thenReturn(true);
772 when(aaiClient.isNodeTypeExistsByName(eq(VNF_GROUP_NAME+"_001"), eq(ResourceType.INSTANCE_GROUP))).thenReturn(false);
774 String expected = IOUtils.toString(this.getClass().getResource("/payload_jsons/instance_group_instantiation_request.json"), "UTF-8");
775 final RequestDetailsWrapper<InstanceGroupInstantiationRequestDetails> result = asyncInstantiationBL.generateInstanceGroupInstantiationRequest(instanceGroup, siModelInfo, serviceInstanceId, "az2018");
776 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
780 public void checkIfNullProjectNameSentToMso(){
781 ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
782 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
785 RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
786 asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
787 JsonNode jsonNode = new ObjectMapper().valueToTree(result.requestDetails);
788 Assert.assertTrue(jsonNode.get("project").isNull());
789 serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
790 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
792 false,"not null",false);
793 result = asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
794 jsonNode = new ObjectMapper().valueToTree(result.requestDetails);
795 Assert.assertTrue(jsonNode.get("project").get("projectName").asText().equalsIgnoreCase("not null"));
802 public void pushBulkJob_macroServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
803 LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
804 final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
806 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
807 100, true,PROJECT_NAME, true
810 pushJobAndAssertDates(startTestDate, request);
814 public void whenCreateServiceInfo_thenModelId_isModelVersionId() {
815 ServiceInfo serviceInfo = asyncInstantiationBL.createServiceInfo("userID",
816 generateALaCarteWithVnfsServiceInstantiationPayload(),
820 "myName", ServiceInfo.ServiceAction.INSTANTIATE);
821 assertEquals(SERVICE_MODEL_VERSION_ID, serviceInfo.getServiceModelId());
826 public void pushBulkJob_aLaCarteServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
827 LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
828 final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
829 pushJobAndAssertDates(startTestDate, request);
832 protected void pushJobAndAssertDates(LocalDateTime startTestDate, ServiceInstantiation request) {
833 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
834 configureMockitoWithMockedJob();
836 asyncInstantiationBL.pushBulkJob(request, "myUserId");
837 List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
839 List<Date> creationDates = new ArrayList<>();
840 for (ServiceInfo serviceInfo : serviceInfoList) {
841 creationDates.add(serviceInfo.getCreatedBulkDate());
843 LocalDateTime endTestDate = LocalDateTime.now();
845 //creation date of all services is the same
846 Assert.assertTrue(creationDates.stream().distinct().count() <= 1);
847 LocalDateTime creationDate = fromDate(creationDates.get(0));
848 assertFalse(creationDate.isBefore(startTestDate));
849 assertFalse(creationDate.isAfter(endTestDate));
852 protected void configureMockitoWithMockedJob() {
853 Mockito.reset(jobAdapterMock);
854 final Job job = mock(Job.class);
855 when(job.getStatus()).thenReturn(PENDING);
856 when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), any(), any())).thenReturn(job);
860 public static Object[][] msoToJobStatusDataProvider() {
861 return new Object[][]{
862 {"IN_PROGRESS", JobStatus.IN_PROGRESS},
863 {"INPROGRESS", JobStatus.IN_PROGRESS},
864 {"IN ProGREsS", JobStatus.IN_PROGRESS},
865 {"JAMES_HARDEN", JobStatus.IN_PROGRESS},
866 {"FAILED", JobStatus.FAILED},
867 {"COMpleTE", JobStatus.COMPLETED},
868 {"PENDING", JobStatus.IN_PROGRESS},
869 {"Paused", JobStatus.PAUSE},
870 {"Pause", JobStatus.PAUSE},
871 {"PENDING_MANUAL_TASK", JobStatus.PAUSE},
872 {"UNLOCKED", JobStatus.IN_PROGRESS}
876 @Test(dataProvider = "msoToJobStatusDataProvider")
877 public void whenGetStatusFromMso_calcRightJobStatus(String msoStatus, Job.JobStatus expectedJobStatus) {
878 AsyncRequestStatus asyncRequestStatus = asyncRequestStatusResponse(msoStatus);
879 assertThat(asyncInstantiationBL.calcStatus(asyncRequestStatus), equalTo(expectedJobStatus));
882 private void createNewAuditStatus(JobAuditStatus auditStatus)
884 Date createdDate= auditStatus.getCreated();
885 dataAccessService.saveDomainObject(auditStatus, getPropsMap());
886 setDateToStatus(auditStatus.getSource(), auditStatus.getJobStatus(), createdDate);
891 private static final String MSO_ARBITRARY_STATUS = "completed mso status";
894 public static Object[][] auditStatuses(Method test) {
895 return new Object[][]{
898 new String[]{ JobStatus.PENDING.toString(), JobStatus.IN_PROGRESS.toString()}
901 new String[]{ JobStatus.IN_PROGRESS.toString(), MSO_ARBITRARY_STATUS }
907 private void setDateToStatus(SourceStatus source, String status, Date date) {
908 List<JobAuditStatus> jobAuditStatusList = dataAccessService.getList(JobAuditStatus.class, getPropsMap());
909 DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
910 jobAuditStatusList.stream()
911 .filter(auditStatus -> source.equals(auditStatus.getSource()) && status.equals(auditStatus.getJobStatus()))
912 .forEach(auditStatus -> {
913 auditStatus.setCreated(date);
914 session.saveOrUpdate(auditStatus);
921 @Test(dataProvider = "auditStatuses")
922 public void givenSomeAuditStatuses_getStatusesOfSpecificSourceAndJobId_getSortedResultsMatchingToParameters(SourceStatus expectedSource, String [] expectedSortedStatuses){
923 UUID jobUuid = UUID.randomUUID();
924 List<JobAuditStatus> auditStatusList = com.google.common.collect.ImmutableList.of(
925 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(2))),
926 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(),"",toDate(LocalDateTime.now().minusHours(30))),
927 new JobAuditStatus(jobUuid, MSO_ARBITRARY_STATUS, SourceStatus.MSO, UUID.randomUUID(),"",toDate(LocalDateTime.now().minusHours(3))),
928 new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(3))),
929 new JobAuditStatus(UUID.randomUUID(), PENDING.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(3))));
930 auditStatusList.forEach((auditStatus) -> createNewAuditStatus(auditStatus));
931 List<JobAuditStatus> statuses = asyncInstantiationBL.getAuditStatuses(jobUuid, expectedSource);
932 List<String> statusesList = statuses.stream().map(status -> status.getJobStatus()).collect(Collectors.toList());
933 Assert.assertTrue(statuses.stream().allMatch(status -> (status.getSource().equals(expectedSource)&& status.getJobId().equals(jobUuid))),"Only statuses of " + expectedSource + " for " + jobUuid + " should be returned. Returned statuses: " + String.join(",", statusesList ));
934 assertThat(statusesList, contains(expectedSortedStatuses));
940 public void addSomeVidStatuses_getThem_verifyGetInsertedWithoutDuplicates(){
941 ImmutableList<JobStatus> statusesToBeInserted = ImmutableList.of(PENDING, IN_PROGRESS, IN_PROGRESS, COMPLETED);
942 UUID jobUuid = UUID.randomUUID();
943 statusesToBeInserted.forEach(status->
945 asyncInstantiationBL.auditVidStatus(jobUuid, status);
947 List<String> statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.VID).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList());
948 List<String> statusesWithoutDuplicates = statusesToBeInserted.stream().distinct().map(x -> x.toString()).collect(Collectors.toList());
949 assertThat(statusesFromDB, is(statusesWithoutDuplicates));
953 public static Object[][] msoAuditStatuses(Method test) {
954 UUID jobUuid = UUID.randomUUID();
955 UUID requestId = UUID.randomUUID();
956 return new Object[][]{
960 new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.MSO, null, null),
961 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
962 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
963 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
964 new JobAuditStatus(jobUuid, COMPLETED.toString(), SourceStatus.MSO, requestId, null)),
965 ImmutableList.of(PENDING.toString(), IN_PROGRESS.toString(), COMPLETED.toString()),
966 "All distinct statuses should be without duplicates"
971 new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.MSO, null, null),
972 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
973 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, "aa"),
974 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, "aa"),
975 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(), "aa"),
976 new JobAuditStatus(jobUuid, COMPLETED.toString(), SourceStatus.MSO, requestId, null)),
977 ImmutableList.of(PENDING.toString(), IN_PROGRESS.toString(), IN_PROGRESS.toString(),IN_PROGRESS.toString(), COMPLETED.toString()),
978 "Statuses should be without duplicates only with same requestId and additionalInfo"
984 @Test(dataProvider = "msoAuditStatuses")
985 public void addSomeMsoStatuses_getThem_verifyGetInsertedWithoutDuplicates(UUID jobUuid, ImmutableList<JobAuditStatus> msoStatuses, ImmutableList<String> expectedStatuses, String assertionReason) {
986 msoStatuses.forEach(status -> {
987 asyncInstantiationBL.auditMsoStatus(status.getJobId(), status.getJobStatus(), status.getRequestId() != null ? status.getRequestId().toString() : null, status.getAdditionalInfo());
989 List<String> statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.MSO).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList());
990 assertThat( assertionReason, statusesFromDB, is(expectedStatuses));
994 public void addSameStatusOfVidAndMso_verifyThatBothWereAdded(){
995 UUID jobUuid = UUID.randomUUID();
996 JobStatus sameStatus = IN_PROGRESS;
997 asyncInstantiationBL.auditMsoStatus(jobUuid, sameStatus.toString(),null,null);
998 asyncInstantiationBL.auditVidStatus(jobUuid, sameStatus);
999 List<JobAuditStatus> list = dataAccessService.getList(
1000 JobAuditStatus.class,
1001 String.format(" where JOB_ID = '%s'", jobUuid),
1003 Assert.assertEquals(list.size(),2);
1004 assertThat(list,everyItem(hasProperty("jobStatus", is(sameStatus.toString()))));
1008 public static Object[][] msoRequestStatusFiles(Method test) {
1009 return new Object[][]{
1010 {"/responses/mso/orchestrationRequestsServiceInstance.json"},
1011 {"/responses/mso/orchestrationRequestsVnf.json"},
1012 {"/responses/mso/orchestrationRequestsMockedMinimalResponse.json"}
1016 @Test(dataProvider="msoRequestStatusFiles")
1017 public void verifyAsyncRequestStatus_canBeReadFromSample(String msoResponseFile) throws IOException {
1018 AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject(
1020 AsyncRequestStatus.class);
1021 assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE"));
1025 public void deleteJobInfo_pending_deleted() {
1026 doNothing().when(jobsBrokerServiceMock).delete(any());
1027 UUID uuid = createServicesInfoWithDefaultValues(PENDING);
1028 asyncInstantiationBL.deleteJob(uuid);
1029 assertNotNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info wasn't deleted");
1032 @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)
1033 public void deleteJobInfo_notAllowdStatus_shouldSendError() {
1034 UUID uuid = createServicesInfoWithDefaultValues(COMPLETED);
1035 doThrow(new IllegalStateException(DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)).when(jobsBrokerServiceMock).delete(any());
1037 asyncInstantiationBL.deleteJob(uuid);
1038 } catch (Exception e) {
1039 assertNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info shouldn't deleted");
1045 public Object[][] jobStatusesFinal() {
1046 return Arrays.stream(Job.JobStatus.values())
1047 .filter(t -> ImmutableList.of(COMPLETED, FAILED, STOPPED).contains(t))
1048 .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
1051 @Test(dataProvider = "jobStatusesFinal")
1052 public void whenHideService_theServiceNotReturnedInServiceList(JobStatus jobStatus) {
1053 UUID uuidToHide = createServicesInfoWithDefaultValues(jobStatus);
1054 UUID uuidToShown = createServicesInfoWithDefaultValues(jobStatus);
1055 List<UUID> serviceInfoList = listServicesUUID();
1056 assertThat(serviceInfoList, hasItems(uuidToHide, uuidToShown));
1058 asyncInstantiationBL.hideServiceInfo(uuidToHide);
1059 serviceInfoList = listServicesUUID();
1060 assertThat(serviceInfoList, hasItem(uuidToShown));
1061 assertThat(serviceInfoList, not(hasItem(uuidToHide)));
1065 protected List<UUID> listServicesUUID() {
1066 return asyncInstantiationBL.getAllServicesInfo().stream().map(ServiceInfo::getJobId).collect(Collectors.toList());
1070 public Object[][] jobStatusesNotFinal() {
1071 return Arrays.stream(Job.JobStatus.values())
1072 .filter(t -> ImmutableList.of(PENDING, IN_PROGRESS, PAUSE).contains(t))
1073 .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
1076 @Test(dataProvider = "jobStatusesNotFinal",
1077 expectedExceptions = OperationNotAllowedException.class,
1078 expectedExceptionsMessageRegExp = "jobId.*Service status does not allow hide service, status = .*")
1079 public void hideServiceInfo_notAllowedStatus_shouldSendError(JobStatus jobStatus) {
1080 UUID uuid = createServicesInfoWithDefaultValues(jobStatus);
1082 asyncInstantiationBL.hideServiceInfo(uuid);
1083 } catch (Exception e) {
1084 assertFalse(asyncInstantiationBL.getServiceInfoByJobId(uuid).isHidden(), "service info shouldn't be hidden");
1090 public void whenUseGetCounterInMultiThreads_EachThreadGetDifferentCounter() throws InterruptedException {
1092 ExecutorService executor = Executors.newFixedThreadPool(SIZE);
1093 List<Callable<Integer>> tasks = IntStream.rangeClosed(0, SIZE)
1094 .mapToObj(x-> ((Callable<Integer>)() -> asyncInstantiationBL.getCounterForName("a")))
1095 .collect(Collectors.toList());
1096 Set<Integer> expectedResults = IntStream.rangeClosed(0, SIZE).boxed().collect(Collectors.toSet());
1097 executor.invokeAll(tasks)
1098 .forEach(future -> {
1100 assertTrue( expectedResults.remove(future.get()), "got unexpected counter");
1102 catch (Exception e) {
1103 throw new RuntimeException(e);
1107 assertThat(expectedResults.size(), is(0));
1111 public void whenUseGetCounterForSameName_numbersReturnedByOrder() {
1113 String name = UUID.randomUUID().toString();
1115 for (int i=0; i<SIZE; i++) {
1116 assertThat(asyncInstantiationBL.getCounterForName(name), is(i));
1121 public void whenNamedInUsedInAai_getNextNumber() {
1122 String name = someCommonStepsAndGetName();
1123 ResourceType type = ResourceType.GENERIC_VNF;
1124 when(aaiClient.isNodeTypeExistsByName(name, type)).thenReturn(true);
1125 when(aaiClient.isNodeTypeExistsByName(name+"_001", type)).thenReturn(false);
1126 assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name+"_001"));
1129 private String someCommonStepsAndGetName() {
1130 mockAaiClientAaiStatusOK();
1131 return UUID.randomUUID().toString();
1134 private void mockAaiClientAaiStatusOK() {
1135 when(aaiClient.isNodeTypeExistsByName(eq(AsyncInstantiationBusinessLogicImpl.NAME_FOR_CHECK_AAI_STATUS), any())).thenReturn(false);
1138 @Test(expectedExceptions=ExceptionWithRequestInfo.class)
1139 public void whenAaiBadResponseCode_throwInvalidAAIResponseException() {
1140 String name = someCommonStepsAndGetName();
1141 ResourceType type = ResourceType.SERVICE_INSTANCE;
1142 when(aaiClient.isNodeTypeExistsByName(name, type)).thenThrow(aaiNodeQueryBadResponseException());
1143 asyncInstantiationBL.getUniqueName(name, type);
1146 @Test(expectedExceptions=MaxRetriesException.class)
1147 public void whenAaiAlwaysReturnNameUsed_throwInvalidAAIResponseException() {
1148 String name = someCommonStepsAndGetName();
1149 ResourceType type = ResourceType.VF_MODULE;
1150 when(aaiClient.isNodeTypeExistsByName(any(), eq(type))).thenReturn(true);
1151 asyncInstantiationBL.setMaxRetriesGettingFreeNameFromAai(10);
1152 asyncInstantiationBL.getUniqueName(name, type);
1156 public void testFormattingOfNameAndCounter() {
1157 AsyncInstantiationBusinessLogicImpl bl = (AsyncInstantiationBusinessLogicImpl) asyncInstantiationBL;
1158 assertThat(bl.formatNameAndCounter("x", 0), equalTo("x"));
1159 assertThat(bl.formatNameAndCounter("x", 3), equalTo("x_003"));
1160 assertThat(bl.formatNameAndCounter("x", 99), equalTo("x_099"));
1161 assertThat(bl.formatNameAndCounter("x", 100), equalTo("x_100"));
1162 assertThat(bl.formatNameAndCounter("x", 1234), equalTo("x_1234"));
1166 public void pushBulkJob_verifyAlacarteFlow_useALaCartServiceInstantiationJobType(){
1167 final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
1169 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
1170 configureMockitoWithMockedJob();
1172 ArgumentCaptor<JobType> argumentCaptor = ArgumentCaptor.forClass(JobType.class);
1173 asyncInstantiationBL.pushBulkJob(request, "myUserId");
1174 verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyInt());
1175 assertTrue(argumentCaptor.getValue().equals(JobType.ALaCarteServiceInstantiation));
1179 public void pushBulkJob_verifyMacroFlow_useMacroServiceInstantiationJobType(){
1180 final ServiceInstantiation request = generateMacroMockServiceInstantiationPayload(false, Collections.emptyMap());
1182 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
1183 configureMockitoWithMockedJob();
1185 ArgumentCaptor<JobType> argumentCaptor = ArgumentCaptor.forClass(JobType.class);
1186 asyncInstantiationBL.pushBulkJob(request, "myUserId");
1187 verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyInt());
1188 assertTrue(argumentCaptor.getValue().equals(JobType.MacroServiceInstantiation));
1192 public void generateALaCarteServiceInstantiationRequest_verifyRequestIsAsExpected() throws IOException {
1193 ServiceInstantiation serviceInstantiationPayload = generateALaCarteServiceInstantiationPayload();
1194 final URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json");
1195 RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
1196 asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
1197 String expected = IOUtils.toString(resource, "UTF-8");
1198 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
1202 public void generateALaCarteServiceDeletionRequest_verifyRequestIsAsExpected() throws IOException {
1203 final URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_deletion_request.json");
1204 String expected = IOUtils.toString(resource, "UTF-8");
1206 ServiceInstantiation serviceDeletionPayload = generateALaCarteServiceDeletionPayload();
1207 RequestDetailsWrapper<ServiceDeletionRequestDetails> result =
1208 asyncInstantiationBL.generateALaCarteServiceDeletionRequest(null, serviceDeletionPayload, "az2016");
1210 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
1214 public void getALaCarteServiceDeletionPath_verifyPathIsAsExpected() throws IOException {
1216 String expected = "/serviceInstantiation/v./serviceInstances/f36f5734-e9df-4fbf-9f35-61be13f028a1";
1218 String result = asyncInstantiationBL.getServiceDeletionPath("f36f5734-e9df-4fbf-9f35-61be13f028a1");
1220 assertThat(result, matchesPattern(expected));
1224 public void getInstanceGroupsDeletionPath_verifyPathIsAsExpected() {
1226 assertEquals(asyncInstantiationBL.getInstanceGroupDeletePath("9aada4af-0f9b-424f-ae21-e693bd3e005b"),
1227 "/serviceInstantiation/v7/instanceGroups/9aada4af-0f9b-424f-ae21-e693bd3e005b");
1231 public static Object[][] testBuildVnfInstanceParamsDataProvider(Method test) {
1232 return new Object[][]{
1234 Collections.EMPTY_LIST,
1236 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1237 ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
1240 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3"))
1243 ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")), //vnf_name, vf_module_name are excluded
1245 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1246 ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")),
1247 ImmutableList.of(Collections.EMPTY_MAP),
1248 Collections.singletonList(null)
1251 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3","j1", "w1"))
1254 Collections.EMPTY_LIST,
1255 Arrays.asList(null, null),
1257 Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
1260 ImmutableList.of(Collections.EMPTY_MAP),
1262 ImmutableList.of(Collections.EMPTY_MAP),
1263 ImmutableList.of(Collections.EMPTY_MAP)
1266 Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
1269 Collections.EMPTY_LIST,
1271 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1272 ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
1275 Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
1278 ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")),
1280 ImmutableList.of(Collections.EMPTY_MAP)
1283 ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1"))
1286 ImmutableList.of(ImmutableMap.of("vnf_name","w2", "vf_module_name", "w3", "j2", "w2", "j4","w4")),
1288 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1289 ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
1292 ImmutableList.of(ImmutableMap.of("j2", "w2", "j4","w4"))
1298 @Test(dataProvider="testBuildVnfInstanceParamsDataProvider")
1299 public void testBuildVnfInstanceParams(List<Map<String, String>> currentVnfInstanceParams,
1300 List<List<Map<String, String>>> vfModulesInstanceParams,
1301 boolean isFeatureActive,
1302 List<Map<String,String>> expectedResult){
1303 when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(isFeatureActive);
1304 List<VfModuleMacro> vfModules =
1305 vfModulesInstanceParams.stream().map(params-> new VfModuleMacro(new ModelInfo(), null, null, params)).collect(Collectors.toList());
1306 List<Map<String,String>> actual = asyncInstantiationBL.buildVnfInstanceParams(currentVnfInstanceParams, vfModules);
1307 assertThat(actual, equalTo(expectedResult));
1312 public void whenLcpRegionNotEmpty_thenCloudRegionIdOfResourceIsLegacy() {
1313 String legacyCloudRegion = "legacyCloudRegion";
1314 Vnf vnf = new Vnf(new ModelInfo(), null, null, Action.Create.name(), null, "anyCloudRegion", legacyCloudRegion, null, null, null, false, null, null);
1315 assertThat(vnf.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
1321 public void whenLcpRegionNotEmpty_thenCloudRegionIdOfServiceIsLegacy() {
1322 String legacyCloudRegion = "legacyCloudRegion";
1323 ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
1324 null, null, "anyCloudRegion", legacyCloudRegion, null, null, null, null, null, null, null, null,
1325 false, 1,false, false, null, null, Action.Create.name());
1326 assertThat(service.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
1330 public void createVolumeGroup_verifyResultAsExpected() throws IOException {
1331 final URL resource = this.getClass().getResource("/payload_jsons/volumegroup_instantiation_request.json");
1332 VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1",
1333 "56e2b103-637c-4d1a-adc8-3a7f4a6c3240",
1334 "72d9d1cd-f46d-447a-abdb-451d6fb05fa8",
1335 Collections.emptyList(),
1336 Collections.emptyMap(),
1337 "vmxnjr001_AVPN_base_vRE_BV_expansion",
1340 vfModule.getModelInfo().setModelInvariantId("ff5256d2-5a33-55df-13ab-12abad84e7ff");
1341 vfModule.getModelInfo().setModelVersion("1");
1342 ModelInfo vnfModelInfo = createVnfModelInfo(true);
1343 RequestDetailsWrapper<VolumeGroupRequestDetails> result =
1344 asyncInstantiationBL.generateVolumeGroupInstantiationRequest(vfModule,
1345 createServiceModelInfo(),
1346 "ff3514e3-5a33-55df-13ab-12abad84e7ff",
1350 String expected = IOUtils.toString(resource, "UTF-8");
1351 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
1355 public void getJobTypeByRequest_verifyResultAsExpected(){
1356 ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
1357 null, null, null, null, null, null, null, null, null, null, null, null,
1358 false, 1,false, false, null, null, Action.Create.name());
1359 JobType jobType = asyncInstantiationBL.getJobType(service) ;
1360 assertThat(jobType, equalTo(JobType.MacroServiceInstantiation));
1361 service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
1362 null, null, null, null, null, null, null, null, null, null, null, null,
1363 false, 1,false, true, null, null, Action.Create.name());
1364 jobType = asyncInstantiationBL.getJobType(service);
1365 assertThat(jobType, equalTo(JobType.ALaCarteServiceInstantiation));
1366 service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
1367 null, null, null, null, null, null, null, null, null, null, null, null,
1368 false, 1,false, true, null, null, Action.Delete.name());
1369 jobType = asyncInstantiationBL.getJobType(service);
1370 assertThat(jobType, equalTo(JobType.ALaCarteService));
1373 protected ServiceInstantiation generateALaCarteServiceInstantiationPayload() {
1374 return generateMockALaCarteServiceInstantiationPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API");
1377 private ServiceInstantiation generateALaCarteServiceDeletionPayload() {
1378 return generateMockALaCarteServiceDeletionPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890");
1381 static class MockedJob implements Job {
1383 private static Map<UUID, MockedJob> uuidToJob = new HashMap<>();
1385 public static void putJob(UUID uuid, MockedJob job) {
1386 uuidToJob.put(uuid, job);
1389 public static MockedJob getJob(UUID uuid) {
1390 return uuidToJob.get(uuid);
1394 private String optimisticUniqueServiceInstanceName;
1396 public MockedJob(String optimisticUniqueServiceInstanceName) {
1397 this.optimisticUniqueServiceInstanceName = optimisticUniqueServiceInstanceName;
1400 private UUID uuid = UUID.randomUUID();
1403 public UUID getUuid() {
1408 public void setUuid(UUID uuid) {
1413 public JobStatus getStatus() {
1414 return JobStatus.PENDING;
1418 public void setStatus(JobStatus status) {
1423 public Map<String, Object> getData() {
1428 public JobSharedData getSharedData() {
1429 return new JobSharedData(uuid, "", null);
1433 public void setTypeAndData(JobType jobType, Map<String, Object> commandData) {
1438 public UUID getTemplateId() {
1443 public void setTemplateId(UUID templateId) {
1448 public Integer getIndexInBulk() {
1453 public void setIndexInBulk(Integer indexInBulk) {
1458 public JobType getType() {
1462 public String getOptimisticUniqueServiceInstanceName() {
1463 return optimisticUniqueServiceInstanceName;