Fixes for bugs in Allocate TN NSSI WF found in integration test
[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 action) {
70
71         String uuid = execution.getVariable('testReqId') // for junits
72         if (uuid == null) {
73             uuid = execution.getVariable("msoRequestId") + "-" + System.currentTimeMillis()
74         }
75
76         def callbackURL = execution.getVariable("sdncCallbackUrl")
77         def requestId = execution.getVariable("msoRequestId")
78         def serviceId = execution.getVariable("sliceServiceInstanceId")
79         def vnfType = execution.getVariable("serviceType")
80         def vnfName = execution.getVariable("sliceServiceInstanceName")
81         def tenantId = execution.getVariable("sliceServiceInstanceId")
82         def source = execution.getVariable("sliceServiceInstanceId")
83         def vnfId = execution.getVariable("sliceServiceInstanceId")
84         def cloudSiteId = execution.getVariable("sliceServiceInstanceId")
85         def serviceModelInfo = execution.getVariable("serviceModelInfo")
86         def vnfModelInfo = execution.getVariable("serviceModelInfo")
87         def globalSubscriberId = execution.getVariable("globalSubscriberId")
88
89         String vnfNameString = """<vnf-name>${MsoUtils.xmlEscape(vnfName)}</vnf-name>"""
90         String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo)
91         String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo)
92
93         String sdncVNFParamsXml = ""
94
95         if (execution.getVariable("vnfParamsExistFlag") == true) {
96             sdncVNFParamsXml = buildSDNCParamsXml(execution)
97         } else {
98             sdncVNFParamsXml = ""
99         }
100
101         String sdncRequest =
102                 """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
103                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
104                                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
105            <sdncadapter:RequestHeader>
106                                 <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
107                                 <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
108                                 <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
109                                 <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
110                                 <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
111                                 <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
112                 </sdncadapter:RequestHeader>
113         <sdncadapterworkflow:SDNCRequestData>
114                 <request-information>
115                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
116                         <request-action>AllocateTnNssi</request-action>
117                         <source>${MsoUtils.xmlEscape(source)}</source>
118                         <notification-url/>
119                         <order-number/>
120                         <order-version/>
121                 </request-information>
122                 <service-information>
123                         <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
124                         <subscription-service-type>${MsoUtils.xmlEscape(serviceId)}</subscription-service-type>
125                         ${serviceEcompModelInformation}
126                         <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
127                         <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>
128                 </service-information>
129                 <vnf-information>
130                         <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
131                         <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
132                         ${vnfEcompModelInformation}
133                 </vnf-information>
134                 <vnf-request-input>
135                         ${vnfNameString}
136                         <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
137                         <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>
138                         ${sdncVNFParamsXml}
139                 </vnf-request-input>
140         </sdncadapterworkflow:SDNCRequestData>
141         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
142
143         logger.debug("sdncRequest:  " + sdncRequest)
144         return sdncRequest
145     }
146
147     String buildSDNCParamsXml(DelegateExecution execution) {
148         String params = ""
149         StringBuilder sb = new StringBuilder()
150         Map<String, String> paramsMap = execution.getVariable("TNNSSMF_vnfParamsMap")
151
152         for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
153             String paramsXml
154             String key = entry.getKey();
155             String value = entry.getValue()
156             paramsXml = """<${key}>$value</$key>"""
157             params = sb.append(paramsXml)
158         }
159         return params
160     }
161
162     void validateSDNCResponse(DelegateExecution execution, String response, String method) {
163         validateSDNCResponse(execution, response, method, true)
164     }
165
166     void validateSDNCResponse(DelegateExecution execution, String response, String method, boolean exceptionOnErr) {
167         logger.debug("STARTED ValidateSDNCResponse Process")
168
169         String msg
170
171         String prefix = execution.setVariable("prefix")
172         if (isBlank(prefix)) {
173             if (exceptionOnErr) {
174                 msg = "validateSDNCResponse: prefix is null"
175                 logger.error(msg)
176                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
177             }
178             return
179         }
180
181         WorkflowException workflowException = execution.getVariable("WorkflowException")
182         boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
183
184         logger.debug("workflowException: " + workflowException)
185
186         sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
187
188         String sdncResponse = response
189         if (execution.getVariable(prefix + 'sdncResponseSuccess') == true) {
190             logger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call.  Response is: \n" + sdncResponse)
191             RollbackData rollbackData = execution.getVariable("rollbackData")
192
193             if (method.equals("allocate")) {
194                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestAllocate", "true")
195             } else if (method.equals("deallocate")) {
196                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeallocate", "true")
197             } else if (method.equals("activate")) {
198                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestActivate", "true")
199             } else if (method.equals("deactivate")) {
200                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeactivate", "true")
201             } else if (method.equals("modify")) {
202                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestModify", "true")
203             }
204             execution.setVariable("rollbackData", rollbackData)
205         } else {
206             if (exceptionOnErr) {
207                 msg = "validateSDNCResponse: bad Response from SDNC Adapter for " + method + " SDNC Call."
208                 logger.error(msg)
209                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
210             }
211         }
212
213         logger.debug("COMPLETED ValidateSDNCResponse Process")
214     }
215
216     String getExecutionInputParams(DelegateExecution execution) {
217         String res = "msoRequestId=" + execution.getVariable("msoRequestId") +
218                 ", modelInvariantUuid=" + execution.getVariable("modelInvariantUuid") +
219                 ", modelUuid=" + execution.getVariable("modelUuid") +
220                 ", serviceInstanceID=" + execution.getVariable("serviceInstanceID") +
221                 ", operationType=" + execution.getVariable("operationType") +
222                 ", globalSubscriberId=" + execution.getVariable("globalSubscriberId") +
223                 ", dummyServiceId=" + execution.getVariable("dummyServiceId") +
224                 ", nsiId=" + execution.getVariable("nsiId") +
225                 ", networkType=" + execution.getVariable("networkType") +
226                 ", subscriptionServiceType=" + execution.getVariable("subscriptionServiceType") +
227                 ", jobId=" + execution.getVariable("jobId") +
228                 ", sliceParams=" + execution.getVariable("sliceParams") +
229                 ", servicename=" + execution.getVariable("servicename")
230
231         return res
232     }
233
234     String getFirstSnssaiFromSliceProfile(String sliceProfileStr) {
235         String snssaiListStr = jsonUtil.getJsonValue(sliceProfileStr, "snssaiList")
236         String snssai = jsonUtil.StringArrayToList(snssaiListStr).get(0)
237
238         return snssai
239     }
240
241     String getFirstPlmnIdFromSliceProfile(String sliceProfileStr) {
242         String plmnListStr = jsonUtil.getJsonValue(sliceProfileStr, "plmnIdList")
243         String res = jsonUtil.StringArrayToList(plmnListStr).get(0)
244
245         return res
246     }
247
248     void createRelationShipInAAI(DelegateExecution execution, AAIResourceUri uri, Relationship relationship) {
249         logger.debug("createRelationShipInAAI Start")
250         String msg
251         AAIResourcesClient client = new AAIResourcesClient()
252         try {
253             if (!client.exists(uri)) {
254                 logger.info("ERROR: createRelationShipInAAI: not exist: uri={}", uri)
255                 return
256             }
257             AAIResourceUri from = ((AAIResourceUri) (uri.clone())).relationshipAPI()
258             client.create(from, relationship)
259
260         } catch (BpmnError e) {
261             throw e
262         } catch (Exception ex) {
263             msg = "Exception in createRelationShipInAAI. " + ex.getMessage()
264             logger.info(msg)
265             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
266         }
267         logger.debug("createRelationShipInAAI Exit")
268     }
269
270     void attachLogicalLinkToAllottedResource(DelegateExecution execution, String aaiVersion, AAIResourceUri arUri,
271                                              String logicalLinkId) {
272
273
274         String toLink = "aai/${aaiVersion}/network/logical-links/logical-link/${logicalLinkId}"
275
276         Relationship relationship = new Relationship()
277         relationship.setRelatedLink(toLink)
278         relationship.setRelatedTo("logical-link")
279         relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
280
281         createRelationShipInAAI(execution, arUri, relationship)
282     }
283 }