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 List<SliceProfile> associatedProfiles = new ArrayList<>()
251 AAIResourcesClient client = getAAIClient()
253 def currentNSSI = execution.getVariable("currentNSSI")
255 ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
257 String nssiId = currentNSSI['nssiId']
260 AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
261 AAIResultWrapper nssiWrapper = client.get(nssiUri)
262 Optional<Relationships> nssiRelationships = nssiWrapper.getRelationships()
264 if (nssiRelationships.isPresent()) {
266 for (AAIResourceUri allottedResourceUri : nssiRelationships.get().getRelatedUris(Types.ALLOTTED_RESOURCE)) {
267 AAIResultWrapper arWrapper = client.get(allottedResourceUri)
268 Optional<Relationships> arRelationships = arWrapper.getRelationships()
270 boolean isFound = false
271 if(arRelationships.isPresent()) {
272 // Slice Profile Instance
273 for (AAIResourceUri sliceProfileInstanceUri : arRelationships.get().getRelatedUris(Types.SERVICE_INSTANCE)) {
274 Optional<ServiceInstance> sliceProfileInstanceOpt = client.get(ServiceInstance.class, sliceProfileInstanceUri)
276 if (sliceProfileInstanceOpt.isPresent()) {
277 ServiceInstance sliceProfileInstance = sliceProfileInstanceOpt.get()
278 if(sliceProfileInstance.getServiceRole().equals("slice-profile-instance")) { // Service instance as a Slice Profile Instance
279 associatedProfiles = sliceProfileInstance.getSliceProfiles()?.getSliceProfile()
281 currentNSSI['sliceProfileInstanceUri'] = sliceProfileInstanceUri
284 break // Should be only one
288 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No Slice Profile Instance found")
293 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No relationships found for Allotted Resource")
302 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No relationships found for nssi id = " + nssiId)
305 if(associatedProfiles.isEmpty()) {
306 String msg = String.format("No associated profiles found for NSSI %s in AAI", nssi.getServiceInstanceId())
308 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
311 currentNSSI['associatedProfiles'] = associatedProfiles
314 LOGGER.trace("${getPrefix()} Exit getNSSIAssociatedProfiles")
319 * Calculates a final list of S-NSSAI
322 void calculateSNSSAI(DelegateExecution execution) {
323 LOGGER.trace("${getPrefix()} Start calculateSNSSAI")
325 def currentNSSI = execution.getVariable("currentNSSI")
327 List<SliceProfile> associatedProfiles = (List<SliceProfile>)currentNSSI['associatedProfiles']
329 String currentSNSSAI = currentNSSI['S-NSSAI']
331 List<String> snssais = new ArrayList<>()
333 String isCreateSliceProfileInstanceVar = execution.getVariable("isCreateSliceProfileInstance" ) // Not exist in case of Deallocate
335 boolean isCreateSliceProfileInstance = Boolean.parseBoolean(isCreateSliceProfileInstanceVar)
337 if(isCreateSliceProfileInstance) { // Slice Profile Instance has to be created
338 for (SliceProfile associatedProfile : associatedProfiles) {
339 snssais.add(associatedProfile.getSNssai())
342 snssais.add(currentSNSSAI)
344 else { // Slice profile instance has to be deleted
345 for (SliceProfile associatedProfile : associatedProfiles) {
346 if (!associatedProfile.getSNssai().equals(currentSNSSAI)) { // not current S-NSSAI
347 snssais.add(associatedProfile.getSNssai())
349 currentNSSI['sliceProfileS-NSSAI'] = associatedProfile
354 currentNSSI['S-NSSAIs'] = snssais
356 LOGGER.trace("${getPrefix()} Exit calculateSNSSAI")
361 * Invoke PUT Service Instance API
364 void invokePUTServiceInstance(DelegateExecution execution) {
365 LOGGER.trace("${getPrefix()} Start invokePUTServiceInstance")
367 def currentNSSI = execution.getVariable("currentNSSI")
370 //url:/onap/so/infra/serviceInstantiation/v7/serviceInstances/{serviceInstanceId}"
371 def nsmfЕndPoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) // ???
373 ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
375 String url = String.format("${nsmfЕndPoint}/serviceInstantiation/v7/serviceInstances/%s", networkServiceInstance.getServiceInstanceId())
377 currentNSSI['putServiceInstanceURL'] = url
379 String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
380 String basicAuth = UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
383 String basicAuthValue = encryptBasicAuth(basicAuth, msoKey) //utils.encrypt(basicAuth, msoKey)
384 String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey) //utils.getBasicAuth(basicAuthValue, msoKey)
386 String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
387 if(errorCode == null || errorCode.isEmpty()) { // No error
388 authHeader = responseAuthHeader
391 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
394 def requestDetails = ""
395 String prepareRequestDetailsResponse = prepareRequestDetails(execution)
396 errorCode = jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorCode")
397 if(errorCode == null || errorCode.isEmpty()) { // No error
398 requestDetails = prepareRequestDetailsResponse
401 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorMessage"))
404 String callPUTServiceInstanceResponse = callPUTServiceInstance(url, authHeader, requestDetails)
405 String putServiceInstanceResponse = ""
407 if(errorCode == null || errorCode.isEmpty()) { // No error
408 putServiceInstanceResponse = callPUTServiceInstanceResponse
411 LOGGER.error(jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
412 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
416 String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
418 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
421 LOGGER.trace("${getPrefix()} Exit invokePUTServiceInstance")
425 String callPUTServiceInstance(String url, String authHeader, String requestDetailsStr) {
426 String errorCode = ""
427 String errorMessage = ""
431 HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.EXTERNAL)
432 httpClient.addAdditionalHeader("Authorization", authHeader)
433 httpClient.addAdditionalHeader("Accept", "application/json")
435 Response httpResponse = httpClient.put(requestDetailsStr) // check http code ???
438 if (httpResponse.hasEntity()) {
439 response = httpResponse.readEntity(String.class)
443 errorMessage = "No response received."
446 " \"errorCode\": \"${errorCode}\",\n" +
447 " \"errorMessage\": \"${errorMessage}\"\n" +
452 String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
456 " \"errorCode\": \"7000\",\n" +
457 " \"errorMessage\": \"${msg}\"\n" +
470 * @param requestDetails
473 ModelInfo prepareModelInfo(DelegateExecution execution) {
475 def currentNSSI = execution.getVariable("currentNSSI")
476 ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
478 ModelInfo modelInfo = new ModelInfo()
480 modelInfo.setModelType(ModelType.service)
481 modelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
483 AAIResourcesClient client = getAAIClient()
485 AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(networkServiceInstance.getModelInvariantId()).modelVer(networkServiceInstance.getModelVersionId()))
486 Optional<ModelVer> modelVerOpt = client.get(ModelVer.class, modelVerUrl)
488 if (modelVerOpt.isPresent()) {
489 modelInfo.setModelVersionId(modelVerOpt.get().getModelVersionId())
490 modelInfo.setModelName(modelVerOpt.get().getModelName())
491 modelInfo.setModelVersion(modelVerOpt.get().getModelVersion())
499 * Prepares subscriber info
501 * @return SubscriberInfo
503 SubscriberInfo prepareSubscriberInfo(DelegateExecution execution) {
504 def currentNSSI = execution.getVariable("currentNSSI")
506 String globalSubscriberId = execution.getVariable("globalSubscriberId")
508 String subscriberName = execution.getVariable("subscriberName")
510 SubscriberInfo subscriberInfo = new SubscriberInfo()
511 subscriberInfo.setGlobalSubscriberId(globalSubscriberId)
512 subscriberInfo.setSubscriberName(subscriberName)
515 AAIResourcesClient client = getAAIClient()
517 Customer customer = null
519 AAIResourceUri networkServiceInstanceUri = currentNSSI['networkServiceInstanceUri']
520 AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
521 Optional<Relationships> serviceSubscriptionRelationshipsOps = wrapper.getRelationships()
522 if(serviceSubscriptionRelationshipsOps.isPresent()) {
523 List<AAIResourceUri> serviceSubscriptionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedUris(Types.SERVICE_SUBSCRIPTION)
524 if(!(serviceSubscriptionRelatedAAIUris == null || serviceSubscriptionRelatedAAIUris.isEmpty())) {
525 AAIResourceUri serviceSubscriptionUri = serviceSubscriptionRelatedAAIUris.get(0) // Many-To-One relation
526 Optional<ServiceSubscription> serviceSubscriptionOpt = client.get(ServiceSubscription.class, serviceSubscriptionUri)
528 if(serviceSubscriptionOpt.isPresent()) {
529 currentNSSI['serviceSubscription'] = serviceSubscriptionOpt.get()
532 wrapper = client.get(serviceSubscriptionUri)
533 Optional<Relationships> customerRelationshipsOps = wrapper.getRelationships()
534 if(customerRelationshipsOps.isPresent()) {
535 List<AAIResourceUri> customerRelatedAAIUris = customerRelationshipsOps.get().getRelatedUris(Types.CUSTOMER)
536 if(!(customerRelatedAAIUris == null || customerRelatedAAIUris.isEmpty())) {
537 Optional<Customer> customerOpt = client.get(Customer.class, customerRelatedAAIUris.get(0)) // Many-To-One relation
538 if(customerOpt.isPresent()) {
539 customer = customerOpt.get()
540 subscriberInfo.setSubscriberName(customer.getSubscriberName())
548 return subscriberInfo
553 * Prepares Request Info
555 * @return RequestInfo
557 RequestInfo prepareRequestInfo(DelegateExecution execution, ServiceInstance networkServiceInstance) {
558 def currentNSSI = execution.getVariable("currentNSSI")
560 String productFamilyId = execution.getVariable("productFamilyId")
562 RequestInfo requestInfo = new RequestInfo()
564 requestInfo.setInstanceName(networkServiceInstance.getServiceInstanceName())
565 requestInfo.setSource("VID")
566 requestInfo.setProductFamilyId(productFamilyId)
567 requestInfo.setRequestorId("NBI")
574 * Prepares Model Info
575 * @param networkServiceInstance
579 ModelInfo prepareServiceModelInfo(ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
581 ModelInfo serviceModelInfo = new ModelInfo()
582 serviceModelInfo.setModelType(ModelType.service)
583 serviceModelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
585 serviceModelInfo.setModelVersionId(modelInfo.getModelVersionId())
586 serviceModelInfo.setModelName(modelInfo.getModelName())
587 serviceModelInfo.setModelVersion(modelInfo.getModelVersion())
589 return serviceModelInfo
594 * Prepares Cloud configuration
596 * @return CloudConfiguration
598 CloudConfiguration prepareCloudConfiguration(DelegateExecution execution) {
599 def currentNSSI = execution.getVariable("currentNSSI")
601 CloudConfiguration cloudConfiguration = new CloudConfiguration()
603 AAIResourcesClient client = getAAIClient()
605 AAIResourceUri constituteVnfUri = currentNSSI['constituteVnfUri']
606 AAIResultWrapper wrapper = client.get(constituteVnfUri)
607 Optional<Relationships> cloudRegionRelationshipsOps = wrapper.getRelationships()
609 if(cloudRegionRelationshipsOps.isPresent()) {
610 List<AAIResourceUri> cloudRegionRelatedAAIUris = cloudRegionRelationshipsOps.get().getRelatedUris(Types.CLOUD_REGION)
611 if (!(cloudRegionRelatedAAIUris == null || cloudRegionRelatedAAIUris.isEmpty())) {
612 AAIResourceUri cloudRegionRelatedAAIUri = cloudRegionRelatedAAIUris.get(0)
613 currentNSSI['cloudRegionRelatedAAIUri'] = cloudRegionRelatedAAIUri
615 Optional<CloudRegion> cloudRegionrOpt = client.get(CloudRegion.class, cloudRegionRelatedAAIUris.get(0))
616 CloudRegion cloudRegion = null
617 if (cloudRegionrOpt.isPresent()) {
618 cloudRegion = cloudRegionrOpt.get()
619 cloudConfiguration.setLcpCloudRegionId(cloudRegion.getCloudRegionId())
620 for (Tenant tenant : cloudRegion.getTenants().getTenant()) {
621 cloudConfiguration.setTenantId(tenant.getTenantId())
622 break // only one is required
625 cloudConfiguration.setCloudOwner(cloudRegion.getCloudOwner())
630 return cloudConfiguration
635 * Prepares a list of VF Modules
637 * @param constituteVnf
638 * @return List<VfModules>
640 List<org.onap.so.serviceinstancebeans.VfModules> prepareVfModules(DelegateExecution execution, GenericVnf constituteVnf) {
642 AAIResourcesClient client = getAAIClient()
644 List<org.onap.so.serviceinstancebeans.VfModules> vfModuless = new ArrayList<>()
645 for (VfModule vfModule : constituteVnf.getVfModules().getVfModule()) {
646 org.onap.so.serviceinstancebeans.VfModules vfmodules = new org.onap.so.serviceinstancebeans.VfModules()
648 ModelInfo vfModuleModelInfo = new ModelInfo()
649 vfModuleModelInfo.setModelInvariantUuid(vfModule.getModelInvariantId())
650 vfModuleModelInfo.setModelCustomizationId(vfModule.getModelCustomizationId())
652 AAIResourceUri vfModuleUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(vfModule.getModelInvariantId()).modelVer(vfModule.getModelVersionId()))
654 Optional<ModelVer> vfModuleModelVerOpt = client.get(ModelVer.class, vfModuleUrl)
656 if (vfModuleModelVerOpt.isPresent()) {
657 vfModuleModelInfo.setModelVersionId(vfModuleModelVerOpt.get().getModelVersionId())
658 vfModuleModelInfo.setModelName(vfModuleModelVerOpt.get().getModelName())
659 vfModuleModelInfo.setModelVersion(vfModuleModelVerOpt.get().getModelVersion())
661 vfmodules.setModelInfo(vfModuleModelInfo)
663 vfmodules.setInstanceName(vfModule.getVfModuleName())
665 vfModuless.add(vfmodules)
673 * prepares VNF Model Info
675 * @param constituteVnf
678 ModelInfo prepareVNFModelInfo(DelegateExecution execution, GenericVnf constituteVnf) {
679 ModelInfo vnfModelInfo = new ModelInfo()
681 AAIResourcesClient client = getAAIClient()
683 vnfModelInfo.setModelInvariantUuid(constituteVnf.getModelInvariantId())
684 vnfModelInfo.setModelCustomizationId(constituteVnf.getModelCustomizationId())
685 vnfModelInfo.setModelInstanceName(constituteVnf.getVnfName())
687 AAIResourceUri vnfModelUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(constituteVnf.getModelInvariantId()).modelVer(constituteVnf.getModelVersionId()))
689 Optional<ModelVer> vnfModelVerOpt = client.get(ModelVer.class, vnfModelUrl)
691 if (vnfModelVerOpt.isPresent()) {
692 vnfModelInfo.setModelVersionId(vnfModelVerOpt.get().getModelVersionId())
693 vnfModelInfo.setModelName(vnfModelVerOpt.get().getModelName())
694 vnfModelInfo.setModelVersion(vnfModelVerOpt.get().getModelVersion())
701 List<Map<String, Object>> prepareInstanceParams(DelegateExecution execution) {
702 def currentNSSI = execution.getVariable("currentNSSI")
704 List<Map<String, Object>> instanceParams = new ArrayList<>()
705 Map<String, Object> instanceParamsMap = new HashMap<>()
708 List<String> snssais = (List<String>) currentNSSI['S-NSSAIs']
710 ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
712 String orchStatus = nssi.getOrchestrationStatus()
715 List<Map<String, String>> snssaiList = new ArrayList<>()
717 for(String snssai:snssais) {
718 Map<String, String> snssaisMap = new HashMap<>()
719 snssaisMap.put("snssai", snssai)
720 snssaisMap.put("status", orchStatus)
721 snssaiList.add(snssaisMap)
724 // Map<String, List<Map<String, String>>> supportedNssaiDetails = new HashMap<>()
725 // supportedNssaiDetails.put("sNssai", supportedNssaiDetails)
727 ObjectMapper mapper = new ObjectMapper()
729 String supportedNssaiDetailsStr = mapper.writeValueAsString(snssaiList)
732 instanceParamsMap.put("k8s-rb-profile-name", "default") // ???
733 instanceParamsMap.put("config-type", "day2") // ???
734 instanceParamsMap.put("supportedNssai", supportedNssaiDetailsStr)
735 instanceParams.add(instanceParamsMap)
737 return instanceParams
745 Resources prepareResources(DelegateExecution execution) {
746 def currentNSSI = execution.getVariable("currentNSSI")
748 Resources resources = new Resources()
751 List<Vnfs> vnfs = new ArrayList<>()
753 Vnfs vnf = new Vnfs()
756 org.onap.so.serviceinstancebeans.LineOfBusiness lob = new org.onap.so.serviceinstancebeans.LineOfBusiness()
757 lob.setLineOfBusinessName("VNF")
758 vnf.setLineOfBusiness(lob)
761 GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
762 vnf.setProductFamilyId(constituteVnf.getServiceId())
764 // Cloud configuration
765 vnf.setCloudConfiguration(prepareCloudConfiguration(execution))
768 vnf.setVfModules(prepareVfModules(execution, constituteVnf))
771 vnf.setModelInfo(prepareVNFModelInfo(execution, constituteVnf))
774 vnf.setInstanceName(constituteVnf.getVnfName())
777 vnf.setInstanceParams(prepareInstanceParams(execution))
782 resources.setVnfs(vnfs)
792 org.onap.so.serviceinstancebeans.Service prepareService(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
793 org.onap.so.serviceinstancebeans.Service service = new org.onap.so.serviceinstancebeans.Service()
796 service.setModelInfo(prepareServiceModelInfo(networkServiceInstance, modelInfo))
798 service.setInstanceName(networkServiceInstance.getServiceInstanceName())
801 service.setResources(prepareResources(execution))
809 * Prepares request parameters
811 * @return RequestParameters
813 RequestParameters prepareRequestParameters(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
814 def currentNSSI = execution.getVariable("currentNSSI")
816 RequestParameters requestParameters = new RequestParameters()
818 ServiceSubscription serviceSubscription = (ServiceSubscription)currentNSSI['serviceSubscription']
820 if(serviceSubscription != null) {
821 requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
825 List<Map<String, Object>> userParams = new ArrayList<>()
827 Map<String, Object> userParam = new HashMap<>()
828 userParam.put("Homing_Solution", "none")
829 userParams.add(userParam)
832 Map<String, Object> serviceMap = new HashMap<>()
833 serviceMap.put("service", prepareService(execution, networkServiceInstance, modelInfo))
834 userParams.add(serviceMap)
835 requestParameters.setUserParams(userParams)
837 return requestParameters
842 * Prepare Owning Entity
844 * @return OwningEntity
846 org.onap.so.serviceinstancebeans.OwningEntity prepareOwningEntity(DelegateExecution execution) {
847 def currentNSSI = execution.getVariable("currentNSSI")
849 AAIResourcesClient client = getAAIClient()
851 AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
853 org.onap.so.serviceinstancebeans.OwningEntity owningEntity = new org.onap.so.serviceinstancebeans.OwningEntity()
854 AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
855 Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
856 if (owningEntityRelationshipsOps.isPresent()) {
857 List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedUris(Types.OWNING_ENTITY)
859 if (!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
860 Optional<org.onap.aai.domain.yang.OwningEntity> owningEntityOpt = client.get(org.onap.aai.domain.yang.v19.OwningEntity.class, owningEntityRelatedAAIUris.get(0)) // Many-To-One relation
861 if (owningEntityOpt.isPresent()) {
862 owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
863 owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
878 org.onap.so.serviceinstancebeans.Project prepareProject(DelegateExecution execution) {
879 def currentNSSI = execution.getVariable("currentNSSI")
881 AAIResourcesClient client = getAAIClient()
883 org.onap.so.serviceinstancebeans.Project project = new org.onap.so.serviceinstancebeans.Project()
885 AAIResourceUri cloudRegionRelatedAAIUri = (AAIResourceUri)currentNSSI['cloudRegionRelatedAAIUri']
887 if (cloudRegionRelatedAAIUri != null) {
888 AAIResultWrapper wrapper = client.get(cloudRegionRelatedAAIUri)
889 Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
890 if (cloudRegionOps.isPresent()) {
891 List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedUris(Types.PROJECT)
892 if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
893 Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.v19.Project.class, projectAAIUris.get(0))
894 if (projectOpt.isPresent()) {
895 project.setProjectName(projectOpt.get().getProjectName())
906 * Prepares RequestDetails object
910 String prepareRequestDetails(DelegateExecution execution) {
911 String errorCode = ""
912 String errorMessage = ""
915 RequestDetails requestDetails = new RequestDetails()
917 def currentNSSI = execution.getVariable("currentNSSI")
919 ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
923 ModelInfo modelInfo = prepareModelInfo(execution)
924 requestDetails.setModelInfo(modelInfo)
927 requestDetails.setSubscriberInfo(prepareSubscriberInfo(execution))
930 requestDetails.setRequestInfo(prepareRequestInfo(execution, networkServiceInstance))
932 // Request Parameters
933 requestDetails.setRequestParameters(prepareRequestParameters(execution, networkServiceInstance, modelInfo))
935 // Cloud configuration
936 requestDetails.setCloudConfiguration(prepareCloudConfiguration(execution))
939 requestDetails.setOwningEntity(prepareOwningEntity(execution))
942 requestDetails.setProject(prepareProject(execution))
944 ObjectMapper mapper = new ObjectMapper()
946 response = mapper.writeValueAsString(requestDetails)
949 String msg = "Exception in ${getPrefix()}.prepareRequestDetails. " + any.getCause()
953 " \"errorCode\": \"7000\",\n" +
954 " \"errorMessage\": \"${msg}\"\n" +
963 String getAuthHeader(DelegateExecution execution, String basicAuthValue, String msokey) {
965 String errorCode = ""
966 String errorMessage = ""
968 LOGGER.debug("Obtained BasicAuth username and password for OOF: " + basicAuthValue)
970 response = utils.getBasicAuth(basicAuthValue, msokey)
971 } catch (Exception ex) {
972 LOGGER.error("Unable to encode username and password string: ", ex)
975 errorMessage = "Internal Error - Unable to encode username and password string"
978 " \"errorCode\": \"${errorCode}\",\n" +
979 " \"errorMessage\": \"${errorMessage}\"\n" +
987 String encryptBasicAuth(String basicAuth, String msoKey) {
988 return utils.encrypt(basicAuth, msoKey)
993 * Removes Slice Profile association with NSSI
996 void removeSPAssociationWithNSSI(DelegateExecution execution) {
997 LOGGER.trace("${getPrefix()} Start removeSPAssociationWithNSSI")
999 AAIResourcesClient client = getAAIClient()
1001 def currentNSSI = execution.getVariable("currentNSSI")
1003 String nssiId = currentNSSI['nssiId']
1004 AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
1006 AAIResourceUri sliceProfileInstanceUri = (AAIResourceUri)currentNSSI['sliceProfileInstanceUri']
1008 Optional<ServiceInstance> sliceProfileInstanceOpt = client.get(ServiceInstance.class, sliceProfileInstanceUri)
1009 if (sliceProfileInstanceOpt.isPresent()) {
1010 ServiceInstance sliceProfileInstance = sliceProfileInstanceOpt.get()
1012 List<SliceProfile> associatedProfiles = sliceProfileInstance.getSliceProfiles()?.getSliceProfile()
1014 String currentSNSSAI = currentNSSI['S-NSSAI']
1016 if(!(associatedProfiles == null || associatedProfiles.isEmpty())) {
1017 // Removes slice profile which contains given S-NSSAI and updates Slice Profile Instance
1018 associatedProfiles.removeIf({ associatedProfile -> (associatedProfile.getSNssai().equals(currentSNSSAI)) })
1021 client.update(sliceProfileInstanceUri, sliceProfileInstance)
1023 currentNSSI['sliceProfileInstance'] = sliceProfileInstance
1024 } catch (Exception e) {
1025 exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile association with NSSI update call: " + e.getMessage())
1029 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No slice profiles found")
1034 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No slice profile instance found")
1037 // Removes SLice Profile Instance association with NSSI
1039 client.disconnect(nssiUri, sliceProfileInstanceUri)
1041 catch (Exception e) {
1042 exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance association with NSSI dosconnect call: " + e.getMessage())
1046 LOGGER.trace("${getPrefix()} Exit removeSPAssociationWithNSSI")
1051 * Deletes Slice Profile Instance
1054 void deleteSliceProfileInstance(DelegateExecution execution) {
1055 LOGGER.trace("${getPrefix()} Start deleteSliceProfileInstance")
1057 AAIResourcesClient client = getAAIClient()
1059 def currentNSSI = execution.getVariable("currentNSSI")
1061 AAIResourceUri sliceProfileInstanceURI = (AAIResourceUri)currentNSSI['sliceProfileInstanceUri']
1064 client.delete(sliceProfileInstanceURI)
1065 }catch(Exception e){
1066 exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
1069 LOGGER.trace("${getPrefix()} Exit deleteSliceProfileInstance")
1074 * Prepares update resource operation status
1077 void prepareUpdateResourceOperationStatus(DelegateExecution execution) {
1078 LOGGER.trace("${getPrefix()} Start updateServiceOperationStatus")
1080 def currentNSSI = execution.getVariable("currentNSSI")
1082 //Prepare Update Status for PUT failure and success
1083 String isTimeOutVar = execution.getVariable("isTimeOut")
1084 if(!isBlank(isTimeOutVar) && isTimeOutVar.equals("YES")) {
1085 LOGGER.error("TIMEOUT - SO PUT Failure")
1086 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "SO PUT Failure")
1088 execution.setVariable("progress", "100")
1089 execution.setVariable("status", "finished")
1090 execution.setVariable("operationContent", "${getAction()} Core NSSI successful.")
1093 setResourceOperationStatus(execution, "finished", "100", "Core NSSI ${getAction()} successful")
1095 LOGGER.trace("${getPrefix()} Exit updateServiceOperationStatus")
1100 * Prepares ResourceOperation status
1102 * @param operationType
1104 void setResourceOperationStatus(DelegateExecution execution, String status, String progress, String statusDesc) {
1105 LOGGER.trace("${getPrefix()} Start setResourceOperationStatus")
1107 def currentNSSI = execution.getVariable("currentNSSI")
1109 String serviceId = currentNSSI['nssiId']
1110 String jobId = execution.getVariable("jobId")
1111 String nsiId = currentNSSI['nsiId']
1112 String operationType = execution.getVariable("operationType")
1114 ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
1115 resourceOperationStatus.setServiceId(serviceId)
1116 resourceOperationStatus.setOperationId(jobId)
1117 resourceOperationStatus.setResourceTemplateUUID(nsiId)
1118 resourceOperationStatus.setOperType(operationType)
1119 resourceOperationStatus.setStatus(status)
1120 resourceOperationStatus.setProgress(progress)
1121 resourceOperationStatus.setStatusDescription(statusDesc)
1122 requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
1124 LOGGER.trace("${getPrefix()} Exit setResourceOperationStatus")
1129 * Prepares failed operation status update
1132 void prepareFailedOperationStatusUpdate(DelegateExecution execution) {
1133 LOGGER.trace("${getPrefix()} Start prepareFailedOperationStatusUpdate")
1135 setResourceOperationStatus(execution, "failed", "0", "Core NSSI ${getAction()} Failed")
1137 LOGGER.trace("${getPrefix()} Exit prepareFailedOperationStatusUpdate")
1142 * Gets progress status of ServiceInstance PUT operation
1145 public void getPUTServiceInstanceProgress(DelegateExecution execution) {
1146 LOGGER.trace("${getPrefix()} Start getPUTServiceInstanceProgress")
1148 def currentNSSI = execution.getVariable("currentNSSI")
1150 String url = currentNSSI['putServiceInstanceURL']
1152 getProgress(execution, url, "putStatus")
1154 LOGGER.trace("${getPrefix()} Exit getPUTServiceInstanceProgress")
1158 void getProgress(DelegateExecution execution, String url, String statusVariableName) {
1162 ExternalAPIUtil externalAPIUtil = getExternalAPIUtilFactory().create()
1163 Response response = externalAPIUtil.executeExternalAPIGetCall(execution, url)
1164 int responseCode = response.getStatus()
1165 execution.setVariable("GetServiceOrderResponseCode", responseCode)
1166 LOGGER.debug("Get ServiceOrder response code is: " + responseCode)
1168 String extApiResponse = response.readEntity(String.class)
1169 JSONObject responseObj = new JSONObject(extApiResponse)
1170 execution.setVariable("GetServiceOrderResponse", extApiResponse)
1171 LOGGER.debug("Create response body is: " + extApiResponse)
1172 //Process Response //200 OK 201 CREATED 202 ACCEPTED
1173 if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
1175 LOGGER.debug("Get Create ServiceOrder Received a Good Response")
1176 String orderState = responseObj.get("state")
1177 if("REJECTED".equalsIgnoreCase(orderState)) {
1178 prepareFailedOperationStatusUpdate(execution)
1182 JSONArray items = responseObj.getJSONArray("orderItem")
1183 JSONObject item = items.get(0)
1184 JSONObject service = item.get("service")
1185 String networkServiceId = service.get("id")
1186 if (networkServiceId == null || networkServiceId.equals("null")) {
1187 prepareFailedOperationStatusUpdate(execution)
1191 execution.setVariable("networkServiceId", networkServiceId)
1192 String serviceOrderState = item.get("state")
1193 execution.setVariable("ServiceOrderState", serviceOrderState)
1194 // Get serviceOrder State and process progress
1195 if("ACKNOWLEDGED".equalsIgnoreCase(serviceOrderState)) {
1196 execution.setVariable(statusVariableName, "processing")
1198 else if("INPROGRESS".equalsIgnoreCase(serviceOrderState)) {
1199 execution.setVariable(statusVariableName, "processing")
1201 else if("COMPLETED".equalsIgnoreCase(serviceOrderState)) {
1202 execution.setVariable(statusVariableName, "completed")
1204 else if("FAILED".equalsIgnoreCase(serviceOrderState)) {
1205 msg = "ServiceOrder failed"
1206 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
1209 msg = "ServiceOrder failed"
1210 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
1214 msg = "Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode
1215 prepareFailedOperationStatusUpdate(execution)
1218 }catch(Exception e){
1219 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e.getMessage())
1230 void timeDelay(DelegateExecution execution) {
1231 LOGGER.trace("${getPrefix()} Start timeDelay")
1234 LOGGER.debug("${getPrefix()} timeDelay going to sleep for 5 sec")
1238 LOGGER.debug("${getPrefix()} ::: timeDelay wakeup after 5 sec")
1239 } catch(InterruptedException e) {
1240 LOGGER.error("${getPrefix()} ::: timeDelay exception" + e)
1243 LOGGER.trace("${getPrefix()} Exit timeDelay")
1248 * Returns AAI client
1249 * @return AAI client
1251 AAIResourcesClient getAAIClient() {
1252 return new AAIResourcesClient()
1256 ExternalAPIUtilFactory getExternalAPIUtilFactory() {
1257 return new ExternalAPIUtilFactory()
1261 String getPrefix() {
1265 String getAction() {