Merge "Remove 504 error for retries"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateTnNssiInstance.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.NetworkPolicy
26 import org.onap.aai.domain.yang.SliceProfile
27 import org.onap.aaiclient.client.aai.AAIResourcesClient
28 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
29 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
30 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
31 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
32 import org.onap.so.bpmn.common.scripts.ExceptionUtil
33 import org.onap.so.bpmn.core.json.JsonUtils
34 import org.slf4j.Logger
35 import org.slf4j.LoggerFactory
36
37 class DoCreateTnNssiInstance extends AbstractServiceTaskProcessor {
38
39     private static final Logger logger = LoggerFactory.getLogger(DoCreateTnNssiInstance.class);
40     final String AAI_VERSION = "v21"
41     JsonUtils jsonUtil = new JsonUtils()
42     TnNssmfUtils tnNssmfUtils = new TnNssmfUtils()
43     ExceptionUtil exceptionUtil = new ExceptionUtil()
44     String Prefix = "DCTN_"
45
46     void preProcessRequest(DelegateExecution execution) {
47         String msg = ""
48         logger.trace("Enter preProcessRequest()")
49
50         execution.setVariable("prefix", Prefix)
51
52         String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
53         String modelUuid = execution.getVariable("modelUuid")
54         //here modelVersion is not set, we use modelUuid to decompose the service.
55         def isDebugLogEnabled = true
56         execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
57         String serviceModelInfo = """{
58             "modelInvariantUuid":"${modelInvariantUuid}",
59             "modelUuid":"${modelUuid}",
60             "modelVersion":""
61              }"""
62         execution.setVariable("serviceModelInfo", serviceModelInfo)
63
64         logger.trace("Exit preProcessRequest")
65     }
66
67
68     void createSliceProfile(DelegateExecution execution) {
69
70         String ssInstanceId = execution.getVariable("sliceServiceInstanceId")
71         String sliceProfileStr = execution.getVariable("sliceProfile")
72         String sliceProfileId = UUID.randomUUID().toString()
73         SliceProfile sliceProfile = new SliceProfile();
74         sliceProfile.setProfileId(sliceProfileId)
75         sliceProfile.setLatency(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "latency")))
76         sliceProfile.setResourceSharingLevel(jsonUtil.getJsonValue(sliceProfileStr, "resourceSharingLevel"))
77         //sliceProfile.setSNssai(tnNssmfUtils.getFirstSnssaiFromSliceProfile(sliceProfileStr))
78
79         sliceProfile.setMaxBandwidth(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "maxBandwidth")))
80
81         //sliceProfile.setReliability(new Object())
82         try {
83             AAIResourcesClient client = getAAIClient()
84             AAIResourceUri uri =
85                     AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business()
86                             .customer(execution.getVariable("globalSubscriberId"))
87                             .serviceSubscription(execution.getVariable("subscriptionServiceType"))
88                             .serviceInstance(ssInstanceId)
89                             .sliceProfile(sliceProfileId))
90             client.create(uri, sliceProfile)
91
92         } catch (BpmnError e) {
93             throw e
94         } catch (Exception ex) {
95             String msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
96             logger.info(msg)
97             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
98         }
99     }
100
101
102     void createServiceInstance(DelegateExecution execution) {
103
104         String serviceRole = "TN"
105         String serviceType = execution.getVariable("subscriptionServiceType")
106         String ssInstanceId = execution.getVariable("sliceServiceInstanceId")
107         String sliceProfileStr = execution.getVariable("sliceProfile")
108         try {
109             org.onap.aai.domain.yang.ServiceInstance ss = new org.onap.aai.domain.yang.ServiceInstance()
110             ss.setServiceInstanceId(ssInstanceId)
111             String sliceInstanceName = execution.getVariable("sliceServiceInstanceName")
112             ss.setServiceInstanceName(sliceInstanceName)
113             ss.setServiceType(serviceType)
114             String serviceStatus = "allocated"
115             ss.setOrchestrationStatus(serviceStatus)
116             String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
117             String modelUuid = execution.getVariable("modelUuid")
118             //TODO: need valid model ID from the caller, as AAI does not accept invalid IDs
119             //ss.setModelInvariantId(modelInvariantUuid)
120             //ss.setModelVersionId(modelUuid)
121             String serviceInstanceLocationid = tnNssmfUtils.getFirstPlmnIdFromSliceProfile(sliceProfileStr)
122             ss.setServiceInstanceLocationId(serviceInstanceLocationid)
123             String snssai = tnNssmfUtils.getFirstSnssaiFromSliceProfile(sliceProfileStr)
124             ss.setEnvironmentContext(snssai)
125             ss.setServiceRole(serviceRole)
126             AAIResourcesClient client = getAAIClient()
127             AAIResourceUri uri =
128                     AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business()
129                             .customer(execution.getVariable("globalSubscriberId"))
130                             .serviceSubscription(execution.getVariable("subscriptionServiceType"))
131                             .serviceInstance(ssInstanceId))
132             client.create(uri, ss)
133         } catch (BpmnError e) {
134             throw e
135         } catch (Exception ex) {
136             String msg = "Exception in DoCreateTnNssiInstance.createServiceInstance: " + ex.getMessage()
137             logger.error(msg)
138             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
139         }
140     }
141
142
143     void createAllottedResource(DelegateExecution execution) {
144         String ssInstanceId = execution.getVariable('sliceServiceInstanceId')
145
146         try {
147             List<String> networkStrList = jsonUtil.StringArrayToList(execution.getVariable("transportSliceNetworks"))
148
149             for (String networkStr : networkStrList) {
150                 String allottedResourceId = UUID.randomUUID().toString()
151                 AAIResourceUri allottedResourceUri =
152                         AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business()
153                                 .customer(execution.getVariable("globalSubscriberId"))
154                                 .serviceSubscription(execution.getVariable("subscriptionServiceType"))
155                                 .serviceInstance(execution.getVariable("sliceServiceInstanceId"))
156                                 .allottedResource(allottedResourceId))
157                 execution.setVariable("allottedResourceUri", allottedResourceUri)
158                 String modelInvariantId = execution.getVariable("modelInvariantUuid")
159                 String modelVersionId = execution.getVariable("modelUuid")
160
161                 org.onap.aai.domain.yang.AllottedResource resource = new org.onap.aai.domain.yang.AllottedResource()
162                 resource.setId(allottedResourceId)
163                 resource.setType("TsciNetwork")
164                 resource.setAllottedResourceName("network_" + execution.getVariable("sliceServiceInstanceName"))
165                 getAAIClient().create(allottedResourceUri, resource)
166
167                 createNetworkPolicyForAllocatedResource(execution, ssInstanceId, allottedResourceId)
168
169                 String linkArrayStr = jsonUtil.getJsonValue(networkStr, "connectionLinks")
170                 createLogicalLinksForAllocatedResource(execution, linkArrayStr, ssInstanceId, allottedResourceId)
171             }
172         } catch (BpmnError e) {
173             throw e
174         } catch (Exception ex) {
175             String msg = "Exception in DoCreateTnNssiInstance.createAllottedResource: " + ex.getMessage()
176             logger.error(msg)
177             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
178         }
179     }
180
181     void createNetworkPolicy(DelegateExecution execution, String ssInstanceId, String networkPolicyId) {
182         try {
183
184             String sliceProfileStr = execution.getVariable("sliceProfile")
185             if (sliceProfileStr == null || sliceProfileStr.isEmpty()) {
186                 String msg = "ERROR: createNetworkPolicy: sliceProfile is null"
187                 logger.error(msg)
188                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
189             }
190
191             NetworkPolicy networkPolicy = new NetworkPolicy();
192             networkPolicy.setNetworkPolicyId(networkPolicyId)
193             networkPolicy.setName("TSCi policy")
194             networkPolicy.setType("SLA")
195             networkPolicy.setNetworkPolicyFqdn(ssInstanceId)
196
197             String latencyStr = jsonUtil.getJsonValue(sliceProfileStr, "latency")
198             if (latencyStr != null && !latencyStr.isEmpty()) {
199                 networkPolicy.setLatency(Integer.parseInt(latencyStr))
200             }
201
202             String bwStr = jsonUtil.getJsonValue(sliceProfileStr, "maxBandwidth")
203             if (bwStr != null && !bwStr.isEmpty()) {
204                 networkPolicy.setMaxBandwidth(Integer.parseInt(bwStr))
205             } else {
206                 log.debug("ERROR: createNetworkPolicy: maxBandwidth is null")
207             }
208
209             //networkPolicy.setReliability(new Object())
210
211             AAIResourceUri networkPolicyUri =
212                     AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().networkPolicy(networkPolicyId))
213             getAAIClient().create(networkPolicyUri, networkPolicy)
214
215         } catch (BpmnError e) {
216             throw e
217         } catch (Exception ex) {
218             String msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
219             logger.error(msg)
220             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
221         }
222     }
223
224     void createNetworkPolicyForAllocatedResource(DelegateExecution execution,
225                                                  String ssInstanceId,
226                                                  String allottedResourceId) {
227         try {
228             AAIResourceUri allottedResourceUri =
229                     AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business()
230                             .customer(execution.getVariable("globalSubscriberId"))
231                             .serviceSubscription(execution.getVariable("subscriptionServiceType"))
232                             .serviceInstance(ssInstanceId)
233                             .allottedResource(allottedResourceId))
234
235             if (!getAAIClient().exists(allottedResourceUri)) {
236                 logger.info("ERROR: createLogicalLinksForAllocatedResource: allottedResource not exist: uri={}",
237                         allottedResourceUri)
238                 return
239             }
240
241             String networkPolicyId = UUID.randomUUID().toString()
242             createNetworkPolicy(execution, ssInstanceId, networkPolicyId)
243
244             tnNssmfUtils.attachNetworkPolicyToAllottedResource(execution, AAI_VERSION, allottedResourceUri, networkPolicyId);
245
246         } catch (BpmnError e) {
247             throw e
248         } catch (Exception ex) {
249             String msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
250             logger.error(msg)
251             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
252         }
253     }
254
255     void createLogicalLinksForAllocatedResource(DelegateExecution execution,
256                                                 String linkArrayStr, String ssInstanceId,
257                                                 String allottedResourceId) {
258         try {
259             AAIResourceUri allottedResourceUri =
260                     AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business()
261                             .customer(execution.getVariable("globalSubscriberId"))
262                             .serviceSubscription(execution.getVariable("subscriptionServiceType"))
263                             .serviceInstance(ssInstanceId)
264                             .allottedResource(allottedResourceId))
265
266             if (!getAAIClient().exists(allottedResourceUri)) {
267                 logger.info("ERROR: createLogicalLinksForAllocatedResource: allottedResource not exist: uri={}",
268                         allottedResourceUri)
269                 return
270             }
271
272             List<String> linkStrList = jsonUtil.StringArrayToList(linkArrayStr)
273
274             for (String linkStr : linkStrList) {
275                 String logicalLinkId = UUID.randomUUID().toString()
276                 String epA = jsonUtil.getJsonValue(linkStr, "transportEndpointA")
277                 String epB = jsonUtil.getJsonValue(linkStr, "transportEndpointB")
278                 String modelInvariantId = execution.getVariable("modelInvariantUuid")
279                 String modelVersionId = execution.getVariable("modelUuid")
280
281                 org.onap.aai.domain.yang.LogicalLink resource = new org.onap.aai.domain.yang.LogicalLink()
282                 resource.setLinkId(logicalLinkId)
283                 resource.setLinkName(epA)
284                 resource.setLinkName2(epB)
285                 resource.setLinkType("TsciConnectionLink")
286                 resource.setInMaint(false)
287
288                 //epA is link-name
289                 AAIResourceUri logicalLinkUri =
290                         AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().logicalLink(epA))
291                 getAAIClient().create(logicalLinkUri, resource)
292
293                 tnNssmfUtils.attachLogicalLinkToAllottedResource(execution, AAI_VERSION, allottedResourceUri, epA);
294             }
295         } catch (BpmnError e) {
296             throw e
297         } catch (Exception ex) {
298             String msg = "Exception in DoCreateTnNssiInstance.createLogicalLinksForAllocatedResource: " + ex.getMessage()
299             logger.error(msg)
300             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
301         }
302     }
303
304     void preprocessSdncAllocateTnNssiRequest(DelegateExecution execution) {
305         def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' +
306                 'execution=' + execution.getId() +
307                 ')'
308         def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
309         logger.trace('Entered ' + method)
310
311         logger.trace("STARTED preProcessSDNCActivateRequest Process")
312         try {
313             String serviceInstanceId = execution.getVariable("sliceServiceInstanceId")
314
315             String createSDNCRequest = tnNssmfUtils.buildSDNCRequest(execution, serviceInstanceId, "create")
316
317             execution.setVariable("TNNSSMF_SDNCRequest", createSDNCRequest)
318             logger.debug("Outgoing SDNCRequest is: \n" + createSDNCRequest)
319
320         } catch (Exception e) {
321             logger.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e)
322             exceptionUtil.buildAndThrowWorkflowException(execution, 1002,
323                     "Error Occured during  preProcessSDNCActivateRequest Method:\n" + e.getMessage())
324         }
325         logger.trace("COMPLETED  preProcessSDNCActivateRequest Process")
326     }
327
328
329     void validateSDNCResponse(DelegateExecution execution, String response, String method) {
330         tnNssmfUtils.validateSDNCResponse(execution, response, method)
331     }
332 }