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