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