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 = ""
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     String buildSDNCParamsXml(DelegateExecution execution) {
171         String params = ""
172         StringBuilder sb = new StringBuilder()
173         Map<String, String> paramsMap = execution.getVariable("TNNSSMF_vnfParamsMap")
174
175         for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
176             String paramsXml
177             String key = entry.getKey();
178             String value = entry.getValue()
179             paramsXml = """<${key}>$value</$key>"""
180             params = sb.append(paramsXml)
181         }
182         return params
183     }
184
185     void validateSDNCResponse(DelegateExecution execution, String response, String method) {
186         validateSDNCResponse(execution, response, method, true)
187     }
188
189     void validateSDNCResponse(DelegateExecution execution, String response, String method, boolean exceptionOnErr) {
190         logger.debug("STARTED ValidateSDNCResponse Process")
191
192         String msg
193
194         String prefix = execution.getVariable("prefix")
195         if (isBlank(prefix)) {
196             if (exceptionOnErr) {
197                 msg = "validateSDNCResponse: prefix is null"
198                 logger.error(msg)
199                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
200             }
201             return
202         }
203
204         WorkflowException workflowException = execution.getVariable("WorkflowException")
205         boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
206
207         logger.debug("TnNssmfUtils.validateSDNCResponse: SDNCResponse: " + response)
208         logger.debug("TnNssmfUtils.validateSDNCResponse: workflowException: " + workflowException)
209
210         sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
211
212         String sdncResponse = response
213         if (execution.getVariable(prefix + 'sdncResponseSuccess') == true) {
214             logger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call.  Response is: \n" + sdncResponse)
215             RollbackData rollbackData = execution.getVariable("rollbackData")
216             if (rollbackData == null) {
217                 rollbackData = new RollbackData()
218             }
219
220             if (method.equals("allocate")) {
221                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestAllocate", "true")
222             } else if (method.equals("deallocate")) {
223                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeallocate", "true")
224             } else if (method.equals("activate")) {
225                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestActivate", "true")
226             } else if (method.equals("deactivate")) {
227                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeactivate", "true")
228             } else if (method.equals("modify")) {
229                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestModify", "true")
230             }
231             execution.setVariable("rollbackData", rollbackData)
232         } else {
233             if (exceptionOnErr) {
234                 msg = "TnNssmfUtils.validateSDNCResponse: bad Response from SDNC Adapter for " + method + " SDNC Call."
235                 logger.error(msg)
236                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
237             }
238         }
239
240         logger.debug("COMPLETED ValidateSDNCResponse Process")
241     }
242
243     String getExecutionInputParams(DelegateExecution execution) {
244         String res = "msoRequestId=" + execution.getVariable("msoRequestId") +
245                 ", modelInvariantUuid=" + execution.getVariable("modelInvariantUuid") +
246                 ", modelUuid=" + execution.getVariable("modelUuid") +
247                 ", serviceInstanceID=" + execution.getVariable("serviceInstanceID") +
248                 ", operationType=" + execution.getVariable("operationType") +
249                 ", globalSubscriberId=" + execution.getVariable("globalSubscriberId") +
250                 ", dummyServiceId=" + execution.getVariable("dummyServiceId") +
251                 ", nsiId=" + execution.getVariable("nsiId") +
252                 ", networkType=" + execution.getVariable("networkType") +
253                 ", subscriptionServiceType=" + execution.getVariable("subscriptionServiceType") +
254                 ", jobId=" + execution.getVariable("jobId") +
255                 ", sliceParams=" + execution.getVariable("sliceParams") +
256                 ", servicename=" + execution.getVariable("servicename")
257
258         return res
259     }
260
261     String getFirstSnssaiFromSliceProfile(String sliceProfileStr) {
262         String snssaiListStr = jsonUtil.getJsonValue(sliceProfileStr, "snssaiList")
263         String snssai = jsonUtil.StringArrayToList(snssaiListStr).get(0)
264
265         return snssai
266     }
267
268     String getFirstPlmnIdFromSliceProfile(String sliceProfileStr) {
269         String plmnListStr = jsonUtil.getJsonValue(sliceProfileStr, "plmnIdList")
270         String res = jsonUtil.StringArrayToList(plmnListStr).get(0)
271
272         return res
273     }
274
275     void createRelationShipInAAI(DelegateExecution execution, AAIResourceUri uri, Relationship relationship) {
276         logger.debug("createRelationShipInAAI Start")
277         String msg
278         AAIResourcesClient client = new AAIResourcesClient()
279         try {
280             if (!client.exists(uri)) {
281                 logger.info("ERROR: createRelationShipInAAI: not exist: uri={}", uri)
282                 return
283             }
284             AAIResourceUri from = ((AAIResourceUri) (uri.clone())).relationshipAPI()
285             client.create(from, relationship)
286
287         } catch (BpmnError e) {
288             throw e
289         } catch (Exception ex) {
290             msg = "Exception in createRelationShipInAAI. " + ex.getMessage()
291             logger.info(msg)
292             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
293         }
294         logger.debug("createRelationShipInAAI Exit")
295     }
296
297     void attachLogicalLinkToAllottedResource(DelegateExecution execution, String aaiVersion, AAIResourceUri arUri,
298                                              String logicalLinkId) {
299
300
301         String toLink = "aai/${aaiVersion}/network/logical-links/logical-link/${logicalLinkId}"
302
303         Relationship relationship = new Relationship()
304         relationship.setRelatedLink(toLink)
305         relationship.setRelatedTo("logical-link")
306         relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
307
308         createRelationShipInAAI(execution, arUri, relationship)
309     }
310 }