2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020 Telecom Italia
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.so.bpmn.infrastructure.scripts
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.json.JSONArray
26 import org.json.JSONObject
27 import org.onap.aai.domain.yang.v19.*
28 import org.onap.aaiclient.client.aai.AAIResourcesClient
29 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
30 import org.onap.aaiclient.client.aai.entities.Relationships
31 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
32 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
33 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
34 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
35 import org.onap.logging.filter.base.ONAPComponents
36 import org.onap.so.bpmn.common.scripts.*
37 import org.onap.so.bpmn.core.UrnPropertiesReader
38 import org.onap.so.bpmn.core.json.JsonUtils
39 import org.onap.so.client.HttpClient
40 import org.onap.so.db.request.beans.ResourceOperationStatus
41 import org.onap.so.serviceinstancebeans.*
42 import org.slf4j.Logger
43 import org.slf4j.LoggerFactory
45 import javax.ws.rs.core.Response
47 import static org.apache.commons.lang3.StringUtils.isBlank
49 class DoCommonCoreNSSI extends AbstractServiceTaskProcessor {
51 private final String PREFIX ="DoCommonCoreNSSI"
53 private static final Logger LOGGER = LoggerFactory.getLogger( DoCommonCoreNSSI.class)
55 private JsonUtils jsonUtil = new JsonUtils()
56 private ExceptionUtil exceptionUtil = new ExceptionUtil()
57 private RequestDBUtil requestDBUtil = new RequestDBUtil()
60 void preProcessRequest(DelegateExecution execution) {
61 LOGGER.trace("${getPrefix()} Start preProcessRequest")
63 def currentNSSI = execution.getVariable("currentNSSI")
69 String nssiId = execution.getVariable("serviceInstanceID")
70 if (isBlank(nssiId)) {
71 String msg = "NSSI service instance id is null"
73 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
76 currentNSSI['nssiId'] = nssiId
80 String nsiId = execution.getVariable("nsiId")
82 String msg = "nsiId is null"
84 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
87 currentNSSI['nsiId'] = nsiId
92 String sliceProfile = jsonUtil.getJsonValue(execution.getVariable("sliceParams"), "sliceProfile")
93 if (isBlank(sliceProfile)) {
94 String msg = "Slice Profile is null"
95 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
97 currentNSSI['sliceProfile'] = sliceProfile
101 def snssaiList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceProfile, "snssaiList"))
103 String sNssai = snssaiList.get(0)
104 currentNSSI['S-NSSAI'] = sNssai
108 String sliceProfileId = jsonUtil.getJsonValue(sliceProfile, "sliceProfileId")
109 currentNSSI['sliceProfileId'] = sliceProfileId
111 execution.setVariable("currentNSSI", currentNSSI)
114 LOGGER.trace("***** ${getPrefix()} Exit preProcessRequest")
119 * Queries Network Service Instance in AAI
122 void getNetworkServiceInstance(DelegateExecution execution) {
123 LOGGER.trace("${getPrefix()} Start getNetworkServiceInstance")
125 AAIResourcesClient client = getAAIClient()
127 def currentNSSI = execution.getVariable("currentNSSI")
129 String nssiId = currentNSSI['nssiId']
131 AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
132 Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, nssiUri)
134 if (nssiOpt.isPresent()) {
135 ServiceInstance nssi = nssiOpt.get()
136 currentNSSI['nssi'] = nssi
138 ServiceInstance networkServiceInstance = handleNetworkInstance(execution, nssiId, nssiUri, client)
139 currentNSSI['networkServiceInstance'] = networkServiceInstance
142 String msg = String.format("NSSI %s not found in AAI", nssiId)
144 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
147 LOGGER.trace("${getPrefix()} Exit getNetworkServiceInstance")
152 * Handles Network Service
156 * @return Network Service Instance
158 private ServiceInstance handleNetworkInstance(DelegateExecution execution, String nssiId, AAIResourceUri nssiUri, AAIResourcesClient client ) {
159 ServiceInstance networkServiceInstance = null
161 def currentNSSI = execution.getVariable("currentNSSI")
163 AAIResultWrapper wrapper = client.get(nssiUri)
164 Optional<Relationships> relationships = wrapper.getRelationships()
166 if (relationships.isPresent()) {
167 for (AAIResourceUri networkServiceInstanceUri : relationships.get().getRelatedUris(Types.SERVICE_INSTANCE)) {
168 Optional<ServiceInstance> networkServiceInstanceOpt = client.get(ServiceInstance.class, networkServiceInstanceUri)
169 if (networkServiceInstanceOpt.isPresent()) {
170 networkServiceInstance = networkServiceInstanceOpt.get()
172 if (networkServiceInstance.getServiceRole() == "Network Service") { // Network Service role
173 currentNSSI['networkServiceInstanceUri'] = networkServiceInstanceUri
178 String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
180 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
185 String msg = String.format("No relationship presented for NSSI %s in AAI", nssiId)
187 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
190 if(networkServiceInstance == null) {
191 String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
193 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
196 return networkServiceInstance
201 * Queries constitute VNF from Network Service Instance
204 void getConstituteVNFFromNetworkServiceInst(DelegateExecution execution) {
205 LOGGER.trace("${getPrefix()} Start getConstituteVNFFromNetworkServiceInst")
207 def currentNSSI = execution.getVariable("currentNSSI")
209 AAIResourcesClient client = getAAIClient()
211 AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
212 AAIResultWrapper wrapper = client.get(networkServiceInstanceUri);
213 Optional<Relationships> relationships = wrapper.getRelationships()
214 if (relationships.isPresent()) {
215 for (AAIResourceUri constituteVnfUri : relationships.get().getRelatedUris(Types.GENERIC_VNF)) {
216 currentNSSI['constituteVnfUri'] = constituteVnfUri
217 Optional<GenericVnf> constituteVnfOpt = client.get(GenericVnf.class, constituteVnfUri)
218 if(constituteVnfOpt.isPresent()) {
219 GenericVnf constituteVnf = constituteVnfOpt.get()
220 currentNSSI['constituteVnf'] = constituteVnf
223 String msg = String.format("No constitute VNF found for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
225 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
228 break // Should be only one constitute VNF
232 String msg = String.format("No relationship presented for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
234 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
237 LOGGER.trace("${getPrefix()} Exit getConstituteVNFFromNetworkServiceInst")
243 * Retrieves NSSI associated profiles from AAI
246 void getNSSIAssociatedProfiles(DelegateExecution execution) {
247 LOGGER.trace("${getPrefix()} Start getNSSIAssociatedProfiles")
249 def currentNSSI = execution.getVariable("currentNSSI")
251 ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
253 List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
255 if(associatedProfiles.isEmpty()) {
256 String msg = String.format("No associated profiles found for NSSI %s in AAI", nssi.getServiceInstanceId())
258 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
261 currentNSSI['associatedProfiles'] = associatedProfiles
264 LOGGER.trace("${getPrefix()} Exit getNSSIAssociatedProfiles")
269 * Calculates a final list of S-NSSAI
272 void calculateSNSSAI(DelegateExecution execution) {
273 LOGGER.trace("${getPrefix()} Start calculateSNSSAI")
275 def currentNSSI = execution.getVariable("currentNSSI")
277 List<SliceProfile> associatedProfiles = (List<SliceProfile>)currentNSSI['associatedProfiles']
279 String currentSNSSAI = currentNSSI['S-NSSAI']
281 List<String> snssais = new ArrayList<>()
283 String isCreateSliceProfileInstanceVar = execution.getVariable("isCreateSliceProfileInstance" ) // Not exist in case of Deallocate
285 boolean isCreateSliceProfileInstance = Boolean.parseBoolean(isCreateSliceProfileInstanceVar)
287 if(isCreateSliceProfileInstance) { // Slice Profile Instance has to be created
288 for (SliceProfile associatedProfile : associatedProfiles) {
289 snssais.add(associatedProfile.getSNssai())
292 snssais.add(currentSNSSAI)
294 else { // Slice profile instance has to be deleted
295 for (SliceProfile associatedProfile : associatedProfiles) {
296 if (!associatedProfile.getSNssai().equals(currentSNSSAI)) { // not current S-NSSAI
297 snssais.add(associatedProfile.getSNssai())
299 currentNSSI['sliceProfileS-NSSAI'] = associatedProfile
304 currentNSSI['S-NSSAIs'] = snssais
306 LOGGER.trace("${getPrefix()} Exit calculateSNSSAI")
311 * Invoke PUT Service Instance API
314 void invokePUTServiceInstance(DelegateExecution execution) {
315 LOGGER.trace("${getPrefix()} Start invokePUTServiceInstance")
317 def currentNSSI = execution.getVariable("currentNSSI")
320 //url:/onap/so/infra/serviceInstantiation/v7/serviceInstances/{serviceInstanceId}"
321 def nsmfЕndPoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) // ???
323 ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
325 String url = String.format("${nsmfЕndPoint}/serviceInstantiation/v7/serviceInstances/%s", networkServiceInstance.getServiceInstanceId())
327 currentNSSI['putServiceInstanceURL'] = url
329 String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
330 String basicAuth = UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
333 String basicAuthValue = encryptBasicAuth(basicAuth, msoKey) //utils.encrypt(basicAuth, msoKey)
334 String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey) //utils.getBasicAuth(basicAuthValue, msoKey)
336 String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
337 if(errorCode == null || errorCode.isEmpty()) { // No error
338 authHeader = responseAuthHeader
341 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
344 def requestDetails = ""
345 String prepareRequestDetailsResponse = prepareRequestDetails(execution)
346 errorCode = jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorCode")
347 if(errorCode == null || errorCode.isEmpty()) { // No error
348 requestDetails = prepareRequestDetailsResponse
351 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorMessage"))
354 String callPUTServiceInstanceResponse = callPUTServiceInstance(url, authHeader, requestDetails)
355 String putServiceInstanceResponse = ""
357 if(errorCode == null || errorCode.isEmpty()) { // No error
358 putServiceInstanceResponse = callPUTServiceInstanceResponse
361 LOGGER.error(jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
362 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
366 String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
368 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
371 LOGGER.trace("${getPrefix()} Exit invokePUTServiceInstance")
375 String callPUTServiceInstance(String url, String authHeader, String requestDetailsStr) {
376 String errorCode = ""
377 String errorMessage = ""
381 HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.EXTERNAL)
382 httpClient.addAdditionalHeader("Authorization", authHeader)
383 httpClient.addAdditionalHeader("Accept", "application/json")
385 Response httpResponse = httpClient.put(requestDetailsStr) // check http code ???
388 if (httpResponse.hasEntity()) {
389 response = httpResponse.readEntity(String.class)
393 errorMessage = "No response received."
396 " \"errorCode\": \"${errorCode}\",\n" +
397 " \"errorMessage\": \"${errorMessage}\"\n" +
402 String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
406 " \"errorCode\": \"7000\",\n" +
407 " \"errorMessage\": \"${msg}\"\n" +
420 * @param requestDetails
423 ModelInfo prepareModelInfo(DelegateExecution execution) {
425 def currentNSSI = execution.getVariable("currentNSSI")
426 ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
428 ModelInfo modelInfo = new ModelInfo()
430 modelInfo.setModelType(ModelType.service)
431 modelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
433 AAIResourcesClient client = getAAIClient()
435 AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(networkServiceInstance.getModelInvariantId()).modelVer(networkServiceInstance.getModelVersionId()))
436 Optional<ModelVer> modelVerOpt = client.get(ModelVer.class, modelVerUrl)
438 if (modelVerOpt.isPresent()) {
439 modelInfo.setModelVersionId(modelVerOpt.get().getModelVersionId())
440 modelInfo.setModelName(modelVerOpt.get().getModelName())
441 modelInfo.setModelVersion(modelVerOpt.get().getModelVersion())
449 * Prepares subscriber info
451 * @return SubscriberInfo
453 SubscriberInfo prepareSubscriberInfo(DelegateExecution execution) {
454 def currentNSSI = execution.getVariable("currentNSSI")
456 String globalSubscriberId = execution.getVariable("globalSubscriberId")
458 String subscriberName = execution.getVariable("subscriberName")
460 SubscriberInfo subscriberInfo = new SubscriberInfo()
461 subscriberInfo.setGlobalSubscriberId(globalSubscriberId)
462 subscriberInfo.setSubscriberName(subscriberName)
465 AAIResourcesClient client = getAAIClient()
467 Customer customer = null
469 AAIResourceUri networkServiceInstanceUri = currentNSSI['networkServiceInstanceUri']
470 AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
471 Optional<Relationships> serviceSubscriptionRelationshipsOps = wrapper.getRelationships()
472 if(serviceSubscriptionRelationshipsOps.isPresent()) {
473 List<AAIResourceUri> serviceSubscriptionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedUris(Types.SERVICE_SUBSCRIPTION)
474 if(!(serviceSubscriptionRelatedAAIUris == null || serviceSubscriptionRelatedAAIUris.isEmpty())) {
475 AAIResourceUri serviceSubscriptionUri = serviceSubscriptionRelatedAAIUris.get(0) // Many-To-One relation
476 Optional<ServiceSubscription> serviceSubscriptionOpt = client.get(ServiceSubscription.class, serviceSubscriptionUri)
478 if(serviceSubscriptionOpt.isPresent()) {
479 currentNSSI['serviceSubscription'] = serviceSubscriptionOpt.get()
482 wrapper = client.get(serviceSubscriptionUri)
483 Optional<Relationships> customerRelationshipsOps = wrapper.getRelationships()
484 if(customerRelationshipsOps.isPresent()) {
485 List<AAIResourceUri> customerRelatedAAIUris = customerRelationshipsOps.get().getRelatedUris(Types.CUSTOMER)
486 if(!(customerRelatedAAIUris == null || customerRelatedAAIUris.isEmpty())) {
487 Optional<Customer> customerOpt = client.get(Customer.class, customerRelatedAAIUris.get(0)) // Many-To-One relation
488 if(customerOpt.isPresent()) {
489 customer = customerOpt.get()
490 subscriberInfo.setSubscriberName(customer.getSubscriberName())
498 return subscriberInfo
503 * Prepares Request Info
505 * @return RequestInfo
507 RequestInfo prepareRequestInfo(DelegateExecution execution, ServiceInstance networkServiceInstance) {
508 def currentNSSI = execution.getVariable("currentNSSI")
510 String productFamilyId = execution.getVariable("productFamilyId")
512 RequestInfo requestInfo = new RequestInfo()
514 requestInfo.setInstanceName(networkServiceInstance.getServiceInstanceName())
515 requestInfo.setSource("VID")
516 requestInfo.setProductFamilyId(productFamilyId)
517 requestInfo.setRequestorId("NBI")
524 * Prepares Model Info
525 * @param networkServiceInstance
529 ModelInfo prepareServiceModelInfo(ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
531 ModelInfo serviceModelInfo = new ModelInfo()
532 serviceModelInfo.setModelType(ModelType.service)
533 serviceModelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
535 serviceModelInfo.setModelVersionId(modelInfo.getModelVersionId())
536 serviceModelInfo.setModelName(modelInfo.getModelName())
537 serviceModelInfo.setModelVersion(modelInfo.getModelVersion())
539 return serviceModelInfo
544 * Prepares Cloud configuration
546 * @return CloudConfiguration
548 CloudConfiguration prepareCloudConfiguration(DelegateExecution execution) {
549 def currentNSSI = execution.getVariable("currentNSSI")
551 CloudConfiguration cloudConfiguration = new CloudConfiguration()
553 AAIResourcesClient client = getAAIClient()
555 AAIResourceUri constituteVnfUri = currentNSSI['constituteVnfUri']
556 AAIResultWrapper wrapper = client.get(constituteVnfUri)
557 Optional<Relationships> cloudRegionRelationshipsOps = wrapper.getRelationships()
559 if(cloudRegionRelationshipsOps.isPresent()) {
560 List<AAIResourceUri> cloudRegionRelatedAAIUris = cloudRegionRelationshipsOps.get().getRelatedUris(Types.CLOUD_REGION)
561 if (!(cloudRegionRelatedAAIUris == null || cloudRegionRelatedAAIUris.isEmpty())) {
562 AAIResourceUri cloudRegionRelatedAAIUri = cloudRegionRelatedAAIUris.get(0)
563 currentNSSI['cloudRegionRelatedAAIUri'] = cloudRegionRelatedAAIUri
565 Optional<CloudRegion> cloudRegionrOpt = client.get(CloudRegion.class, cloudRegionRelatedAAIUris.get(0))
566 CloudRegion cloudRegion = null
567 if (cloudRegionrOpt.isPresent()) {
568 cloudRegion = cloudRegionrOpt.get()
569 cloudConfiguration.setLcpCloudRegionId(cloudRegion.getCloudRegionId())
570 for (Tenant tenant : cloudRegion.getTenants().getTenant()) {
571 cloudConfiguration.setTenantId(tenant.getTenantId())
572 break // only one is required
575 cloudConfiguration.setCloudOwner(cloudRegion.getCloudOwner())
580 return cloudConfiguration
585 * Prepares a list of VF Modules
587 * @param constituteVnf
588 * @return List<VfModules>
590 List<VfModules> prepareVfModules(DelegateExecution execution, GenericVnf constituteVnf) {
592 AAIResourcesClient client = getAAIClient()
594 List<VfModules> vfModuless = new ArrayList<>()
595 for (VfModule vfModule : constituteVnf.getVfModules().getVfModule()) {
596 VfModules vfmodules = new VfModules()
598 ModelInfo vfModuleModelInfo = new ModelInfo()
599 vfModuleModelInfo.setModelInvariantUuid(vfModule.getModelInvariantId())
600 vfModuleModelInfo.setModelCustomizationId(vfModule.getModelCustomizationId())
602 AAIResourceUri vfModuleUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(vfModule.getModelInvariantId()).modelVer(vfModule.getModelVersionId()))
604 Optional<ModelVer> vfModuleModelVerOpt = client.get(ModelVer.class, vfModuleUrl)
606 if (vfModuleModelVerOpt.isPresent()) {
607 vfModuleModelInfo.setModelVersionId(vfModuleModelVerOpt.get().getModelVersionId())
608 vfModuleModelInfo.setModelName(vfModuleModelVerOpt.get().getModelName())
609 vfModuleModelInfo.setModelVersion(vfModuleModelVerOpt.get().getModelVersion())
611 vfmodules.setModelInfo(vfModuleModelInfo)
613 vfmodules.setInstanceName(vfModule.getVfModuleName())
615 vfModuless.add(vfmodules)
623 * prepares VNF Model Info
625 * @param constituteVnf
628 ModelInfo prepareVNFModelInfo(DelegateExecution execution, GenericVnf constituteVnf) {
629 ModelInfo vnfModelInfo = new ModelInfo()
631 AAIResourcesClient client = getAAIClient()
633 vnfModelInfo.setModelInvariantUuid(constituteVnf.getModelInvariantId())
634 vnfModelInfo.setModelCustomizationId(constituteVnf.getModelCustomizationId())
635 vnfModelInfo.setModelInstanceName(constituteVnf.getVnfName())
637 AAIResourceUri vnfModelUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(constituteVnf.getModelInvariantId()).modelVer(constituteVnf.getModelVersionId()))
639 Optional<ModelVer> vnfModelVerOpt = client.get(ModelVer.class, vnfModelUrl)
641 if (vnfModelVerOpt.isPresent()) {
642 vnfModelInfo.setModelVersionId(vnfModelVerOpt.get().getModelVersionId())
643 vnfModelInfo.setModelName(vnfModelVerOpt.get().getModelName())
644 vnfModelInfo.setModelVersion(vnfModelVerOpt.get().getModelVersion())
651 List<Map<String, Object>> prepareInstanceParams(DelegateExecution execution) {
652 def currentNSSI = execution.getVariable("currentNSSI")
654 List<Map<String, Object>> instanceParams = new ArrayList<>()
655 Map<String, Object> instanceParamsMap = new HashMap<>()
658 List<String> snssais = (List<String>) currentNSSI['S-NSSAIs']
660 ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
662 String orchStatus = nssi.getOrchestrationStatus()
665 List<Map<String, String>> snssaiList = new ArrayList<>()
667 for(String snssai:snssais) {
668 Map<String, String> snssaisMap = new HashMap<>()
669 snssaisMap.put("snssai", snssai)
670 snssaisMap.put("status", orchStatus)
671 snssaiList.add(snssaisMap)
674 // Map<String, List<Map<String, String>>> supportedNssaiDetails = new HashMap<>()
675 // supportedNssaiDetails.put("sNssai", supportedNssaiDetails)
677 ObjectMapper mapper = new ObjectMapper()
679 String supportedNssaiDetailsStr = mapper.writeValueAsString(snssaiList)
682 instanceParamsMap.put("k8s-rb-profile-name", "default") // ???
683 instanceParamsMap.put("config-type", "day2") // ???
684 instanceParamsMap.put("supportedNssai", supportedNssaiDetailsStr)
685 instanceParams.add(instanceParamsMap)
687 return instanceParams
695 Resources prepareResources(DelegateExecution execution) {
696 def currentNSSI = execution.getVariable("currentNSSI")
698 Resources resources = new Resources()
701 List<Vnfs> vnfs = new ArrayList<>()
703 Vnfs vnf = new Vnfs()
706 LineOfBusiness lob = new LineOfBusiness()
707 lob.setLineOfBusinessName("VNF")
708 vnf.setLineOfBusiness(lob)
711 GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
712 vnf.setProductFamilyId(constituteVnf.getServiceId())
714 // Cloud configuration
715 vnf.setCloudConfiguration(prepareCloudConfiguration(execution))
718 vnf.setVfModules(prepareVfModules(execution, constituteVnf))
721 vnf.setModelInfo(prepareVNFModelInfo(execution, constituteVnf))
724 vnf.setInstanceName(constituteVnf.getVnfName())
727 vnf.setInstanceParams(prepareInstanceParams(execution))
732 resources.setVnfs(vnfs)
742 Service prepareService(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
743 Service service = new Service()
746 service.setModelInfo(prepareServiceModelInfo(networkServiceInstance, modelInfo))
748 service.setInstanceName(networkServiceInstance.getServiceInstanceName())
751 service.setResources(prepareResources(execution))
759 * Prepares request parameters
761 * @return RequestParameters
763 RequestParameters prepareRequestParameters(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
764 def currentNSSI = execution.getVariable("currentNSSI")
766 RequestParameters requestParameters = new RequestParameters()
768 ServiceSubscription serviceSubscription = (ServiceSubscription)currentNSSI['serviceSubscription']
770 if(serviceSubscription != null) {
771 requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
775 List<Map<String, Object>> userParams = new ArrayList<>()
777 Map<String, Object> userParam = new HashMap<>()
778 userParam.put("Homing_Solution", "none")
779 userParams.add(userParam)
782 Map<String, Object> serviceMap = new HashMap<>()
783 serviceMap.put("service", prepareService(execution, networkServiceInstance, modelInfo))
784 userParams.add(serviceMap)
785 requestParameters.setUserParams(userParams)
787 return requestParameters
792 * Prepare Owning Entity
794 * @return OwningEntity
796 OwningEntity prepareOwningEntity(DelegateExecution execution) {
797 def currentNSSI = execution.getVariable("currentNSSI")
799 AAIResourcesClient client = getAAIClient()
801 AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
803 OwningEntity owningEntity = new OwningEntity()
804 AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
805 Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
806 if (owningEntityRelationshipsOps.isPresent()) {
807 List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedUris(Types.OWNING_ENTITY)
809 if (!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
810 Optional<org.onap.aai.domain.yang.OwningEntity> owningEntityOpt = client.get(org.onap.aai.domain.yang.OwningEntity.class, owningEntityRelatedAAIUris.get(0)) // Many-To-One relation
811 if (owningEntityOpt.isPresent()) {
812 owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
813 owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
828 Project prepareProject(DelegateExecution execution) {
829 def currentNSSI = execution.getVariable("currentNSSI")
831 AAIResourcesClient client = getAAIClient()
833 Project project = new Project()
835 AAIResourceUri cloudRegionRelatedAAIUri = (AAIResourceUri)currentNSSI['cloudRegionRelatedAAIUri']
837 if (cloudRegionRelatedAAIUri != null) {
838 AAIResultWrapper wrapper = client.get(cloudRegionRelatedAAIUri)
839 Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
840 if (cloudRegionOps.isPresent()) {
841 List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedUris(Types.PROJECT)
842 if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
843 Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.Project.class, projectAAIUris.get(0))
844 if (projectOpt.isPresent()) {
845 project.setProjectName(projectOpt.get().getProjectName())
856 * Prepares RequestDetails object
860 String prepareRequestDetails(DelegateExecution execution) {
861 String errorCode = ""
862 String errorMessage = ""
865 RequestDetails requestDetails = new RequestDetails()
867 def currentNSSI = execution.getVariable("currentNSSI")
869 ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
873 ModelInfo modelInfo = prepareModelInfo(execution)
874 requestDetails.setModelInfo(modelInfo)
877 requestDetails.setSubscriberInfo(prepareSubscriberInfo(execution))
880 requestDetails.setRequestInfo(prepareRequestInfo(execution, networkServiceInstance))
882 // Request Parameters
883 requestDetails.setRequestParameters(prepareRequestParameters(execution, networkServiceInstance, modelInfo))
885 // Cloud configuration
886 requestDetails.setCloudConfiguration(prepareCloudConfiguration(execution))
889 requestDetails.setOwningEntity(prepareOwningEntity(execution))
892 requestDetails.setProject(prepareProject(execution))
894 ObjectMapper mapper = new ObjectMapper()
896 response = mapper.writeValueAsString(requestDetails)
899 String msg = "Exception in ${getPrefix()}.prepareRequestDetails. " + any.getCause()
903 " \"errorCode\": \"7000\",\n" +
904 " \"errorMessage\": \"${msg}\"\n" +
913 String getAuthHeader(DelegateExecution execution, String basicAuthValue, String msokey) {
915 String errorCode = ""
916 String errorMessage = ""
918 LOGGER.debug("Obtained BasicAuth username and password for OOF: " + basicAuthValue)
920 response = utils.getBasicAuth(basicAuthValue, msokey)
921 } catch (Exception ex) {
922 LOGGER.error("Unable to encode username and password string: ", ex)
925 errorMessage = "Internal Error - Unable to encode username and password string"
928 " \"errorCode\": \"${errorCode}\",\n" +
929 " \"errorMessage\": \"${errorMessage}\"\n" +
937 String encryptBasicAuth(String basicAuth, String msoKey) {
938 return utils.encrypt(basicAuth, msoKey)
943 * Removes Slice Profile association with NSSI
946 void removeSPAssociationWithNSSI(DelegateExecution execution) {
947 LOGGER.trace("${getPrefix()} Start removeSPAssociationWithNSSI")
949 AAIResourcesClient client = getAAIClient()
951 def currentNSSI = execution.getVariable("currentNSSI")
953 ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
955 String nssiId = currentNSSI['nssiId']
956 AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
958 List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
960 String currentSNSSAI = currentNSSI['S-NSSAI']
962 associatedProfiles.removeIf({ associatedProfile -> (associatedProfile.getSNssai().equals(currentSNSSAI)) })
965 getAAIClient().update(nssiUri, nssi)
967 exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile association with NSSI update call: " + e.getMessage())
970 LOGGER.trace("${getPrefix()} Exit removeSPAssociationWithNSSI")
975 * Deletes Slice Profile Instance
978 void deleteSliceProfileInstance(DelegateExecution execution) {
979 LOGGER.trace("${getPrefix()} Start deleteSliceProfileInstance")
981 AAIResourcesClient client = getAAIClient()
983 def currentNSSI = execution.getVariable("currentNSSI")
985 SliceProfile sliceProfileContainsSNSSAI = (SliceProfile)currentNSSI['sliceProfileS-NSSAI']
987 String globalSubscriberId = execution.getVariable("globalSubscriberId")
988 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
989 String nssiId = currentNSSI['nssiId']
991 // global-customer-id, service-type, service-instance-id, profile-id
992 AAIResourceUri sliceProfileUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(nssiId).sliceProfile(sliceProfileContainsSNSSAI.getProfileId()))
995 client.delete(sliceProfileUri)
997 exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
1000 LOGGER.trace("${getPrefix()} Exit deleteSliceProfileInstance")
1005 * Prepares update resource operation status
1008 void prepareUpdateResourceOperationStatus(DelegateExecution execution) {
1009 LOGGER.trace("${getPrefix()} Start updateServiceOperationStatus")
1011 def currentNSSI = execution.getVariable("currentNSSI")
1013 //Prepare Update Status for PUT failure and success
1014 String isTimeOutVar = execution.getVariable("isTimeOut")
1015 if(!isBlank(isTimeOutVar) && isTimeOutVar.equals("YES")) {
1016 LOGGER.error("TIMEOUT - SO PUT Failure")
1017 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "SO PUT Failure")
1019 execution.setVariable("progress", "100")
1020 execution.setVariable("status", "finished")
1021 execution.setVariable("operationContent", "${getAction()} Core NSSI successful.")
1024 setResourceOperationStatus(execution, "finished", "100", "Core NSSI ${getAction()} successful")
1026 LOGGER.trace("${getPrefix()} Exit updateServiceOperationStatus")
1031 * Prepares ResourceOperation status
1033 * @param operationType
1035 void setResourceOperationStatus(DelegateExecution execution, String status, String progress, String statusDesc) {
1036 LOGGER.trace("${getPrefix()} Start setResourceOperationStatus")
1038 def currentNSSI = execution.getVariable("currentNSSI")
1040 String serviceId = currentNSSI['nssiId']
1041 String jobId = execution.getVariable("jobId")
1042 String nsiId = currentNSSI['nsiId']
1043 String operationType = execution.getVariable("operationType")
1045 ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
1046 resourceOperationStatus.setServiceId(serviceId)
1047 resourceOperationStatus.setOperationId(jobId)
1048 resourceOperationStatus.setResourceTemplateUUID(nsiId)
1049 resourceOperationStatus.setOperType(operationType)
1050 resourceOperationStatus.setStatus(status)
1051 resourceOperationStatus.setProgress(progress)
1052 resourceOperationStatus.setStatusDescription(statusDesc)
1053 requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
1055 LOGGER.trace("${getPrefix()} Exit setResourceOperationStatus")
1060 * Prepares failed operation status update
1063 void prepareFailedOperationStatusUpdate(DelegateExecution execution) {
1064 LOGGER.trace("${getPrefix()} Start prepareFailedOperationStatusUpdate")
1066 setResourceOperationStatus(execution, "failed", "0", "Core NSSI ${getAction()} Failed")
1068 LOGGER.trace("${getPrefix()} Exit prepareFailedOperationStatusUpdate")
1073 * Gets progress status of ServiceInstance PUT operation
1076 public void getPUTServiceInstanceProgress(DelegateExecution execution) {
1077 LOGGER.trace("${getPrefix()} Start getPUTServiceInstanceProgress")
1079 def currentNSSI = execution.getVariable("currentNSSI")
1081 String url = currentNSSI['putServiceInstanceURL']
1083 getProgress(execution, url, "putStatus")
1085 LOGGER.trace("${getPrefix()} Exit getPUTServiceInstanceProgress")
1089 void getProgress(DelegateExecution execution, String url, String statusVariableName) {
1093 ExternalAPIUtil externalAPIUtil = getExternalAPIUtilFactory().create()
1094 Response response = externalAPIUtil.executeExternalAPIGetCall(execution, url)
1095 int responseCode = response.getStatus()
1096 execution.setVariable("GetServiceOrderResponseCode", responseCode)
1097 LOGGER.debug("Get ServiceOrder response code is: " + responseCode)
1099 String extApiResponse = response.readEntity(String.class)
1100 JSONObject responseObj = new JSONObject(extApiResponse)
1101 execution.setVariable("GetServiceOrderResponse", extApiResponse)
1102 LOGGER.debug("Create response body is: " + extApiResponse)
1103 //Process Response //200 OK 201 CREATED 202 ACCEPTED
1104 if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
1106 LOGGER.debug("Get Create ServiceOrder Received a Good Response")
1107 String orderState = responseObj.get("state")
1108 if("REJECTED".equalsIgnoreCase(orderState)) {
1109 prepareFailedOperationStatusUpdate(execution)
1113 JSONArray items = responseObj.getJSONArray("orderItem")
1114 JSONObject item = items.get(0)
1115 JSONObject service = item.get("service")
1116 String networkServiceId = service.get("id")
1117 if (networkServiceId == null || networkServiceId.equals("null")) {
1118 prepareFailedOperationStatusUpdate(execution)
1122 execution.setVariable("networkServiceId", networkServiceId)
1123 String serviceOrderState = item.get("state")
1124 execution.setVariable("ServiceOrderState", serviceOrderState)
1125 // Get serviceOrder State and process progress
1126 if("ACKNOWLEDGED".equalsIgnoreCase(serviceOrderState)) {
1127 execution.setVariable(statusVariableName, "processing")
1129 else if("INPROGRESS".equalsIgnoreCase(serviceOrderState)) {
1130 execution.setVariable(statusVariableName, "processing")
1132 else if("COMPLETED".equalsIgnoreCase(serviceOrderState)) {
1133 execution.setVariable(statusVariableName, "completed")
1135 else if("FAILED".equalsIgnoreCase(serviceOrderState)) {
1136 msg = "ServiceOrder failed"
1137 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
1140 msg = "ServiceOrder failed"
1141 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
1145 msg = "Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode
1146 prepareFailedOperationStatusUpdate(execution)
1149 }catch(Exception e){
1150 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e.getMessage())
1161 void timeDelay(DelegateExecution execution) {
1162 LOGGER.trace("${getPrefix()} Start timeDelay")
1165 LOGGER.debug("${getPrefix()} timeDelay going to sleep for 5 sec")
1169 LOGGER.debug("${getPrefix()} ::: timeDelay wakeup after 5 sec")
1170 } catch(InterruptedException e) {
1171 LOGGER.error("${getPrefix()} ::: timeDelay exception" + e)
1174 LOGGER.trace("${getPrefix()} Exit timeDelay")
1179 * Returns AAI client
1180 * @return AAI client
1182 AAIResourcesClient getAAIClient() {
1183 return new AAIResourcesClient()
1187 ExternalAPIUtilFactory getExternalAPIUtilFactory() {
1188 return new ExternalAPIUtilFactory()
1192 String getPrefix() {
1196 String getAction() {