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