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