removed references to AAIObjectType
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeallocateNSSI.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  # Copyright (c) 2019, CMCC Technologies Co., Ltd.
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 package org.onap.so.bpmn.infrastructure.scripts
21
22 import org.camunda.bpm.engine.delegate.DelegateExecution
23 import org.json.JSONObject
24 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
25 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
26 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
27 import org.onap.so.beans.nsmf.DeAllocateNssi
28 import org.onap.so.beans.nsmf.EsrInfo
29 import org.onap.so.beans.nsmf.NetworkType
30 import org.onap.so.beans.nsmf.NssiResponse
31 import org.onap.so.beans.nsmf.ServiceInfo
32 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
33 import org.onap.so.bpmn.common.scripts.ExceptionUtil
34 import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
35 import org.onap.so.bpmn.common.scripts.RequestDBUtil
36 import org.onap.so.bpmn.core.domain.ServiceArtifact
37 import org.onap.so.bpmn.core.domain.ServiceDecomposition
38 import org.onap.so.bpmn.core.json.JsonUtils
39 import org.onap.so.db.request.beans.OperationStatus
40 import org.slf4j.Logger
41 import org.slf4j.LoggerFactory
42
43
44 class DoDeallocateNSSI extends AbstractServiceTaskProcessor
45 {
46     private final String PREFIX ="DoDeallocateNSSI"
47
48     private ExceptionUtil exceptionUtil = new ExceptionUtil()
49     private JsonUtils jsonUtil = new JsonUtils()
50     private RequestDBUtil requestDBUtil = new RequestDBUtil()
51     private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
52
53     private static final Logger LOGGER = LoggerFactory.getLogger( DoDeallocateNSSI.class)
54
55     @Override
56     void preProcessRequest(DelegateExecution execution) {
57         LOGGER.trace(" ***** ${PREFIX} Start preProcessRequest *****")
58
59         def currentNSSI = execution.getVariable("currentNSSI")
60         if (!currentNSSI) {
61             String msg = "currentNSSI is null"
62             LOGGER.error(msg)
63             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
64         }
65
66         LOGGER.trace("***** ${PREFIX} Exit preProcessRequest *****")
67     }
68
69     /**
70      *
71      * @param execution
72      */
73     void prepareDecomposeService(DelegateExecution execution)
74     {
75         LOGGER.trace(" *****${PREFIX} Start prepareDecomposeService *****")
76         try
77         {
78             def currentNSSI = execution.getVariable("currentNSSI")
79             String modelInvariantUuid = currentNSSI['modelInvariantId']
80             String modelVersionId = currentNSSI['modelVersionId']
81             String serviceModelInfo = """{
82             "modelInvariantUuid":"${modelInvariantUuid}",
83             "modelUuid":"${modelVersionId}",
84             "modelVersion":""
85              }"""
86             execution.setVariable("serviceModelInfo", serviceModelInfo)
87         }
88         catch (any)
89         {
90             String exceptionMessage = "Bpmn error encountered in deallocate nssi. Unexpected Error from method prepareDecomposeService() - " + any.getMessage()
91             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
92         }
93         LOGGER.debug(" ***** ${PREFIX} Exit prepareDecomposeService *****")
94     }
95
96     /**
97      * get vendor Info
98      * @param execution
99      */
100     void processDecomposition(DelegateExecution execution) {
101         LOGGER.debug("*****${PREFIX} start processDecomposition *****")
102
103         try {
104             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") as ServiceDecomposition
105             ServiceArtifact serviceArtifact = serviceDecomposition ?.getServiceInfo()?.getServiceArtifact()?.get(0)
106             String content = serviceArtifact.getContent()
107             String vendor = jsonUtil.getJsonValue(content, "metadata.vendor")
108             String domainType  = jsonUtil.getJsonValue(content, "metadata.domainType")
109
110             def currentNSSI = execution.getVariable("currentNSSI")
111             currentNSSI['vendor'] = vendor
112             currentNSSI['domainType'] = domainType
113             LOGGER.info("processDecomposition, current vendor-domainType:" +String.join("-", vendor, domainType))
114
115         } catch (any) {
116             String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
117             LOGGER.debug(exceptionMessage)
118             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
119         }
120         LOGGER.debug("*****${PREFIX} Exit processDecomposition *****")
121     }
122     
123     /**
124      * send deallocate request to nssmf
125      * @param execution
126      */
127     void sendRequestToNSSMF(DelegateExecution execution)
128     {
129         LOGGER.debug("*****${PREFIX} start sendRequestToNSSMF *****")
130         def currentNSSI = execution.getVariable("currentNSSI")
131         String snssai= currentNSSI['snssai']
132         String profileId = currentNSSI['profileId']
133         String nssiId = currentNSSI['nssiServiceInstanceId']
134         String nsiId = currentNSSI['nsiServiceInstanceId']
135         String scriptName = execution.getVariable("scriptName")
136         boolean modifyAction = execution.getVariable("terminateNSI")
137
138         String serviceInvariantUuid = currentNSSI['modelInvariantId']
139         String serviceUuid = currentNSSI['modelVersionId']
140         String globalSubscriberId = currentNSSI['globalSubscriberId']
141         String subscriptionServiceType = execution.getVariable("serviceType")
142         
143         DeAllocateNssi deAllocateNssi = new DeAllocateNssi()
144         deAllocateNssi.setNsiId(nsiId)
145         deAllocateNssi.setNssiId(nssiId)
146         deAllocateNssi.setTerminateNssiOption(0)
147         deAllocateNssi.setSnssaiList(Arrays.asList(snssai))
148         deAllocateNssi.setScriptName(scriptName)
149         deAllocateNssi.setSliceProfileId(profileId)
150         deAllocateNssi.setModifyAction(modifyAction)
151         
152         ServiceInfo serviceInfo = new ServiceInfo()
153         serviceInfo.setServiceInvariantUuid(serviceInvariantUuid)
154         serviceInfo.setServiceUuid(serviceUuid)
155         serviceInfo.setGlobalSubscriberId(globalSubscriberId)
156         serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
157         
158         EsrInfo esrInfo = getEsrInfo(currentNSSI)
159         
160         execution.setVariable("deAllocateNssi",deAllocateNssi)
161         execution.setVariable("esrInfo",esrInfo)
162         execution.setVariable("serviceInfo",serviceInfo)
163         String nssmfRequest = """
164                 {
165                   "deAllocateNssi": "${execution.getVariable("deAllocateNssi") as JSONObject}",
166                   "esrInfo":  ${execution.getVariable("esrInfo") as JSONObject},
167                   "serviceInfo": ${execution.getVariable("serviceInfo") as JSONObject}
168                 }
169               """
170
171         String urlStr = String.format("/api/rest/provMns/v1/NSS/nssi/%s",nssiId)
172
173         NssiResponse nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlStr, nssmfRequest, NssiResponse.class)
174         if (nssmfResponse != null) {
175             currentNSSI['jobId']= nssmfResponse.getJobId() ?: "" 
176             currentNSSI['jobProgress'] = 0            
177             execution.setVariable("currentNSSI", currentNSSI)    
178             } 
179             else {
180             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
181         }
182         LOGGER.debug("*****${PREFIX} Exit sendRequestToNSSMF *****")
183     }
184
185 /**
186      * send to nssmf query progress
187      * @param execution
188      */
189     void prepareJobStatusRequest(DelegateExecution execution)
190     {
191         def currentNSSI = execution.getVariable("currentNSSI")
192         String jobId = currentNSSI['jobId']
193         String nssiId = currentNSSI['nssiServiceInstanceId']
194         String nsiId = currentNSSI['nsiServiceInstanceId']
195         String serviceInvariantUuid = currentNSSI['modelInvariantId']
196         String serviceUuid = currentNSSI['modelVersionId']
197         String globalSubscriberId = currentNSSI['globalSubscriberId']
198         String subscriptionServiceType = execution.getVariable("serviceType")
199         String sST =  currentNSSI['sST']
200         String PLMNIdList = currentNSSI['PLMNIdList']
201         String nssiName = currentNSSI['nssiName']
202         
203         execution.setVariable("responseId", "3")
204         execution.setVariable("esrInfo", getEsrInfo(currentNSSI))
205         execution.setVariable("jobId", jobId)
206         
207         Map<String, ?> serviceInfoMap = new HashMap<>()
208         serviceInfoMap.put("nssiId", nssiId)
209         serviceInfoMap.put("nsiId", nsiId)
210         serviceInfoMap.put("nssiName", nssiName)
211         serviceInfoMap.put("sST", sST)
212         serviceInfoMap.put("PLMNIdList", PLMNIdList)
213         serviceInfoMap.put("globalSubscriberId", globalSubscriberId)
214         serviceInfoMap.put("subscriptionServiceType", subscriptionServiceType)
215         serviceInfoMap.put("serviceInvariantUuid", serviceInvariantUuid)
216         serviceInfoMap.put("serviceUuid", serviceUuid)
217     
218         execution.setVariable("serviceInfo", serviceInfoMap)
219     }
220
221     
222     /**
223      * send to nssmf query progress
224      * @param execution
225      */
226     void handleJobStatus(DelegateExecution execution)
227     {
228         try 
229         {
230         String jobStatusResponse = execution.getVariable("responseDescriptor")
231         String status = jsonUtil.getJsonValue(jobStatusResponse,"status")
232         def statusDescription = jsonUtil.getJsonValue(jobStatusResponse,"statusDescription")
233         def progress = jsonUtil.getJsonValue(jobStatusResponse,"progress")
234         if(!status.equalsIgnoreCase("failed"))
235         {
236             if(!progress)
237             {
238                 LOGGER.error("job progress is null or empty!")
239                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Job progress from NSSMF.")
240             }
241             int oldProgress = currentNSSI['jobProgress']
242             int currentProgress = progress
243
244             execution.setVariable("isNSSIDeAllocated", (currentProgress == 100))
245             execution.setVariable("isNeedUpdateDB", (oldProgress != currentProgress))
246             currentNSSI['jobProgress'] = currentProgress
247             currentNSSI['status'] = status
248             currentNSSI['statusDescription'] = statusDescription
249
250             LOGGER.debug("job status result: nsiId = ${nsiId}, nssiId=${nssiId}, oldProgress=${oldProgress}, progress = ${currentProgress}" )
251         }
252           else {
253             execution.setVariable("isNeedUpdateDB", "true")
254             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
255         }
256         }
257         catch (any)
258         {
259             String msg = "Received a Bad Response from NSSMF." cause-"+any.getCause()"
260             LOGGER.error(any.printStackTrace())
261             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
262         }
263     }
264
265     private EsrInfo getEsrInfo(def currentNSSI)
266     {
267         String domaintype = currentNSSI['domainType']
268         String vendor = currentNSSI['vendor']
269         
270         EsrInfo info = new EsrInfo()
271         info.setNetworkType(NetworkType.fromString(domaintype))
272         info.setVendor(vendor)
273         return info
274     }
275
276  /**
277      * handle job status
278      * prepare update requestdb
279      * @param execution
280      */
281     void prepareUpdateOperationStatus(DelegateExecution execution)
282     {
283         def currentNSSI = execution.getVariable("currentNSSI")
284         int currentProgress = currentNSSI["jobProgress"]
285         def proportion = currentNSSI['proportion']
286         def statusDes = currentNSSI["statusDescription"]
287         int progress = (currentProgress as int) == 0 ? 0 : (currentProgress as int) / 100 * (proportion as int)
288         def status = currentNSSI['status']
289         
290         OperationStatus operationStatus = new OperationStatus()
291         operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
292         operationStatus.setOperationId(currentNSSI['operationId'] as String)
293         operationStatus.setOperation("DELETE")
294         operationStatus.setResult(status as String)
295         operationStatus.setProgress(progress as String)
296         operationStatus.setOperationContent(statusDes as String)
297         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
298         LOGGER.debug("update operation, currentProgress=${currentProgress}, proportion=${proportion}, progress = ${progress}" )
299     }
300     
301     /**
302      * delete slice profile from aai
303      * @param execution
304      */
305     void delSliceProfileFromAAI(DelegateExecution execution)
306     {
307         LOGGER.debug("*****${PREFIX} start delSliceProfileFromAAI *****")
308         def currentNSSI = execution.getVariable("currentNSSI")
309         String nssiServiceInstanceId = currentNSSI['nssiServiceInstanceId']
310         String profileId = currentNSSI['profileId']
311         String globalSubscriberId = currentNSSI["globalSubscriberId"]
312         String serviceType = currentNSSI["serviceType"]
313
314         try
315         {
316             LOGGER.debug("delete nssiServiceInstanceId:${nssiServiceInstanceId}, profileId:${profileId}")
317             AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(
318                 AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(serviceType).serviceInstance(nssiServiceInstanceId).sliceProfile(profileId))
319             if (!getAAIClient().exists(resourceUri)) {
320                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
321             }
322             getAAIClient().delete(resourceUri)
323         }
324         catch (any)
325         {
326             String msg = "delete slice profile from aai failed! cause-"+any.getCause()
327             LOGGER.error(any.printStackTrace())
328             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
329         }
330         LOGGER.debug("*****${PREFIX} Exist delSliceProfileFromAAI *****")
331     }
332 }