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