Fixes for bugs found in Transport Slicing integration
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / TnNssmfUtils.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.aai.domain.yang.Relationship
26 import org.onap.aaiclient.client.aai.AAIResourcesClient
27 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
28 import org.onap.so.bpmn.common.scripts.ExceptionUtil
29 import org.onap.so.bpmn.common.scripts.MsoUtils
30 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
31 import org.onap.so.bpmn.core.RollbackData
32 import org.onap.so.bpmn.core.UrnPropertiesReader
33 import org.onap.so.bpmn.core.WorkflowException
34 import org.onap.so.bpmn.core.json.JsonUtils
35 import org.slf4j.Logger
36 import org.slf4j.LoggerFactory
37
38 import static org.apache.commons.lang3.StringUtils.isBlank
39
40 class TnNssmfUtils {
41     private static final Logger logger = LoggerFactory.getLogger(TnNssmfUtils.class);
42
43
44     ExceptionUtil exceptionUtil = new ExceptionUtil()
45     JsonUtils jsonUtil = new JsonUtils()
46     MsoUtils msoUtils = new MsoUtils()
47     SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
48
49     TnNssmfUtils() {
50     }
51
52
53     void setSdncCallbackUrl(DelegateExecution execution, boolean exceptionOnErr) {
54         setSdncCallbackUrl(execution, "sdncCallbackUrl", exceptionOnErr)
55     }
56
57     void setSdncCallbackUrl(DelegateExecution execution, String variableName, boolean exceptionOnErr) {
58         String sdncCallbackUrl = UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback', execution)
59
60         if (isBlank(sdncCallbackUrl) && exceptionOnErr) {
61             String msg = "mso.workflow.sdncadapter.callback is null"
62             logger.debug(msg)
63             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
64         } else {
65             execution.setVariable(variableName, sdncCallbackUrl)
66         }
67     }
68
69     String buildSDNCRequest(DelegateExecution execution, String svcInstId, String svcAction) {
70         String reqAction
71         switch (svcAction) {
72             case "create":
73                 reqAction = "AllocateTransportSliceInstance"
74                 break
75             case "delete":
76                 reqAction = "DeleteTransportSliceInstance"
77                 break
78             case "activate":
79                 reqAction = "ActivateTransportSliceInstance"
80                 break
81             case "deactivate":
82                 reqAction = "DeactivateTransportSliceInstance"
83                 break
84             default:
85                 reqAction = svcAction
86         }
87
88         buildSDNCRequest(execution, svcInstId, svcAction, reqAction)
89     }
90
91     String buildSDNCRequest(DelegateExecution execution, String svcInstId, String svcAction, String reqAction) {
92
93         String uuid = execution.getVariable('testReqId') // for junits
94         if (uuid == null) {
95             uuid = execution.getVariable("msoRequestId") + "-" + System.currentTimeMillis()
96         }
97
98         def callbackURL = execution.getVariable("sdncCallbackUrl")
99         def requestId = execution.getVariable("msoRequestId")
100         def serviceId = execution.getVariable("sliceServiceInstanceId")
101         def subServiceType = execution.getVariable("subscriptionServiceType")
102         def vnfType = execution.getVariable("serviceType")
103         def vnfName = execution.getVariable("sliceServiceInstanceName")
104         def tenantId = execution.getVariable("sliceServiceInstanceId")
105         def source = execution.getVariable("sliceServiceInstanceId")
106         def vnfId = execution.getVariable("sliceServiceInstanceId")
107         def cloudSiteId = execution.getVariable("sliceServiceInstanceId")
108         def serviceModelInfo = execution.getVariable("serviceModelInfo")
109         def vnfModelInfo = execution.getVariable("serviceModelInfo")
110         def globalSubscriberId = execution.getVariable("globalSubscriberId")
111
112         String vnfNameString = """<vnf-name>${MsoUtils.xmlEscape(vnfName)}</vnf-name>"""
113         String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo)
114         String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo)
115
116         String sdncVNFParamsXml = ""
117
118         if (execution.getVariable("vnfParamsExistFlag") == true) {
119             sdncVNFParamsXml = buildSDNCParamsXml(execution)
120         } else {
121             sdncVNFParamsXml = buildDefaultVnfInputParams(vnfId)
122         }
123
124         String sdncRequest =
125         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
126                                                     xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
127                                                     xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
128          <sdncadapter:RequestHeader>
129             <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
130             <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
131             <sdncadapter:SvcAction>${MsoUtils.xmlEscape(svcAction)}</sdncadapter:SvcAction>
132             <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
133             <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
134             <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
135          </sdncadapter:RequestHeader>
136     <sdncadapterworkflow:SDNCRequestData>
137         <request-information>
138             <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
139             <request-action>${MsoUtils.xmlEscape(reqAction)}</request-action>
140             <source>${MsoUtils.xmlEscape(source)}</source>
141             <notification-url/>
142             <order-number/>
143             <order-version/>
144         </request-information>
145         <service-information>
146             <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
147             <subscription-service-type>${MsoUtils.xmlEscape(subServiceType)}</subscription-service-type>
148             ${serviceEcompModelInformation}
149             <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
150             <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>
151         </service-information>
152         <vnf-information>
153             <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
154             <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
155             ${vnfEcompModelInformation}
156         </vnf-information>
157         <vnf-request-input>
158             ${vnfNameString}
159             <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
160             <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>
161             ${sdncVNFParamsXml}
162         </vnf-request-input>
163     </sdncadapterworkflow:SDNCRequestData>
164     </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
165
166         logger.debug("sdncRequest:  " + sdncRequest)
167         return sdncRequest
168     }
169
170
171     String buildDefaultVnfInputParams(String vnfName) {
172         String res =
173                 """<vnf-input-parameters>
174                       <param>
175                           <name>${MsoUtils.xmlEscape(vnfName)}</name>
176                       </param>
177                    </vnf-input-parameters>"""
178
179         return res
180     }
181
182     String buildSDNCParamsXml(DelegateExecution execution) {
183         String params = ""
184         StringBuilder sb = new StringBuilder()
185         Map<String, String> paramsMap = execution.getVariable("TNNSSMF_vnfParamsMap")
186
187         for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
188             String paramsXml
189             String key = entry.getKey();
190             String value = entry.getValue()
191             paramsXml = """<${key}>$value</$key>"""
192             params = sb.append(paramsXml)
193         }
194         return params
195     }
196
197     void validateSDNCResponse(DelegateExecution execution, String response, String method) {
198         validateSDNCResponse(execution, response, method, true)
199     }
200
201     void validateSDNCResponse(DelegateExecution execution, String response, String method, boolean exceptionOnErr) {
202         logger.debug("STARTED ValidateSDNCResponse Process")
203
204         String msg
205
206         String prefix = execution.getVariable("prefix")
207         if (isBlank(prefix)) {
208             if (exceptionOnErr) {
209                 msg = "validateSDNCResponse: prefix is null"
210                 logger.error(msg)
211                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
212             }
213             return
214         }
215
216         WorkflowException workflowException = execution.getVariable("WorkflowException")
217         boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
218
219         logger.debug("TnNssmfUtils.validateSDNCResponse: SDNCResponse: " + response)
220         logger.debug("TnNssmfUtils.validateSDNCResponse: workflowException: " + workflowException)
221
222         sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
223
224         String sdncResponse = response
225         if (execution.getVariable(prefix + 'sdncResponseSuccess') == true) {
226             logger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call.  Response is: \n" + sdncResponse)
227             RollbackData rollbackData = execution.getVariable("rollbackData")
228             if (rollbackData == null) {
229                 rollbackData = new RollbackData()
230             }
231
232             if (method.equals("allocate")) {
233                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestAllocate", "true")
234             } else if (method.equals("deallocate")) {
235                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeallocate", "true")
236             } else if (method.equals("activate")) {
237                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestActivate", "true")
238             } else if (method.equals("deactivate")) {
239                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeactivate", "true")
240             } else if (method.equals("modify")) {
241                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestModify", "true")
242             }
243             execution.setVariable("rollbackData", rollbackData)
244         } else {
245             if (exceptionOnErr) {
246                 msg = "TnNssmfUtils.validateSDNCResponse: bad Response from SDNC Adapter for " + method + " SDNC Call."
247                 logger.error(msg)
248                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
249             }
250         }
251
252         logger.debug("COMPLETED ValidateSDNCResponse Process")
253     }
254
255     String getExecutionInputParams(DelegateExecution execution) {
256         String res = "\n msoRequestId=" + execution.getVariable("msoRequestId") +
257                 "\n modelInvariantUuid=" + execution.getVariable("modelInvariantUuid") +
258                 "\n modelUuid=" + execution.getVariable("modelUuid") +
259                 "\n serviceInstanceID=" + execution.getVariable("serviceInstanceID") +
260                 "\n operationType=" + execution.getVariable("operationType") +
261                 "\n globalSubscriberId=" + execution.getVariable("globalSubscriberId") +
262                 "\n dummyServiceId=" + execution.getVariable("dummyServiceId") +
263                 "\n nsiId=" + execution.getVariable("nsiId") +
264                 "\n networkType=" + execution.getVariable("networkType") +
265                 "\n subscriptionServiceType=" + execution.getVariable("subscriptionServiceType") +
266                 "\n jobId=" + execution.getVariable("jobId") +
267                 "\n sliceParams=" + execution.getVariable("sliceParams") +
268                 "\n servicename=" + execution.getVariable("servicename")
269
270         return res
271     }
272
273     String getFirstSnssaiFromSliceProfile(String sliceProfileStr) {
274         String snssaiListStr = jsonUtil.getJsonValue(sliceProfileStr, "snssaiList")
275         String snssai = jsonUtil.StringArrayToList(snssaiListStr).get(0)
276
277         return snssai
278     }
279
280     String getFirstPlmnIdFromSliceProfile(String sliceProfileStr) {
281         String plmnListStr = jsonUtil.getJsonValue(sliceProfileStr, "plmnIdList")
282         String res = jsonUtil.StringArrayToList(plmnListStr).get(0)
283
284         return res
285     }
286
287     void createRelationShipInAAI(DelegateExecution execution, AAIResourceUri uri, Relationship relationship) {
288         logger.debug("createRelationShipInAAI Start")
289         String msg
290         AAIResourcesClient client = new AAIResourcesClient()
291         try {
292             if (!client.exists(uri)) {
293                 logger.info("ERROR: createRelationShipInAAI: not exist: uri={}", uri)
294                 return
295             }
296             AAIResourceUri from = ((AAIResourceUri) (uri.clone())).relationshipAPI()
297             client.create(from, relationship)
298
299         } catch (BpmnError e) {
300             throw e
301         } catch (Exception ex) {
302             msg = "Exception in createRelationShipInAAI. " + ex.getMessage()
303             logger.info(msg)
304             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
305         }
306         logger.debug("createRelationShipInAAI Exit")
307     }
308
309     void attachLogicalLinkToAllottedResource(DelegateExecution execution, String aaiVersion, AAIResourceUri arUri,
310                                              String logicalLinkId) {
311
312         String toLink = "aai/${aaiVersion}/network/logical-links/logical-link/${logicalLinkId}"
313
314         Relationship relationship = new Relationship()
315         relationship.setRelatedLink(toLink)
316         relationship.setRelatedTo("logical-link")
317         relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
318
319         createRelationShipInAAI(execution, arUri, relationship)
320     }
321
322     void attachNetworkPolicyToAllottedResource(DelegateExecution execution, String aaiVersion,
323                                                AAIResourceUri aaiResourceUri, String networkPolicyId) {
324
325         String toLink = "aai/${aaiVersion}/network/network-policies/network-policy/${networkPolicyId}"
326
327         Relationship relationship = new Relationship()
328         relationship.setRelatedLink(toLink)
329         relationship.setRelatedTo("network-policy")
330         relationship.setRelationshipLabel("org.onap.relationships.inventory.Uses")
331
332         createRelationShipInAAI(execution, aaiResourceUri, relationship)
333
334     }
335 }