2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.so.bpmn.infrastructure.scripts
23 import org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.aai.domain.yang.AllottedResources
26 import org.onap.aai.domain.yang.LogicalLink
27 import org.onap.aai.domain.yang.NetworkPolicy
28 import org.onap.aai.domain.yang.Relationship
29 import org.onap.aai.domain.yang.ServiceInstance
30 import org.onap.aaiclient.client.aai.AAIResourcesClient
31 import org.onap.aaiclient.client.aai.AAIVersion
32 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
33 import org.onap.aaiclient.client.aai.entities.Relationships
34 import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri
35 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
36 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
37 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
38 import org.onap.so.bpmn.common.scripts.ExceptionUtil
39 import org.onap.so.bpmn.common.scripts.MsoUtils
40 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
41 import org.onap.so.bpmn.core.RollbackData
42 import org.onap.so.bpmn.core.UrnPropertiesReader
43 import org.onap.so.bpmn.core.WorkflowException
44 import org.onap.so.bpmn.core.json.JsonUtils
45 import org.onap.so.db.request.beans.ResourceOperationStatus
46 import org.slf4j.Logger
47 import org.slf4j.LoggerFactory
49 import static org.apache.commons.lang3.StringUtils.isBlank
52 static final String AAI_VERSION = AAIVersion.LATEST
53 private static final Logger logger = LoggerFactory.getLogger(TnNssmfUtils.class);
56 ExceptionUtil exceptionUtil = new ExceptionUtil()
57 JsonUtils jsonUtil = new JsonUtils()
58 MsoUtils msoUtils = new MsoUtils()
59 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
65 void setSdncCallbackUrl(DelegateExecution execution, boolean exceptionOnErr) {
66 setSdncCallbackUrl(execution, "sdncCallbackUrl", exceptionOnErr)
69 void setSdncCallbackUrl(DelegateExecution execution, String variableName, boolean exceptionOnErr) {
70 String sdncCallbackUrl = UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback', execution)
72 if (isBlank(sdncCallbackUrl) && exceptionOnErr) {
73 String msg = "mso.workflow.sdncadapter.callback is null"
75 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
77 execution.setVariable(variableName, sdncCallbackUrl)
81 String buildSDNCRequest(DelegateExecution execution, String svcInstId, String svcAction) {
85 reqAction = "AllocateTransportSliceInstance"
88 reqAction = "DeleteTransportSliceInstance"
91 reqAction = "ActivateTransportSliceInstance"
94 reqAction = "DeactivateTransportSliceInstance"
97 reqAction = "ModifyTransportSliceInstance"
100 reqAction = svcAction
103 buildSDNCRequest(execution, svcInstId, svcAction, reqAction)
106 String buildSDNCRequest(DelegateExecution execution, String svcInstId, String svcAction, String reqAction) {
108 String uuid = execution.getVariable('testReqId') // for junits
110 uuid = execution.getVariable("msoRequestId") + "-" + System.currentTimeMillis()
113 def callbackURL = execution.getVariable("sdncCallbackUrl")
114 def requestId = execution.getVariable("msoRequestId")
115 def serviceId = execution.getVariable("sliceServiceInstanceId")
116 def subServiceType = execution.getVariable("subscriptionServiceType")
117 def vnfType = execution.getVariable("serviceType")
118 def vnfName = execution.getVariable("sliceServiceInstanceName")
119 def tenantId = execution.getVariable("sliceServiceInstanceId")
120 def source = execution.getVariable("sliceServiceInstanceId")
121 def vnfId = execution.getVariable("sliceServiceInstanceId")
122 def cloudSiteId = execution.getVariable("sliceServiceInstanceId")
123 def serviceModelInfo = execution.getVariable("serviceModelInfo")
124 def vnfModelInfo = execution.getVariable("serviceModelInfo")
125 def globalSubscriberId = execution.getVariable("globalSubscriberId")
127 String vnfNameString = """<vnf-name>${MsoUtils.xmlEscape(vnfName)}</vnf-name>"""
128 String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo)
129 String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo)
131 String sdncVNFParamsXml = ""
133 if (execution.getVariable("vnfParamsExistFlag") == true) {
134 sdncVNFParamsXml = buildSDNCParamsXml(execution)
136 sdncVNFParamsXml = buildDefaultVnfInputParams(vnfId)
140 """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
141 xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
142 xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
143 <sdncadapter:RequestHeader>
144 <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
145 <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
146 <sdncadapter:SvcAction>${MsoUtils.xmlEscape(svcAction)}</sdncadapter:SvcAction>
147 <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
148 <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
149 <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
150 </sdncadapter:RequestHeader>
151 <sdncadapterworkflow:SDNCRequestData>
152 <request-information>
153 <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
154 <request-action>${MsoUtils.xmlEscape(reqAction)}</request-action>
155 <source>${MsoUtils.xmlEscape(source)}</source>
159 </request-information>
160 <service-information>
161 <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
162 <subscription-service-type>${MsoUtils.xmlEscape(subServiceType)}</subscription-service-type>
163 ${serviceEcompModelInformation}
164 <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
165 <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>
166 </service-information>
168 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
169 <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
170 ${vnfEcompModelInformation}
174 <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
175 <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>
178 </sdncadapterworkflow:SDNCRequestData>
179 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
181 logger.debug("sdncRequest: " + sdncRequest)
186 String buildDefaultVnfInputParams(String vnfName) {
188 """<vnf-input-parameters>
190 <name>${MsoUtils.xmlEscape(vnfName)}</name>
192 </vnf-input-parameters>"""
197 String buildSDNCParamsXml(DelegateExecution execution) {
199 StringBuilder sb = new StringBuilder()
200 Map<String, String> paramsMap = execution.getVariable("TNNSSMF_vnfParamsMap")
202 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
204 String key = entry.getKey();
205 String value = entry.getValue()
206 paramsXml = """<${key}>$value</$key>"""
207 params = sb.append(paramsXml)
212 void validateSDNCResponse(DelegateExecution execution, String response, String method) {
213 validateSDNCResponse(execution, response, method, true)
216 void validateSDNCResponse(DelegateExecution execution, String response, String method, boolean exceptionOnErr) {
217 logger.debug("STARTED ValidateSDNCResponse Process")
221 String prefix = execution.getVariable("prefix")
222 if (isBlank(prefix)) {
223 if (exceptionOnErr) {
224 msg = "validateSDNCResponse: prefix is null"
226 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
231 WorkflowException workflowException = execution.getVariable("WorkflowException")
232 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
234 logger.debug("TnNssmfUtils.validateSDNCResponse: SDNCResponse: " + response)
235 logger.debug("TnNssmfUtils.validateSDNCResponse: workflowException: " + workflowException)
237 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
239 String sdncResponse = response
240 if (execution.getVariable(prefix + 'sdncResponseSuccess') == true) {
241 logger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse)
242 RollbackData rollbackData = execution.getVariable("rollbackData")
243 if (rollbackData == null) {
244 rollbackData = new RollbackData()
247 if (method.equals("allocate")) {
248 rollbackData.put("VNFMODULE", "rollbackSDNCRequestAllocate", "true")
249 } else if (method.equals("deallocate")) {
250 rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeallocate", "true")
251 } else if (method.equals("activate")) {
252 rollbackData.put("VNFMODULE", "rollbackSDNCRequestActivate", "true")
253 } else if (method.equals("deactivate")) {
254 rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeactivate", "true")
255 } else if (method.equals("modify")) {
256 rollbackData.put("VNFMODULE", "rollbackSDNCRequestModify", "true")
258 execution.setVariable("rollbackData", rollbackData)
260 if (exceptionOnErr) {
261 msg = "TnNssmfUtils.validateSDNCResponse: bad Response from SDNC Adapter for " + method + " SDNC Call."
263 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
267 logger.debug("COMPLETED ValidateSDNCResponse Process")
270 String getExecutionInputParams(DelegateExecution execution) {
271 String res = "\n msoRequestId=" + execution.getVariable("msoRequestId") +
272 "\n modelInvariantUuid=" + execution.getVariable("modelInvariantUuid") +
273 "\n modelUuid=" + execution.getVariable("modelUuid") +
274 "\n serviceInstanceID=" + execution.getVariable("serviceInstanceID") +
275 "\n operationType=" + execution.getVariable("operationType") +
276 "\n globalSubscriberId=" + execution.getVariable("globalSubscriberId") +
277 "\n dummyServiceId=" + execution.getVariable("dummyServiceId") +
278 "\n nsiId=" + execution.getVariable("nsiId") +
279 "\n networkType=" + execution.getVariable("networkType") +
280 "\n subscriptionServiceType=" + execution.getVariable("subscriptionServiceType") +
281 "\n jobId=" + execution.getVariable("jobId") +
282 "\n sliceParams=" + execution.getVariable("sliceParams") +
283 "\n servicename=" + execution.getVariable("servicename")
288 String getFirstSnssaiFromSliceProfile(String sliceProfileStr) {
289 String snssaiListStr = jsonUtil.getJsonValue(sliceProfileStr, "snssaiList")
290 String snssai = jsonUtil.StringArrayToList(snssaiListStr).get(0)
295 String getFirstPlmnIdFromSliceProfile(String sliceProfileStr) {
296 String plmnListStr = jsonUtil.getJsonValue(sliceProfileStr, "pLMNIdList")
297 String res = jsonUtil.StringArrayToList(plmnListStr).get(0)
302 void createRelationShipInAAI(DelegateExecution execution, AAIResourceUri uri, Relationship relationship) {
303 logger.debug("createRelationShipInAAI Start")
305 AAIResourcesClient client = new AAIResourcesClient()
307 if (!client.exists(uri)) {
308 logger.info("ERROR: createRelationShipInAAI: not exist: uri={}", uri)
311 AAIResourceUri from = ((AAIResourceUri) (uri.clone())).relationshipAPI()
312 client.create(from, relationship)
314 } catch (BpmnError e) {
316 } catch (Exception ex) {
317 msg = "Exception in createRelationShipInAAI. " + ex.getMessage()
319 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
321 logger.debug("createRelationShipInAAI Exit")
324 void attachLogicalLinkToAllottedResource(DelegateExecution execution, String aaiVersion, AAIResourceUri arUri,
325 String logicalLinkId) {
327 String toLink = "aai/${aaiVersion}/network/logical-links/logical-link/${logicalLinkId}"
329 Relationship relationship = new Relationship()
330 relationship.setRelatedLink(toLink)
331 relationship.setRelatedTo("logical-link")
332 relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
334 createRelationShipInAAI(execution, arUri, relationship)
337 void attachNetworkPolicyToAllottedResource(DelegateExecution execution, String aaiVersion,
338 AAIResourceUri aaiResourceUri, String networkPolicyId) {
340 String toLink = "aai/${aaiVersion}/network/network-policies/network-policy/${networkPolicyId}"
342 Relationship relationship = new Relationship()
343 relationship.setRelatedLink(toLink)
344 relationship.setRelatedTo("network-policy")
345 relationship.setRelationshipLabel("org.onap.relationships.inventory.Uses")
347 createRelationShipInAAI(execution, aaiResourceUri, relationship)
351 ResourceOperationStatus buildRoStatus(String nsstId,
358 String statusDescription) {
359 ResourceOperationStatus roStatus = new ResourceOperationStatus()
360 roStatus.setResourceTemplateUUID(nsstId)
361 roStatus.setResourceInstanceID(nssiId)
362 roStatus.setServiceId(nsiId)
363 roStatus.setOperationId(jobId)
364 roStatus.setOperType(action)
365 roStatus.setProgress(progress)
366 roStatus.setStatus(status)
367 roStatus.setStatusDescription(statusDescription)
373 void setEnableSdncConfig(DelegateExecution execution) {
374 String enableSdnc = UrnPropertiesReader.getVariable(
375 "mso.workflow.TnNssmf.enableSDNCNetworkConfig")
376 if (isBlank(enableSdnc)) {
377 logger.debug("mso.workflow.TnNssmf.enableSDNCNetworkConfig is undefined, so use default value (true)")
380 logger.debug("setEnableSdncConfig: enableSdnc=" + enableSdnc)
382 execution.setVariable("enableSdnc", enableSdnc)
385 void setEnableOofConfig(DelegateExecution execution) {
386 String enableOof = UrnPropertiesReader.getVariable(
387 "mso.workflow.TnNssmf.enableOOFNetworkConfig")
388 if (isBlank(enableOof)) {
389 logger.debug("mso.workflow.TnNssmf.enableOOFNetworkConfig is undefined, so use default value (true)")
392 logger.debug("setEnableOofConfig: enableOof=" + enableOof)
394 execution.setVariable("enableOof", enableOof)
397 String setExecVarFromJsonIfExists(DelegateExecution execution,
398 String jsonStr, String jsonKey, String varName) {
399 return setExecVarFromJsonStr(execution, jsonStr, jsonKey, varName, false)
402 String setExecVarFromJsonStr(DelegateExecution execution,
403 String jsonStr, String jsonKey, String varName,
404 boolean exceptionOnErr) {
406 String valueStr = jsonUtil.getJsonValue(jsonStr, jsonKey)
407 if (isBlank(valueStr)) {
408 if (exceptionOnErr) {
409 msg = "cannot find " + jsonKey + " in " + jsonStr
411 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
414 execution.setVariable(varName, valueStr)
420 ServiceInstance getServiceInstanceFromAai(String serviceInstanceId) {
421 if (isBlank(serviceInstanceId)) {
422 logger.error("ERROR: getServiceInstanceFromAai: serviceInstanceId is blank")
426 ServiceInstance nssi = null
427 AAIResourcesClient client = new AAIResourcesClient()
428 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.Types.SERVICE_INSTANCE
429 .getFragment(serviceInstanceId))
430 Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, uri)
432 if (nssiOpt.isPresent()) {
436 String msg = String.format("ERROR: getServiceInstanceFromAai: NSSI %s not found in AAI", serviceInstanceId)
443 String getModelUuidFromServiceInstance(String serviceInstanceId) {
444 ServiceInstance si = getServiceInstanceFromAai(serviceInstanceId)
446 String msg = String.format("ERROR: getModelUuidFromServiceInstance: getServiceInstanceFromAai() failed. " +
447 "serviceInstanceId=%s", serviceInstanceId)
452 return si.getModelVersionId()
455 AAIResourceUri buildNetworkPolicyUri(String networkPolicyId) {
456 AAIResourceUri networkPolicyUri =
457 AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().networkPolicy(networkPolicyId))
459 return networkPolicyUri
462 AAIResourceUri buildAllottedResourceUri(DelegateExecution execution, String serviceInstanceId,
463 String allottedResourceId) {
465 AAIResourceUri allottedResourceUri =
466 AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business()
467 .customer(execution.getVariable("globalSubscriberId"))
468 .serviceSubscription(execution.getVariable("subscriptionServiceType"))
469 .serviceInstance(serviceInstanceId)
470 .allottedResource(allottedResourceId))
472 return allottedResourceUri
475 AAIPluralResourceUri buildAllottedResourcesUri(DelegateExecution execution, String serviceInstanceId) {
477 AAIPluralResourceUri arsUri =
478 AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business()
479 .customer(execution.getVariable("globalSubscriberId"))
480 .serviceSubscription(execution.getVariable("subscriptionServiceType"))
481 .serviceInstance(serviceInstanceId)
482 .allottedResources())
487 AllottedResources getAllottedResourcesFromAai(DelegateExecution execution, String serviceInstanceId, boolean exceptionOnErr) {
488 AllottedResources res
490 AAIResourcesClient client = new AAIResourcesClient()
492 AAIPluralResourceUri arsUri = buildAllottedResourcesUri(execution, serviceInstanceId)
494 //AAIResultWrapper wrapperAllotted = client.get(arsUri, NotFoundException.class)
495 //Optional<AllottedResources> allAllotted = wrapperAllotted.asBean(AllottedResources.class)
496 //AllottedResources allottedResources = allAllotted.get()
498 Optional<AllottedResources> arsOpt = client.get(AllottedResources.class, arsUri)
499 if (arsOpt.isPresent()) {
503 String msg = String.format("ERROR: getAllottedResourcesFromAai: ars not found. nssiId=%s", serviceInstanceId)
505 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
507 } catch (BpmnError e) {
508 if (exceptionOnErr) {
511 } catch (Exception ex) {
512 if (exceptionOnErr) {
513 String msg = String.format("ERROR: getAllottedResourcesFromAai: %s", ex.getMessage())
515 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
522 String getPolicyIdFromAr(DelegateExecution execution, String serviceInstanceId,
523 String arId, boolean exceptionOnErr) {
526 AAIResourcesClient client = new AAIResourcesClient()
528 AAIResourceUri arUri = buildAllottedResourceUri(execution, serviceInstanceId, arId)
529 List<AAIResourceUri> policyUriList = getRelationshipUriListInAai(execution, arUri,
530 AAIFluentTypeBuilder.Types.NETWORK_POLICY, exceptionOnErr)
531 for (AAIResourceUri policyUri : policyUriList) {
532 Optional<NetworkPolicy> policyOpt = client.get(NetworkPolicy.class, policyUri)
533 if (policyOpt.isPresent()) {
534 NetworkPolicy policy = policyOpt.get()
535 return policy.getNetworkPolicyId()
537 String msg = String.format("ERROR: getPolicyIdFromAr: arUri=%s", policyUri)
539 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
542 } catch (BpmnError e) {
543 if (exceptionOnErr) {
546 } catch (Exception ex) {
547 if (exceptionOnErr) {
548 String msg = String.format("ERROR: getPolicyIdFromAr: %s", ex.getMessage())
550 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
558 List<AAIResourceUri> getRelationshipUriListInAai(DelegateExecution execution,
561 boolean exceptionOnErr) {
562 AAIResourcesClient client = new AAIResourcesClient()
563 AAIResultWrapper wrapper = client.get(uri);
564 Optional<Relationships> relationships = wrapper.getRelationships()
565 if (relationships.isPresent()) {
566 return relationships.get().getRelatedUris(info)
568 if (exceptionOnErr) {
569 String msg = "ERROR: getRelationshipUriListInAai: No relationship found"
571 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
578 List<String> getLogicalLinkNamesFromAr(DelegateExecution execution, String serviceInstanceId,
579 String arId, boolean exceptionOnErr) {
580 List<String> res = new ArrayList<>()
582 AAIResourcesClient client = new AAIResourcesClient()
584 AAIResourceUri arUri = buildAllottedResourceUri(execution, serviceInstanceId, arId)
585 List<AAIResourceUri> logicalLinkUriList = getRelationshipUriListInAai(execution, arUri,
586 AAIFluentTypeBuilder.Types.LOGICAL_LINK, exceptionOnErr)
587 for (AAIResourceUri logicalLinkUri : logicalLinkUriList) {
588 Optional<LogicalLink> logicalLinkOpt = client.get(LogicalLink.class, logicalLinkUri)
589 if (logicalLinkOpt.isPresent()) {
590 LogicalLink logicalLink = logicalLinkOpt.get()
591 res.add(logicalLink.getLinkName())
593 String msg = String.format("ERROR: getLogicalLinkNamesFromAr: logicalLinkUri=%s", logicalLinkUri)
595 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
598 } catch (BpmnError e) {
599 if (exceptionOnErr) {
602 } catch (Exception ex) {
603 if (exceptionOnErr) {
604 String msg = String.format("ERROR: getLogicalLinkNamesFromAr: %s", ex.getMessage())
606 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)