Merge "fixed some JUnits"
[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         String scriptName = execution.getVariable("scriptName")
143
144         DeAllocateNssi deAllocateNssi = new DeAllocateNssi()
145         deAllocateNssi.setNsiId(nsiId)
146         deAllocateNssi.setNssiId(nssiId)
147         deAllocateNssi.setTerminateNssiOption(0)
148         deAllocateNssi.setSnssaiList(Arrays.asList(snssai))
149         deAllocateNssi.setScriptName(scriptName)
150
151         NssiDeAllocateRequest deAllocateRequest = new NssiDeAllocateRequest()
152         deAllocateRequest.setDeAllocateNssi(deAllocateNssi)
153         deAllocateRequest.setEsrInfo(getEsrInfo(currentNSSI))
154
155         ObjectMapper mapper = new ObjectMapper()
156         String nssmfRequest = mapper.writeValueAsString(deAllocateRequest)
157
158         String urlStr = String.format("/api/rest/provMns/v1/NSS/SliceProfiles/%s",profileId)
159
160         NssiResponse nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlStr, nssmfRequest, NssiResponse.class)
161         if (nssmfResponse != null) {
162             currentNSSI['jobId']= nssmfResponse.getJobId() ?: ""
163             currentNSSI['jobProgress'] = 0
164             execution.setVariable("currentNSSI", currentNSSI)
165
166             LOGGER.debug("*****${PREFIX} Exit sendRequestToNSSMF *****")
167         } else {
168             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
169         }
170
171     }
172
173     /**
174      * send to nssmf query progress
175      * @param execution
176      */
177     void getJobStatus(DelegateExecution execution)
178     {
179         def currentNSSI = execution.getVariable("currentNSSI")
180         String jobId = currentNSSI['jobId']
181         String nssiId = currentNSSI['nssiServiceInstanceId']
182         String nsiId = currentNSSI['nsiServiceInstanceId']
183
184         JobStatusRequest jobStatusRequest = new JobStatusRequest()
185         jobStatusRequest.setNssiId(nssiId)
186         jobStatusRequest.setNsiId(nsiId)
187         jobStatusRequest.setEsrInfo(getEsrInfo(currentNSSI))
188
189         ObjectMapper mapper = new ObjectMapper()
190         String nssmfRequest = mapper.writeValueAsString(jobStatusRequest)
191
192         String urlStr = String.format("/api/rest/provMns/v1/NSS/jobs/%s", jobId)
193
194         JobStatusResponse jobStatusResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlStr, nssmfRequest, JobStatusResponse.class)
195
196         if (jobStatusResponse != null) {
197             def progress = jobStatusResponse?.getResponseDescriptor()?.getProgress()
198             if(!progress)
199             {
200                 LOGGER.error("job progress is null or empty!")
201                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Job progress from NSSMF.")
202             }
203             int oldProgress = currentNSSI['jobProgress']
204             int currentProgress = progress
205
206             execution.setVariable("isNSSIDeAllocated", (currentProgress == 100))
207             execution.setVariable("isNeedUpdateDB", (oldProgress != currentProgress))
208             currentNSSI['jobProgress'] = currentProgress
209
210             def statusDescription = jobStatusResponse?.getResponseDescriptor()?.getStatusDescription()
211             currentNSSI['statusDescription'] = statusDescription
212
213             LOGGER.debug("job status result: nsiId = ${nsiId}, nssiId=${nssiId}, oldProgress=${oldProgress}, progress = ${currentProgress}" )
214
215         } else {
216             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
217         }
218
219     }
220
221     private EsrInfo getEsrInfo(def currentNSSI)
222     {
223         String domaintype = currentNSSI['domainType']
224         String vendor = currentNSSI['vendor']
225
226         EsrInfo info = new EsrInfo()
227         info.setNetworkType(NetworkType.fromString(domaintype))
228         info.setVendor(vendor)
229         return info
230     }
231
232     /**
233      * handle job status
234      * prepare update requestdb
235      * @param execution
236      */
237     void handleJobStatus(DelegateExecution execution)
238     {
239         def currentNSSI = execution.getVariable("currentNSSI")
240         int currentProgress = currentNSSI["jobProgress"]
241         def proportion = currentNSSI['proportion']
242         def statusDes = currentNSSI["statusDescription"]
243         int progress = (currentProgress as int) == 0 ? 0 : (currentProgress as int) / 100 * (proportion as int)
244
245         OperationStatus operationStatus = new OperationStatus()
246         operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
247         operationStatus.setOperationId(currentNSSI['operationId'] as String)
248         operationStatus.setOperation("DELETE")
249         operationStatus.setResult("processing")
250         operationStatus.setProgress(progress as String)
251         operationStatus.setOperationContent(statusDes as String)
252         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
253         LOGGER.debug("update operation, currentProgress=${currentProgress}, proportion=${proportion}, progress = ${progress}" )
254     }
255
256     void timeDelay(DelegateExecution execution) {
257         try {
258             Thread.sleep(10000);
259         } catch(InterruptedException e) {
260             LOGGER.error("Time Delay exception" + e)
261         }
262     }
263
264     /**
265      * delete slice profile from aai
266      * @param execution
267      */
268     void delSliceProfileFromAAI(DelegateExecution execution)
269     {
270         LOGGER.debug("*****${PREFIX} start delSliceProfileFromAAI *****")
271         def currentNSSI = execution.getVariable("currentNSSI")
272         String nssiServiceInstanceId = currentNSSI['nssiServiceInstanceId']
273         String profileId = currentNSSI['profileId']
274         String globalSubscriberId = currentNSSI["globalSubscriberId"]
275         String serviceType = currentNSSI["serviceType"]
276
277         try
278         {
279             LOGGER.debug("delete nssiServiceInstanceId:${nssiServiceInstanceId}, profileId:${profileId}")
280             AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, globalSubscriberId, serviceType, nssiServiceInstanceId, profileId)
281             if (!getAAIClient().exists(resourceUri)) {
282                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
283             }
284             getAAIClient().delete(resourceUri)
285         }
286         catch (any)
287         {
288             String msg = "delete slice profile from aai failed! cause-"+any.getCause()
289             LOGGER.error(any.printStackTrace())
290             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
291         }
292         LOGGER.debug("*****${PREFIX} Exist delSliceProfileFromAAI *****")
293     }
294 }