Add nssiId for AllocateTNNSSI request
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeallocateCoreNSSI.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020  Telecom Italia
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
21 package org.onap.so.bpmn.infrastructure.scripts
22
23
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.aai.domain.yang.v19.AllottedResource
26 import org.onap.aai.domain.yang.v19.ServiceInstance
27 import org.onap.aaiclient.client.aai.AAIResourcesClient
28 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
29 import org.onap.aaiclient.client.aai.entities.Relationships
30 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
31 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
32 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
33 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
34 import org.onap.logging.filter.base.ONAPComponents
35 import org.onap.so.bpmn.common.scripts.ExceptionUtil
36 import org.onap.so.bpmn.common.scripts.MsoUtils
37 import org.onap.so.bpmn.common.scripts.RequestDBUtil
38 import org.onap.so.bpmn.core.UrnPropertiesReader
39 import org.onap.so.bpmn.core.json.JsonUtils
40 import org.onap.so.client.HttpClient
41 import org.onap.so.client.HttpClientFactory
42 import org.slf4j.Logger
43 import org.slf4j.LoggerFactory
44
45 import javax.ws.rs.core.Response
46
47 class DoDeallocateCoreNSSI extends DoCommonCoreNSSI {
48     private final String PREFIX ="DoDeallocateCoreNSSI"
49     private final  String ACTION = "Deallocate"
50
51     private ExceptionUtil exceptionUtil = new ExceptionUtil()
52     private RequestDBUtil requestDBUtil = new RequestDBUtil()
53     private MsoUtils utils = new MsoUtils()
54     private JsonUtils jsonUtil = new JsonUtils()
55
56     private static final Logger LOGGER = LoggerFactory.getLogger( DoDeallocateCoreNSSI.class)
57
58     /**
59      * Queries OOF for NSSI termination
60      * @param execution
61      */
62     void executeTerminateNSSIQuery(DelegateExecution execution) {
63         LOGGER.trace("${PREFIX} Start executeTerminateNSSIQuery")
64
65         String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
66
67         //Prepare auth for OOF
68         def authHeader = ""
69         String basicAuth = UrnPropertiesReader.getVariable("mso.oof.auth", execution)
70         String msokey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
71
72         String basicAuthValue = encryptBasicAuth(basicAuth, msokey)
73         if (basicAuthValue != null) {
74             String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msokey)
75             String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
76             if(errorCode == null || errorCode.isEmpty()) { // No error
77                 authHeader = responseAuthHeader
78             }
79             else {
80                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
81             }
82         } else {
83             LOGGER.error( "Unable to obtain BasicAuth - BasicAuth value null")
84             exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
85                     "value null")
86         }
87
88         //Prepare send request to OOF
89         String oofRequest = buildOOFRequest(execution)
90
91         String callOOFResponse = callOOF(urlString, authHeader, oofRequest)
92         String errorCode = jsonUtil.getJsonValue(callOOFResponse, "errorCode")
93         if(errorCode == null || errorCode.isEmpty()) { // No error
94             String oofResponse = callOOFResponse
95             String isTerminateNSSI = jsonUtil.getJsonValue(oofResponse, "terminateResponse")
96
97             execution.setVariable("isTerminateNSSI", Boolean.parseBoolean(isTerminateNSSI))
98         }
99         else {
100             LOGGER.error(jsonUtil.getJsonValue(callOOFResponse, "errorMessage"))
101             exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callOOFResponse, "errorMessage"))
102         }
103
104
105         LOGGER.trace("${PREFIX} Exit executeTerminateNSSIQuery")
106     }
107
108
109     /**
110      * Executes sync call to OOF
111      * @return OOF response
112      */
113     String callOOF(String urlString, String authHeader, String oofRequest) {
114         String errorCode = ""
115         String errorMessage = ""
116         String response = ""
117
118         try {
119             URL url = new URL(urlString + "/api/oof/terminate/nxi/v1")
120             HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.OOF)
121             httpClient.addAdditionalHeader("Authorization", authHeader)
122             httpClient.addAdditionalHeader("Accept", "application/json")
123             httpClient.addAdditionalHeader("Content-Type", "application/json")
124
125             Response httpResponse = httpClient.post(oofRequest)
126
127             int responseCode = httpResponse.getStatus()
128             LOGGER.debug("OOF sync response code is: " + responseCode)
129
130             if (responseCode != 202) { // Accepted
131                 errorCode = responseCode
132                 errorMessage = "Received a Bad Sync Response from OOF."
133
134                 response =  "{\n" +
135                         " \"errorCode\": \"${errorCode}\",\n" +
136                         " \"errorMessage\": \"${errorMessage}\"\n" +
137                         "}"
138                 //exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
139             }
140
141             if (httpResponse.hasEntity()) {
142                 response = httpResponse.readEntity(String.class)
143             }
144             else {
145                 errorCode = 500
146                 errorMessage = "No response received from OOF."
147
148                 response =  "{\n" +
149                         " \"errorCode\": \"${errorCode}\",\n" +
150                         " \"errorMessage\": \"${errorMessage}\"\n" +
151                         "}"
152             }
153         }
154         catch(Exception e) {
155             errorCode = 400
156             errorMessage = e.getMessage()
157
158             response =  "{\n" +
159                     " \"errorCode\": \"${errorCode}\",\n" +
160                     " \"errorMessage\": \"${errorMessage}\"\n" +
161                     "}"
162         }
163
164
165         return response
166     }
167
168
169     /**
170      * Builds OOF request
171      * @param execution
172      * @return
173      */
174     private String buildOOFRequest(DelegateExecution execution) {
175
176         def currentNSSI = execution.getVariable("currentNSSI")
177
178         String nssiId = currentNSSI['nssiId']
179         String requestId = execution.getVariable("mso-request-id")
180
181         String request =    "{\n" +
182                             "  \"type\": \"NSSI\",\n" +
183                             "  \"NxIId\": \"${nssiId}\",\n" +
184                             "  \"requestInfo\": {\n" +
185                             "    \"transactionId\": \"${requestId}\",\n" +
186                             "    \"requestId\": \"${requestId}\",\n" +
187                             "    \"sourceId\": \"so\",\n" +
188                             "    }\n" +
189                             "}"
190
191         return request
192     }
193
194
195
196     /**
197      * Invokes deleteServiceOrder external API
198      * @param execution
199      */
200     void deleteServiceOrder(DelegateExecution execution) {
201         LOGGER.trace("${PREFIX} Start deleteServiceOrder")
202
203         def currentNSSI = execution.getVariable("currentNSSI")
204
205         try {
206             //url:/nbi/api/v4/serviceOrder/"
207             def nbiEndpointUrl = UrnPropertiesReader.getVariable("nbi.endpoint.url", execution)
208
209             ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
210
211             String url = String.format("${nbiEndpointUrl}/api/v4/serviceOrder/%s", networkServiceInstance.getServiceInstanceId())
212
213             currentNSSI['deleteServiceOrderURL'] = url
214
215             String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
216             String basicAuth =  UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
217
218             String basicAuthValue = encryptBasicAuth(basicAuth, msoKey)
219             def authHeader = ""
220             if (basicAuthValue != null) {
221                 String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey)
222                 String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
223                 if(errorCode == null || errorCode.isEmpty()) { // No error
224                     authHeader = responseAuthHeader
225                 }
226                 else {
227                     exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
228                 }
229             } else {
230                 LOGGER.error( "Unable to obtain BasicAuth - BasicAuth value null")
231                 exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
232                         "value null")
233             }
234
235             String callDeleteServiceOrderResponse = callDeleteServiceOrder(execution, url, authHeader)
236             String errorCode = jsonUtil.getJsonValue(callDeleteServiceOrderResponse, "errorCode")
237             String deleteServcieResponse = ""
238
239             if(errorCode == null || errorCode.isEmpty()) { // No error
240                 deleteServcieResponse = callDeleteServiceOrderResponse // check the response ???
241             }
242             else {
243                 LOGGER.error(jsonUtil.getJsonValue(callDeleteServiceOrderResponse, "errorMessage"))
244                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callDeleteServiceOrderResponse, "errorMessage"))
245             }
246         } catch (any) {
247             String msg = "Exception in DoDeallocateCoreNSSI.deleteServiceOrder. " + any.getCause()
248             LOGGER.error(msg)
249             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
250         }
251
252         LOGGER.trace("${PREFIX} Exit deleteServiceOrder")
253     }
254
255
256     String callDeleteServiceOrder(DelegateExecution execution, String urlString, String authHeader) {
257         String errorCode = ""
258         String errorMessage = ""
259         String response = ""
260
261         try {
262             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(urlString), ONAPComponents.EXTERNAL)
263             httpClient.addAdditionalHeader("Authorization", authHeader)
264             httpClient.addAdditionalHeader("Accept", "application/json")
265             Response httpResponse = httpClient.delete()
266
267             if (httpResponse.hasEntity()) {
268                 response = httpResponse.readEntity(String.class)
269             }
270             else {
271                 errorCode = 500
272                 errorMessage = "No response received."
273
274                 response =  "{\n" +
275                         " \"errorCode\": \"${errorCode}\",\n" +
276                         " \"errorMessage\": \"${errorMessage}\"\n" +
277                         "}"
278             }
279         }
280         catch (any) {
281             String msg = "Exception in DoDeallocateCoreNSSI.deleteServiceOrder. " + any.getCause()
282
283             response =  "{\n" +
284                     " \"errorCode\": \"7000\",\n" +
285                     " \"errorMessage\": \"${msg}\"\n" +
286                     "}"
287         }
288
289         return response
290     }
291
292
293     /**
294      * Removes NSSI association with NSI
295      * @param execution
296      */
297     void removeNSSIAssociationWithNSI(DelegateExecution execution) {
298         LOGGER.trace("${PREFIX} Start removeNSSIAssociationWithNSI")
299
300         AAIResourcesClient client = getAAIClient()
301
302         def currentNSSI = execution.getVariable("currentNSSI")
303
304         String nssiId = currentNSSI['nssiId']
305         String nsiId = currentNSSI['nsiId']
306         String globalSubscriberId = execution.getVariable("globalSubscriberId")
307         String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
308
309         // NSSI
310         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
311         ServiceInstance nssi = currentNSSI['nssi']
312
313         String allottedResourceId = null
314
315         // Removes Allotted resource
316         List<AllottedResource> allottedResources = nssi.getAllottedResources()?.getAllottedResource()
317         if(allottedResources != null && allottedResources.size() == 1) { // Shouldn contain one allotted resource
318             allottedResourceId = allottedResources.get(0).getId()
319             allottedResources.remove(0)
320         }
321         else {
322             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No allotted resource found for NSSI id = " + nssiId)
323         }
324
325         try {
326             client.update(nssiUri, nssi)
327         }catch(Exception e){
328             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while NSSI association with NSI disconnect call: " + e.getMessage())
329         }
330
331
332         // Remove association between NSI and Allotted Resource
333         AAIResourceUri nsiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nsiId))
334         AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(nssiId).allottedResource(allottedResourceId))
335
336         try {
337             client.disconnect(nsiUri, allottedResourceUri)
338         }catch(Exception e){
339             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while NSSI association with NSI disconnect call: " + e.getMessage())
340         }
341
342         LOGGER.trace("${PREFIX} Exit removeNSSIAssociationWithNSI")
343     }
344
345
346     /**
347      * Delets NSSI Service Instance
348      * @param execution
349      */
350     void deleteNSSIServiceInstance(DelegateExecution execution) {
351         LOGGER.trace("${PREFIX} Start deleteNSSIServiceInstance")
352
353         AAIResourcesClient client = getAAIClient()
354
355         def currentNSSI = execution.getVariable("currentNSSI")
356
357         String nssiId = currentNSSI['nssiId']
358         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
359
360         try {
361             getAAIClient().delete(nssiUri)
362         }catch(Exception e){
363             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occurred while NSSI Service Instance delete call: " + e.getMessage())
364         }
365
366         LOGGER.trace("${PREFIX} Exit deleteNSSIServiceInstance")
367     }
368
369
370     /**
371      * Gets Delete Service Order progress
372      * @param execution
373      */
374     void getDeleteServiceOrderProgress(DelegateExecution execution) {
375         LOGGER.trace("${getPrefix()} Start getDeleteServiceOrderProgress")
376
377         def currentNSSI = execution.getVariable("currentNSSI")
378
379         String url = currentNSSI['deleteServiceOrderURL']
380
381         getProgress(execution, url, "deleteStatus")
382
383     }
384
385
386     @Override
387     String getPrefix() {
388         return PREFIX
389     }
390
391     @Override
392     String getAction() {
393         return ACTION
394     }
395 }