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