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