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 / DoModifyTnNssi.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 com.fasterxml.jackson.databind.ObjectMapper
24 import groovy.json.JsonSlurper
25 import org.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.delegate.DelegateExecution
27 import org.onap.aai.domain.yang.ServiceInstance
28 import org.onap.aai.domain.yang.SliceProfile
29 import org.onap.aaiclient.client.aai.AAIObjectType
30 import org.onap.aaiclient.client.aai.AAIResourcesClient
31 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
32 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
33 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
34 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
35 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
36 import org.onap.so.bpmn.common.scripts.ExceptionUtil
37 import org.onap.so.bpmn.common.scripts.RequestDBUtil
38 import org.onap.so.bpmn.core.json.JsonUtils
39 import org.onap.so.db.request.beans.ResourceOperationStatus
40 import org.slf4j.Logger
41 import org.slf4j.LoggerFactory
42
43 import static org.apache.commons.lang3.StringUtils.isBlank
44
45 public class DoModifyTnNssi extends AbstractServiceTaskProcessor {
46     String Prefix = "TNMOD_"
47
48     ExceptionUtil exceptionUtil = new ExceptionUtil()
49     JsonUtils jsonUtil = new JsonUtils()
50     RequestDBUtil requestDBUtil = new RequestDBUtil()
51     TnNssmfUtils tnNssmfUtils = new TnNssmfUtils()
52     JsonSlurper jsonSlurper = new JsonSlurper()
53     ObjectMapper objectMapper = new ObjectMapper()
54     private static final Logger logger = LoggerFactory.getLogger(DoModifyTnNssi.class)
55
56
57     void preProcessRequest(DelegateExecution execution) {
58         logger.debug("Start preProcessRequest")
59         execution.setVariable("prefix", Prefix)
60         String msg = ""
61
62         try {
63             execution.setVariable("startTime", System.currentTimeMillis())
64             msg = tnNssmfUtils.getExecutionInputParams(execution)
65             logger.debug("Modify TN NSSI input parameters: " + msg)
66
67             execution.setVariable("prefix", Prefix)
68
69             tnNssmfUtils.setSdncCallbackUrl(execution, true)
70             logger.debug("SDNC Callback URL: " + execution.getVariable("sdncCallbackUrl"))
71
72             String additionalPropJsonStr = execution.getVariable("sliceParams")
73
74             String sliceServiceInstanceId = execution.getVariable("serviceInstanceID")
75             execution.setVariable("sliceServiceInstanceId", sliceServiceInstanceId)
76
77             String sliceServiceInstanceName = execution.getVariable("servicename")
78             execution.setVariable("sliceServiceInstanceName", sliceServiceInstanceName)
79
80             String operationId = UUID.randomUUID().toString()
81             execution.setVariable("operationId", operationId)
82
83             String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
84             String modelUuid = execution.getVariable("modelUuid")
85             //here modelVersion is not set, we use modelUuid to decompose the service.
86             def isDebugLogEnabled = true
87             execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
88             String serviceModelInfo = """{
89             "modelInvariantUuid":"${modelInvariantUuid}",
90             "modelUuid":"${modelUuid}",
91             "modelVersion":""
92              }"""
93             execution.setVariable("serviceModelInfo", serviceModelInfo)
94
95             //additional properties
96             String sliceProfile = jsonUtil.getJsonValue(additionalPropJsonStr, "sliceProfile")
97             if (isBlank(sliceProfile)) {
98                 msg = "Input sliceProfile is null"
99                 logger.debug(msg)
100                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
101             } else {
102                 execution.setVariable("sliceProfile", sliceProfile)
103             }
104
105             String transportSliceNetworks = jsonUtil.getJsonValue(additionalPropJsonStr, "transportSliceNetworks")
106             if (isBlank(transportSliceNetworks)) {
107                 msg = "Input transportSliceNetworks is null"
108                 logger.debug(msg)
109                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
110             } else {
111                 execution.setVariable("transportSliceNetworks", transportSliceNetworks)
112             }
113             logger.debug("transportSliceNetworks: " + transportSliceNetworks)
114
115             String nsiInfo = jsonUtil.getJsonValue(additionalPropJsonStr, "nsiInfo")
116             if (isBlank(nsiInfo)) {
117                 msg = "Input nsiInfo is null"
118                 logger.debug(msg)
119                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
120             } else {
121                 execution.setVariable("nsiInfo", nsiInfo)
122             }
123         } catch (BpmnError e) {
124             throw e
125         } catch (Exception ex) {
126             msg = "Exception in preProcessRequest " + ex.getMessage()
127             logger.debug(msg)
128             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
129         }
130         logger.debug("Finish preProcessRequest")
131     }
132
133
134     void deleteServiceInstance(DelegateExecution execution) {
135         try {
136             AAIResourcesClient client = getAAIClient()
137             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("subscriptionServiceType")).serviceInstance(execution.getVariable("serviceInstanceID")))
138             client.delete(uri)
139         } catch (BpmnError e) {
140             throw e
141         } catch (Exception ex) {
142             String msg = "Exception in DoDeallocateTnNssi.deleteServiceInstance. " + ex.getMessage()
143             logger.info(msg)
144             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
145         }
146     }
147
148
149     void getExistingServiceInstance(DelegateExecution execution) {
150         String serviceInstanceId = execution.getVariable("serviceInstanceID")
151
152         AAIResourcesClient resourceClient = getAAIClient()
153         AAIResourceUri ssServiceuri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(serviceInstanceId))
154
155         try {
156             if (resourceClient.exists(ssServiceuri)) {
157                 execution.setVariable("ssi_resourceLink", ssServiceuri.build().toString())
158                 org.onap.aai.domain.yang.ServiceInstance ss =
159                         resourceClient.get(org.onap.aai.domain.yang.ServiceInstance.class, ssServiceuri)
160                 org.onap.aai.domain.yang.SliceProfile sliceProfile = ss.getSliceProfiles().getSliceProfile().get(0)
161                 execution.setVariable("sliceProfileId", sliceProfile.getProfileId())
162
163                 org.onap.aai.domain.yang.AllottedResources ars = ss.getAllottedResources()
164                 List<org.onap.aai.domain.yang.AllottedResource> arList = ars.getAllottedResource()
165                 List<String> arIdList = new ArrayList<>()
166                 for (org.onap.aai.domain.yang.AllottedResource ar : arList) {
167                     String arId = ar.getId()
168                     arIdList.add(arId)
169                 }
170                 execution.setVariable("arIdList", arIdList)
171             } else {
172                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai to " +
173                         "associate allotted resource for service :" + serviceInstanceId)
174             }
175         } catch (BpmnError e) {
176             throw e;
177         } catch (Exception ex) {
178             String msg = "Exception in getServiceInstance. " + ex.getMessage()
179             logger.debug(msg)
180             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
181         }
182
183     }
184
185     public void updateTnNssiInAAI(DelegateExecution execution) {
186         getExistingServiceInstance(execution)
187
188         updateServiceInstance(execution)
189         updateSliceProfile(execution)
190         updateAllottedResource(execution)
191     }
192
193     void updateServiceInstance(DelegateExecution execution) {
194         String serviceRole = "TN"
195         String serviceType = execution.getVariable("subscriptionServiceType")
196         String sliceProfileStr = execution.getVariable("sliceProfile")
197         String ssInstanceId = execution.getVariable("sliceServiceInstanceId")
198         try {
199             org.onap.aai.domain.yang.ServiceInstance ss = new org.onap.aai.domain.yang.ServiceInstance()
200             ss.setServiceInstanceId(ssInstanceId)
201             String sliceInstanceName = execution.getVariable("sliceServiceInstanceName")
202             ss.setServiceInstanceName(sliceInstanceName)
203             ss.setServiceType(serviceType)
204             String serviceStatus = "modified"
205             ss.setOrchestrationStatus(serviceStatus)
206             String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
207             String modelUuid = execution.getVariable("modelUuid")
208             ss.setModelInvariantId(modelInvariantUuid)
209             ss.setModelVersionId(modelUuid)
210             String serviceInstanceLocationid = tnNssmfUtils.getFirstPlmnIdFromSliceProfile(sliceProfileStr)
211             ss.setServiceInstanceLocationId(serviceInstanceLocationid)
212             String snssai = tnNssmfUtils.getFirstSnssaiFromSliceProfile(sliceProfileStr)
213             ss.setEnvironmentContext(snssai)
214             ss.setServiceRole(serviceRole)
215             AAIResourcesClient client = getAAIClient()
216             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("subscriptionServiceType")).serviceInstance(ssInstanceId))
217             client.update(uri, ss)
218         } catch (BpmnError e) {
219             throw e
220         } catch (Exception ex) {
221             String msg = "Exception in DoCreateTnNssiInstance.createServiceInstance. " + ex.getMessage()
222             logger.info(msg)
223             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
224         }
225     }
226
227     void updateSliceProfile(DelegateExecution execution) {
228
229         String sliceserviceInstanceId = execution.getVariable("sliceServiceInstanceId")
230         String sliceProfileStr = execution.getVariable("sliceProfile")
231         String sliceProfileId = execution.getVariable("sliceProfileId")
232         SliceProfile sliceProfile = new SliceProfile();
233         sliceProfile.setProfileId(sliceProfileId)
234         sliceProfile.setLatency(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "latency")))
235         sliceProfile.setResourceSharingLevel(jsonUtil.getJsonValue(sliceProfileStr, "resourceSharingLevel"))
236         sliceProfile.setSNssai(tnNssmfUtils.getFirstSnssaiFromSliceProfile(sliceProfileStr))    //TODO: should be list
237
238         sliceProfile.setE2ELatency(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "latency")))
239         sliceProfile.setMaxBandwidth(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "maxBandwidth")))
240
241         //TODO: new API
242         sliceProfile.setReliability(new Object())
243         try {
244             AAIResourcesClient client = getAAIClient()
245             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("subscriptionServiceType")).serviceInstance(sliceserviceInstanceId).sliceProfile(sliceProfileId))
246             client.update(uri, sliceProfile)
247
248         } catch (BpmnError e) {
249             throw e
250         } catch (Exception ex) {
251             String msg = "Exception in updateSliceProfile. " + ex.getMessage()
252             logger.info(msg)
253             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
254         }
255     }
256
257     void updateAllottedResource(DelegateExecution execution) {
258         String serviceInstanceId = execution.getVariable('serviceInstanceID')
259
260         List<String> arIdList = execution.getVariable("arIdList")
261         try {
262             for (String arId : arIdList) {
263                 AAIResourceUri arUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("subscriptionServiceType")).serviceInstance(serviceInstanceId).allottedResource(arId))
264
265                 getAAIClient().delete(arUri)
266             }
267
268             List<String> networkStrList = jsonUtil.StringArrayToList(execution.getVariable("transportSliceNetworks"))
269
270             for (String networkStr : networkStrList) {
271                 String allottedResourceId = UUID.randomUUID().toString()
272                 AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("subscriptionServiceType")).serviceInstance(execution.getVariable("sliceserviceInstanceId")).allottedResource(allottedResourceId))
273                 execution.setVariable("allottedResourceUri", allottedResourceUri)
274                 String modelInvariantId = execution.getVariable("modelInvariantUuid")
275                 String modelVersionId = execution.getVariable("modelUuid")
276
277                 org.onap.aai.domain.yang.AllottedResource resource = new org.onap.aai.domain.yang.AllottedResource()
278                 resource.setId(allottedResourceId)
279                 resource.setType("TsciNetwork")
280                 resource.setAllottedResourceName("network_" + execution.getVariable("sliceServiceInstanceName"))
281                 resource.setModelInvariantId(modelInvariantId)
282                 resource.setModelVersionId(modelVersionId)
283                 getAAIClient().create(allottedResourceUri, resource)
284
285                 String linkArrayStr = jsonUtil.getJsonValue(networkStr, "connectionLinks")
286                 createLogicalLinksForAllocatedResource(execution, linkArrayStr, serviceInstanceId, allottedResourceId)
287             }
288
289         } catch (Exception ex) {
290             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception in createAaiAR " + ex.getMessage())
291         }
292     }
293
294     void createLogicalLinksForAllocatedResource(DelegateExecution execution,
295                                                 String linkArrayStr, String serviceInstanceId,
296                                                 String allottedResourceId) {
297
298         try {
299             List<String> linkStrList = jsonUtil.StringArrayToList(linkArrayStr)
300
301             for (String linkStr : linkStrList) {
302                 String logicalLinkId = UUID.randomUUID().toString()
303                 String epA = jsonUtil.getJsonValue(linkStr, "transportEndpointA")
304                 String epB = jsonUtil.getJsonValue(linkStr, "transportEndpointB")
305                 String modelInvariantId = execution.getVariable("modelInvariantUuid")
306                 String modelVersionId = execution.getVariable("modelUuid")
307
308                 org.onap.aai.domain.yang.LogicalLink resource = new org.onap.aai.domain.yang.LogicalLink()
309                 resource.setLinkId(logicalLinkId)
310                 resource.setLinkName(epA)
311                 resource.setLinkName2(epB)
312                 resource.setModelInvariantId(modelInvariantId)
313                 resource.setModelVersionId(modelVersionId)
314
315                 AAIResourceUri logicalLinkUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().logicalLink(logicalLinkId))
316                 getAAIClient().create(logicalLinkUri, resource)
317             }
318         } catch (Exception ex) {
319             exceptionUtil.buildAndThrowWorkflowException(execution, 7000,
320                     "Exception in createLogicalLinksForAllocatedResource" + ex.getMessage())
321         }
322     }
323
324
325     void preprocessSdncModifyTnNssiRequest(DelegateExecution execution) {
326         def method = getClass().getSimpleName() + '.preprocessSdncModifyTnNssiRequest(' +
327                 'execution=' + execution.getId() + ')'
328         def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
329         logger.trace('Entered ' + method)
330
331         try {
332             String serviceInstanceId = execution.getVariable("serviceInstanceID")
333
334             String sdncRequest = tnNssmfUtils.buildSDNCRequest(execution, serviceInstanceId, "modify")
335
336             execution.setVariable("TNNSSMF_SDNCRequest", sdncRequest)
337             logger.debug("Outgoing SDNCRequest is: \n" + sdncRequest)
338
339         } catch (Exception e) {
340             logger.debug("Exception Occured Processing preprocessSdncModifyTnNssiRequest. Exception is:\n" + e)
341             exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during  preProcessSDNCActivateRequest Method:\n" + e.getMessage())
342         }
343         logger.trace("COMPLETED preprocessSdncModifyTnNssiRequest Process")
344     }
345
346
347     void validateSDNCResponse(DelegateExecution execution, String response, String method) {
348         tnNssmfUtils.validateSDNCResponse(execution, response, method)
349     }
350
351
352     void updateAAIOrchStatus(DelegateExecution execution) {
353         logger.debug("Start updateAAIOrchStatus")
354         String sliceServiceInstanceId = execution.getVariable("sliceServiceInstanceId")
355         String orchStatus = execution.getVariable("orchestrationStatus")
356
357         try {
358             ServiceInstance si = new ServiceInstance()
359             si.setOrchestrationStatus(orchStatus)
360             AAIResourcesClient client = getAAIClient()
361             AAIResourceUri uri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(sliceServiceInstanceId))
362             client.update(uri, si)
363         } catch (BpmnError e) {
364             throw e
365         } catch (Exception ex) {
366             String msg = "Exception in CreateSliceService.updateAAIOrchStatus " + ex.getMessage()
367             logger.info(msg)
368             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
369         }
370
371         logger.debug("Finish updateAAIOrchStatus")
372     }
373
374     void prepareUpdateJobStatus(DelegateExecution execution,
375                                 String status,
376                                 String progress,
377                                 String statusDescription) {
378         String serviceId = execution.getVariable("serviceInstanceID")
379         String jobId = execution.getVariable("jobId")
380         String nsiId = execution.getVariable("nsiId")
381
382         ResourceOperationStatus roStatus = new ResourceOperationStatus()
383         roStatus.setServiceId(serviceId)
384         roStatus.setOperationId(jobId)
385         roStatus.setResourceTemplateUUID(nsiId)
386         roStatus.setOperType("Modify")
387         roStatus.setProgress(progress)
388         roStatus.setStatus(status)
389         roStatus.setStatusDescription(statusDescription)
390         requestDBUtil.prepareUpdateResourceOperationStatus(execution, roStatus)
391     }
392
393 }
394