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