Merge branch 'recursive-orch'
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeallocateTnNssi.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved.
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 groovy.json.JsonSlurper
25 import org.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.delegate.DelegateExecution
27 import org.onap.aai.domain.yang.ServiceInstance
28 import org.onap.aaiclient.client.aai.AAIResourcesClient
29 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
30 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
31 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
32 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
33 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
34 import org.onap.so.bpmn.common.scripts.ExceptionUtil
35 import org.onap.so.bpmn.common.scripts.RequestDBUtil
36 import org.onap.so.bpmn.core.json.JsonUtils
37 import org.onap.so.bpmn.core.UrnPropertiesReader
38 import org.onap.so.bpmn.common.scripts.OofUtils
39 import org.onap.so.client.HttpClient
40 import org.onap.so.client.HttpClientFactory
41 import org.onap.so.client.oof.adapter.beans.payload.OofRequest
42 import javax.ws.rs.core.Response
43 import org.onap.logging.filter.base.ONAPComponents
44 import org.onap.so.db.request.beans.ResourceOperationStatus
45 import org.slf4j.Logger
46 import org.slf4j.LoggerFactory
47
48 import static org.apache.commons.lang3.StringUtils.isBlank
49 import static org.apache.commons.lang3.StringUtils.isEmpty
50
51 class DoDeallocateTnNssi extends AbstractServiceTaskProcessor {
52     String Prefix = "TNDEALLOC_"
53
54     ExceptionUtil exceptionUtil = new ExceptionUtil()
55     JsonUtils jsonUtil = new JsonUtils()
56     RequestDBUtil requestDBUtil = new RequestDBUtil()
57     TnNssmfUtils tnNssmfUtils = new TnNssmfUtils()
58     OofUtils oofUtils = new OofUtils()
59     JsonSlurper jsonSlurper = new JsonSlurper()
60     ObjectMapper objectMapper = new ObjectMapper()
61     private static final Logger logger = LoggerFactory.getLogger(DoDeallocateTnNssi.class)
62
63
64     void preProcessRequest(DelegateExecution execution) {
65         logger.debug("Start preProcessRequest")
66
67         execution.setVariable("startTime", System.currentTimeMillis())
68         String msg = tnNssmfUtils.getExecutionInputParams(execution)
69         logger.debug("Deallocate TN NSSI input parameters: " + msg)
70
71         execution.setVariable("prefix", Prefix)
72
73         tnNssmfUtils.setSdncCallbackUrl(execution, true)
74         logger.debug("SDNC Callback URL: " + execution.getVariable("sdncCallbackUrl"))
75
76         String sliceServiceInstanceId = execution.getVariable("serviceInstanceID")
77         execution.setVariable("sliceServiceInstanceId", sliceServiceInstanceId)
78
79         String sliceServiceInstanceName = execution.getVariable("servicename")
80         execution.setVariable("sliceServiceInstanceName", sliceServiceInstanceName)
81
82         String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
83         String modelUuid = execution.getVariable("modelUuid")
84         if (isEmpty(modelUuid)) {
85             modelUuid = tnNssmfUtils.getModelUuidFromServiceInstance(execution.getVariable("serviceInstanceID"))
86         }
87         def isDebugLogEnabled = true
88         execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
89         String serviceModelInfo = """{
90             "modelInvariantUuid":"${modelInvariantUuid}",
91             "modelUuid":"${modelUuid}",
92             "modelVersion":""
93              }"""
94         execution.setVariable("serviceModelInfo", serviceModelInfo)
95
96         String additionalPropJsonStr = execution.getVariable("sliceParams")
97         if (isBlank(additionalPropJsonStr) ||
98                 isBlank(tnNssmfUtils.setExecVarFromJsonIfExists(execution,
99                         additionalPropJsonStr,
100                         "enableSdnc", "enableSdnc"))) {
101             tnNssmfUtils.setEnableSdncConfig(execution)
102         }
103         if (isBlank(additionalPropJsonStr) ||
104                 isBlank(tnNssmfUtils.setExecVarFromJsonIfExists(execution,
105                         additionalPropJsonStr,
106                         "enableOof", "enableOof"))) {
107             tnNssmfUtils.setEnableOofConfig(execution)
108         }
109
110                 String nsiId = jsonUtil.getJsonValue(additionalPropJsonStr, "nsiId")
111         execution.setVariable("nsiId", nsiId)
112         logger.debug("Finish preProcessRequest")
113     }
114
115     void prepareOOFNssiTerminationRequest(DelegateExecution execution) {
116         logger.debug("Start prepareOOFTnNssiTerminationRequest")
117                 String requestId = execution.getVariable("msoRequestId")
118                 String messageType = "TN_NSSITermination"
119                 String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
120                 String serviceInstanceId = execution.getVariable("sliceServiceInstanceId")
121
122         String relatedNsiId = execution.getVariable("nsiId")
123
124                 String oofRequest = oofUtils.buildTerminateNxiRequest(requestId,serviceInstanceId, "NSSI",messageType,relatedNsiId)
125                 execution.setVariable("oofTnNssiPayload", oofRequest)
126                 logger.debug("Finish prepareOOFTnNssiTerminationRequest")
127     }
128
129     void performOofNSSITerminationCall(DelegateExecution execution) {
130         boolean terminateTnNSSI = callOofAdapter(execution,execution.getVariable("oofTnNssiPayload"))
131                 execution.setVariable("terminateTnNSSI", terminateTnNSSI)
132     }
133
134     /**
135          * @param execution
136          * @param oofRequest - Request payload to be sent to adapter
137          * @return
138          */
139         boolean callOofAdapter(DelegateExecution execution, Object oofRequest) {
140                 logger.debug("Start callOofAdapter")
141                 String requestId = execution.getVariable("msoRequestId")
142                 String oofAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.oof.endpoint", execution)
143                 URL requestUrl = new URL(oofAdapterEndpoint)
144                 OofRequest oofPayload = new OofRequest()
145                 oofPayload.setApiPath("/api/oof/terminate/nxi/v1")
146                 oofPayload.setRequestDetails(oofRequest)
147                 String requestJson = objectMapper.writeValueAsString(oofPayload)
148                 logger.debug("Calling OOF adapter  : ${requestUrl} with payload : ${requestJson}")
149                 HttpClient httpClient = new HttpClientFactory().newJsonClient(requestUrl, ONAPComponents.EXTERNAL)
150                 Response httpResponse = httpClient.post(requestJson)
151                 int responseCode = httpResponse.getStatus()
152                 logger.debug("OOF sync response code is: " + responseCode)
153                 if(responseCode < 200 || responseCode >= 300){
154                         logger.debug("OOF request failed with reason : " + httpResponse)
155                         exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
156                 }else {
157                         Map<String,Object> response = objectMapper.readValue(httpResponse.getEntity(),Map.class)
158                         boolean terminateResponse =  response.get("terminateResponse")
159                         if(!terminateResponse) {
160                                 logger.debug("Terminate response is false because " + response.get("reason"))
161                         }
162                         return terminateResponse
163                 }
164         }
165
166     void preprocessSdncDeallocateTnNssiRequest(DelegateExecution execution) {
167         def method = getClass().getSimpleName() + '.preprocessSdncDeallocateTnNssiRequest(' +
168                 'execution=' + execution.getId() + ')'
169         def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
170         logger.trace('Entered ' + method)
171
172         try {
173             String serviceInstanceId = execution.getVariable("serviceInstanceID")
174
175             String sdncRequest = tnNssmfUtils.buildSDNCRequest(execution, serviceInstanceId, "delete")
176
177             execution.setVariable("TNNSSMF_SDNCRequest", sdncRequest)
178             logger.debug("Outgoing SDNCRequest is: \n" + sdncRequest)
179
180         } catch (Exception e) {
181             logger.debug("Exception Occured Processing preprocessSdncDeallocateTnNssiRequest. Exception is:\n" + e)
182             exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during  preProcessSDNCActivateRequest Method:\n" + e.getMessage())
183         }
184         logger.trace("COMPLETED preprocessSdncDeallocateTnNssiRequest Process")
185     }
186
187
188     void validateSDNCResponse(DelegateExecution execution, String response, String method) {
189         tnNssmfUtils.validateSDNCResponse(execution, response, method)
190     }
191
192     void deleteServiceInstance(DelegateExecution execution) {
193         try {
194             AAIResourcesClient client = getAAIClient()
195             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("subscriptionServiceType")).serviceInstance(execution.getVariable("serviceInstanceID")))
196             client.delete(uri)
197         } catch (BpmnError e) {
198             throw e
199         } catch (Exception ex) {
200             String msg = "Exception in DoDeallocateTnNssi.deleteServiceInstance. " + ex.getMessage()
201             logger.info(msg)
202             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
203         }
204     }
205
206     public void updateAAIOrchStatus(DelegateExecution execution) {
207         logger.debug("Start updateAAIOrchStatus")
208         String tnNssiId = execution.getVariable("sliceServiceInstanceId")
209         String orchStatus = execution.getVariable("orchestrationStatus")
210
211         try {
212             ServiceInstance si = new ServiceInstance()
213             si.setOrchestrationStatus(orchStatus)
214             AAIResourcesClient client = getAAIClient()
215             AAIResourceUri uri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(tnNssiId))
216             client.update(uri, si)
217         } catch (BpmnError e) {
218             throw e
219         } catch (Exception ex) {
220             String msg = "Exception in CreateSliceService.updateAAIOrchStatus " + ex.getMessage()
221             logger.info(msg)
222             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
223         }
224
225         logger.debug("Finish updateAAIOrchStatus")
226     }
227
228     void prepareUpdateJobStatus(DelegateExecution execution,
229                                 String status,
230                                 String progress,
231                                 String statusDescription) {
232         String ssInstanceId = execution.getVariable("sliceServiceInstanceId")
233         String modelUuid = execution.getVariable("modelUuid")
234         String jobId = execution.getVariable("jobId")
235         String nsiId = execution.getVariable("nsiId")
236
237         ResourceOperationStatus roStatus = tnNssmfUtils.buildRoStatus(modelUuid, ssInstanceId,
238                 jobId, nsiId, "DEALLOCATE", status, progress, statusDescription)
239
240         logger.debug("DoDeallocateTnNssi: roStatus={}", roStatus)
241         requestDBUtil.prepareUpdateResourceOperationStatus(execution, roStatus)
242     }
243 }