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