Merge "removed unused imports"
[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.EsrInfo
27 import org.onap.so.beans.nsmf.JobStatusRequest
28 import org.onap.so.beans.nsmf.JobStatusResponse
29 import org.onap.so.beans.nsmf.NetworkType
30 import org.onap.so.beans.nsmf.NssiDeAllocateRequest
31 import org.onap.so.beans.nsmf.NssiResponse
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.UrnPropertiesReader
37 import org.onap.so.bpmn.core.domain.ServiceArtifact
38 import org.onap.so.bpmn.core.domain.ServiceDecomposition
39 import org.onap.so.bpmn.core.json.JsonUtils
40 import org.onap.so.client.HttpClient
41 import org.onap.aaiclient.client.aai.AAIObjectType
42 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
43 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
44 import org.onap.so.db.request.beans.OperationStatus
45 import org.slf4j.Logger
46 import org.slf4j.LoggerFactory
47
48 import javax.ws.rs.core.Response
49
50
51 class DoDeallocateNSSI extends AbstractServiceTaskProcessor
52 {
53     private final String PREFIX ="DoDeallocateNSSI"
54
55     private ExceptionUtil exceptionUtil = new ExceptionUtil()
56     private JsonUtils jsonUtil = new JsonUtils()
57     private RequestDBUtil requestDBUtil = new RequestDBUtil()
58     private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
59
60     private static final Logger LOGGER = LoggerFactory.getLogger( DoDeallocateNSSI.class)
61
62     @Override
63     void preProcessRequest(DelegateExecution execution) {
64         LOGGER.trace(" ***** ${PREFIX} Start preProcessRequest *****")
65
66         def currentNSSI = execution.getVariable("currentNSSI")
67         if (!currentNSSI) {
68             String msg = "currentNSSI is null"
69             LOGGER.error(msg)
70             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
71         }
72
73         LOGGER.trace("***** ${PREFIX} Exit preProcessRequest *****")
74     }
75
76     /**
77      *
78      * @param execution
79      */
80     void prepareDecomposeService(DelegateExecution execution)
81     {
82         LOGGER.trace(" *****${PREFIX} Start prepareDecomposeService *****")
83         try
84         {
85             def currentNSSI = execution.getVariable("currentNSSI")
86             String modelInvariantUuid = currentNSSI['modelInvariantId']
87             String modelVersionId = currentNSSI['modelVersionId']
88             String serviceModelInfo = """{
89             "modelInvariantUuid":"${modelInvariantUuid}",
90             "modelUuid":"${modelVersionId}",
91             "modelVersion":""
92              }"""
93             execution.setVariable("serviceModelInfo", serviceModelInfo)
94         }
95         catch (any)
96         {
97             String exceptionMessage = "Bpmn error encountered in deallocate nssi. Unexpected Error from method prepareDecomposeService() - " + any.getMessage()
98             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
99         }
100         LOGGER.debug(" ***** ${PREFIX} Exit prepareDecomposeService *****")
101     }
102
103     /**
104      * get vendor Info
105      * @param execution
106      */
107     void processDecomposition(DelegateExecution execution) {
108         LOGGER.debug("*****${PREFIX} start processDecomposition *****")
109
110         try {
111             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") as ServiceDecomposition
112             ServiceArtifact serviceArtifact = serviceDecomposition ?.getServiceInfo()?.getServiceArtifact()?.get(0)
113             String content = serviceArtifact.getContent()
114             String vendor = jsonUtil.getJsonValue(content, "metadata.vendor")
115             String domainType  = jsonUtil.getJsonValue(content, "metadata.domainType")
116
117             def currentNSSI = execution.getVariable("currentNSSI")
118             currentNSSI['vendor'] = vendor
119             currentNSSI['domainType'] = domainType
120             LOGGER.info("processDecomposition, current vendor-domainType:" +String.join("-", vendor, domainType))
121
122         } catch (any) {
123             String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
124             LOGGER.debug(exceptionMessage)
125             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
126         }
127         LOGGER.debug("*****${PREFIX} Exit processDecomposition *****")
128     }
129
130     /**
131      * send deallocate request to nssmf
132      * @param execution
133      */
134     void sendRequestToNSSMF(DelegateExecution execution)
135     {
136         LOGGER.debug("*****${PREFIX} start sendRequestToNSSMF *****")
137         def currentNSSI = execution.getVariable("currentNSSI")
138         String snssai= currentNSSI['snssai']
139         String profileId = currentNSSI['profileId']
140         String nssiId = currentNSSI['nssiServiceInstanceId']
141         String nsiId = currentNSSI['nsiServiceInstanceId']
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
149         NssiDeAllocateRequest deAllocateRequest = new NssiDeAllocateRequest()
150         deAllocateRequest.setDeAllocateNssi(deAllocateNssi)
151         deAllocateRequest.setEsrInfo(getEsrInfo(currentNSSI))
152
153         ObjectMapper mapper = new ObjectMapper()
154         String nssmfRequest = mapper.writeValueAsString(deAllocateRequest)
155
156         String urlStr = String.format("/api/rest/provMns/v1/NSS/SliceProfiles/%s",profileId)
157
158         NssiResponse nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlStr, nssmfRequest, NssiResponse.class)
159         if (nssmfResponse != null) {
160             currentNSSI['jobId']= nssmfResponse.getJobId() ?: ""
161             currentNSSI['jobProgress'] = 0
162             execution.setVariable("currentNSSI", currentNSSI)
163
164             LOGGER.debug("*****${PREFIX} Exit sendRequestToNSSMF *****")
165         } else {
166             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
167         }
168
169     }
170
171     /**
172      * send to nssmf query progress
173      * @param execution
174      */
175     void getJobStatus(DelegateExecution execution)
176     {
177         def currentNSSI = execution.getVariable("currentNSSI")
178         String jobId = currentNSSI['jobId']
179         String nssiId = currentNSSI['nssiServiceInstanceId']
180         String nsiId = currentNSSI['nsiServiceInstanceId']
181
182         JobStatusRequest jobStatusRequest = new JobStatusRequest()
183         jobStatusRequest.setNssiId(nssiId)
184         jobStatusRequest.setNsiId(nsiId)
185         jobStatusRequest.setEsrInfo(getEsrInfo(currentNSSI))
186
187         ObjectMapper mapper = new ObjectMapper()
188         String nssmfRequest = mapper.writeValueAsString(jobStatusRequest)
189
190         String urlStr = String.format("/api/rest/provMns/v1/NSS/jobs/%s", jobId)
191
192         JobStatusResponse jobStatusResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlStr, nssmfRequest, JobStatusResponse.class)
193
194         if (jobStatusResponse != null) {
195             def progress = jobStatusResponse?.getResponseDescriptor()?.getProgress()
196             if(!progress)
197             {
198                 LOGGER.error("job progress is null or empty!")
199                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Job progress from NSSMF.")
200             }
201             int oldProgress = currentNSSI['jobProgress']
202             int currentProgress = progress
203
204             execution.setVariable("isNSSIDeAllocated", (currentProgress == 100))
205             execution.setVariable("isNeedUpdateDB", (oldProgress != currentProgress))
206             currentNSSI['jobProgress'] = currentProgress
207
208             def statusDescription = jobStatusResponse?.getResponseDescriptor()?.getStatusDescription()
209             currentNSSI['statusDescription'] = statusDescription
210
211             LOGGER.debug("job status result: nsiId = ${nsiId}, nssiId=${nssiId}, oldProgress=${oldProgress}, progress = ${currentProgress}" )
212
213         } else {
214             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
215         }
216
217     }
218
219     private EsrInfo getEsrInfo(def currentNSSI)
220     {
221         String domaintype = currentNSSI['domainType']
222         String vendor = currentNSSI['vendor']
223
224         EsrInfo info = new EsrInfo()
225         info.setNetworkType(NetworkType.fromString(domaintype))
226         info.setVendor(vendor)
227         return info
228     }
229
230     /**
231      * handle job status
232      * prepare update requestdb
233      * @param execution
234      */
235     void handleJobStatus(DelegateExecution execution)
236     {
237         def currentNSSI = execution.getVariable("currentNSSI")
238         int currentProgress = currentNSSI["jobProgress"]
239         def proportion = currentNSSI['proportion']
240         def statusDes = currentNSSI["statusDescription"]
241         int progress = (currentProgress as int) == 0 ? 0 : (currentProgress as int) / 100 * (proportion as int)
242
243         OperationStatus operationStatus = new OperationStatus()
244         operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
245         operationStatus.setOperationId(currentNSSI['operationId'] as String)
246         operationStatus.setOperation("DELETE")
247         operationStatus.setResult("processing")
248         operationStatus.setProgress(progress as String)
249         operationStatus.setOperationContent(statusDes as String)
250         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
251         LOGGER.debug("update operation, currentProgress=${currentProgress}, proportion=${proportion}, progress = ${progress}" )
252     }
253
254     void timeDelay(DelegateExecution execution) {
255         try {
256             Thread.sleep(10000);
257         } catch(InterruptedException e) {
258             LOGGER.error("Time Delay exception" + e)
259         }
260     }
261
262     /**
263      * delete slice profile from aai
264      * @param execution
265      */
266     void delSliceProfileFromAAI(DelegateExecution execution)
267     {
268         LOGGER.debug("*****${PREFIX} start delSliceProfileFromAAI *****")
269         def currentNSSI = execution.getVariable("currentNSSI")
270         String nssiServiceInstanceId = currentNSSI['nssiServiceInstanceId']
271         String profileId = currentNSSI['profileId']
272         String globalSubscriberId = currentNSSI["globalSubscriberId"]
273         String serviceType = currentNSSI["serviceType"]
274
275         try
276         {
277             LOGGER.debug("delete nssiServiceInstanceId:${nssiServiceInstanceId}, profileId:${profileId}")
278             AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, globalSubscriberId, serviceType, nssiServiceInstanceId, profileId)
279             if (!getAAIClient().exists(resourceUri)) {
280                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
281             }
282             getAAIClient().delete(resourceUri)
283         }
284         catch (any)
285         {
286             String msg = "delete slice profile from aai failed! cause-"+any.getCause()
287             LOGGER.error(any.printStackTrace())
288             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
289         }
290         LOGGER.debug("*****${PREFIX} Exist delSliceProfileFromAAI *****")
291     }
292 }