Merge "Add the query to AAI for SI with customer info"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeleteVFCNetworkServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - SO
4  * ================================================================================
5  * Copyright (C) 2017 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 org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
26 import org.onap.so.bpmn.common.scripts.ExceptionUtil
27 import org.onap.so.bpmn.core.json.JsonUtils
28 import org.onap.so.client.HttpClient
29 import org.onap.so.client.aai.AAIObjectType
30 import org.onap.so.client.aai.entities.uri.AAIResourceUri
31 import org.onap.so.client.aai.entities.uri.AAIUriFactory
32 import org.onap.so.logger.MessageEnum
33 import org.onap.so.logger.MsoLogger
34 import org.onap.so.utils.TargetEntity
35 import org.onap.so.bpmn.core.UrnPropertiesReader
36
37 import javax.ws.rs.core.Response
38 /**
39  * This groovy class supports the <class>DoDeleteVFCNetworkServiceInstance.bpmn</class> process.
40  * flow for E2E ServiceInstance Delete
41  */
42 public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProcessor {
43         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVFCNetworkServiceInstance.class);
44
45     ExceptionUtil exceptionUtil = new ExceptionUtil()
46
47     JsonUtils jsonUtil = new JsonUtils()
48
49     /**
50      * Pre Process the BPMN Flow Request
51      * Inclouds:
52      * generate the nsOperationKey
53      */
54     public void preProcessRequest (DelegateExecution execution) {
55
56         String msg = ""
57         msoLogger.trace("preProcessRequest() ")
58         try {
59             //deal with operation key
60             String globalSubscriberId = execution.getVariable("globalSubscriberId")
61             msoLogger.info("globalSubscriberId:" + globalSubscriberId)
62             String serviceType = execution.getVariable("serviceType")
63             msoLogger.info("serviceType:" + serviceType)
64             String serviceId = execution.getVariable("serviceId")
65             msoLogger.info("serviceId:" + serviceId)
66             String operationId = execution.getVariable("operationId")
67             msoLogger.info("serviceType:" + serviceType)
68             String nodeTemplateUUID = execution.getVariable("resourceTemplateId")
69             msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID)
70             String nsInstanceId = execution.getVariable("resourceInstanceId")
71             msoLogger.info("nsInstanceId:" + nsInstanceId)
72             execution.setVariable("nsInstanceId",nsInstanceId)
73             String nsOperationKey = """{
74             "globalSubscriberId":"${globalSubscriberId}",
75             "serviceType":"${serviceType}",
76             "serviceId":"${serviceId}",
77             "operationId":"${operationId}",
78             "nodeTemplateUUID":"${nodeTemplateUUID}"
79              }"""
80             execution.setVariable("nsOperationKey", nsOperationKey);
81             msoLogger.info("nsOperationKey:" + nsOperationKey)
82
83             String vfcAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.vfc.rest.endpoint", execution)
84                         
85             if (vfcAdapterUrl == null || vfcAdapterUrl.isEmpty()) {
86                 msg = getProcessKey(execution) + ': mso:adapters:vfcc:rest:endpoint URN mapping is not defined'
87                 msoLogger.debug(msg)
88             }
89  
90             while (vfcAdapterUrl.endsWith('/')) {
91                 vfcAdapterUrl = vfcAdapterUrl.substring(0, vfcAdapterUrl.length()-1)
92             }
93                         
94             execution.setVariable("vfcAdapterUrl", vfcAdapterUrl)
95
96         } catch (BpmnError e) {
97             throw e;
98         } catch (Exception ex){
99             msg = "Exception in preProcessRequest " + ex.getMessage()
100             msoLogger.info(msg)
101             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
102         }
103         msoLogger.trace("Exit preProcessRequest ")
104         }
105
106     /**
107      * unwind NS from AAI relationship
108      */
109     public void deleteNSRelationship(DelegateExecution execution) {
110         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
111         utils.log("INFO"," ***** deleteNSRelationship *****",  isDebugEnabled)
112         String nsInstanceId = execution.getVariable("resourceInstanceId")
113         if(nsInstanceId == null || nsInstanceId == ""){
114             utils.log("INFO"," Delete NS failed",  isDebugEnabled)
115             return
116         }
117         String globalSubscriberId = execution.getVariable("globalSubscriberId")
118         String serviceType = execution.getVariable("serviceType")
119         String serviceId = execution.getVariable("serviceId")
120         AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceId)
121         AAIResourceUri nsServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, nsInstanceId)
122         try {
123             getAAIClient().disconnect(serviceInstanceUri, nsServiceInstanceUri)
124         }catch(Exception e){
125             exceptionUtil.buildAndThrowWorkflowException(execution,25000,"Exception occured while NS disconnect call: " + e.getMessage())
126         }
127         utils.log("INFO"," *****Exit deleteNSRelationship *****",  isDebugEnabled)
128     }
129
130     /**
131      * delete NS task
132      */
133     public void deleteNetworkService(DelegateExecution execution) {
134
135         msoLogger.trace("deleteNetworkService  start ")
136         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
137         String nsOperationKey = execution.getVariable("nsOperationKey");
138         String url = vfcAdapterUrl + "/ns/" + execution.getVariable("nsInstanceId")
139         Response apiResponse = deleteRequest(execution, url, nsOperationKey)
140         String returnCode = apiResponse.getStatus()
141         String operationStatus = "error";
142         if(returnCode== "200" || returnCode== "202"){
143             operationStatus = "finished"
144         }
145         execution.setVariable("operationStatus", operationStatus)
146
147         msoLogger.trace("deleteNetworkService  end ")
148     }
149
150     /**
151      * instantiate NS task
152      */
153     public void terminateNetworkService(DelegateExecution execution) {
154
155         msoLogger.trace("terminateNetworkService  start ")
156         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
157         String nsOperationKey = execution.getVariable("nsOperationKey")
158         String url =  vfcAdapterUrl + "/ns/" + execution.getVariable("nsInstanceId") + "/terminate"
159         Response apiResponse = postRequest(execution, url, nsOperationKey)
160         String returnCode = apiResponse.getStatus()
161         String aaiResponseAsString = apiResponse.readEntity(String.class)
162         String jobId = "";
163         if(returnCode== "200" || returnCode== "202"){
164             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
165         }
166         execution.setVariable("jobId", jobId)
167         msoLogger.trace("terminateNetworkService  end ")
168     }
169
170     /**
171      * query NS task
172      */
173     public void queryNSProgress(DelegateExecution execution) {
174
175         msoLogger.trace("queryNSProgress  start ")
176         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
177         String jobId = execution.getVariable("jobId")
178         String nsOperationKey = execution.getVariable("nsOperationKey");
179         String url =  vfcAdapterUrl + "/jobs/" +  execution.getVariable("jobId")
180         Response apiResponse = postRequest(execution, url, nsOperationKey)
181         String returnCode = apiResponse.getStatus()
182         String apiResponseAsString = apiResponse.readEntity(String.class)
183         String operationProgress = "100"
184         if(returnCode== "200"){
185             operationProgress = jsonUtil.getJsonValue(apiResponseAsString, "responseDescriptor.progress")
186         }
187         execution.setVariable("operationProgress", operationProgress)
188         msoLogger.trace("queryNSProgress  end ")
189     }
190
191     /**
192      * delay 5 sec
193      */
194     public void timeDelay(DelegateExecution execution) {
195         try {
196             Thread.sleep(5000);
197         } catch(InterruptedException e) {
198             msoLogger.info("Time Delay exception" + e)
199         }
200     }
201
202     /**
203      * finish NS task
204      */
205     public void finishNSDelete(DelegateExecution execution) {
206         //no need to do anything util now
207     }
208
209     /**
210      * post request
211      * url: the url of the request
212      * requestBody: the body of the request
213      */
214     private Response postRequest(DelegateExecution execution, String urlString, String requestBody){
215
216                 msoLogger.trace("Started Execute VFC adapter Post Process ")
217                 msoLogger.info("url:"+urlString +"\nrequestBody:"+ requestBody)
218                 Response apiResponse = null
219                 try{
220                         URL url = new URL(urlString);
221
222                         // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7'
223             // user 'bepl' authHeader is the same with mso.db.auth
224             String basicAuthValuedb =  UrnPropertiesReader.getVariable("mso.db.auth", execution)
225             HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER)
226             httpClient.addAdditionalHeader("Accept", "application/json")
227             httpClient.addAdditionalHeader("Authorization", basicAuthValuedb)
228
229                         apiResponse = httpClient.post(requestBody)
230
231                         msoLogger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class))
232
233                         msoLogger.trace("Completed Execute VF-C adapter Post Process ")
234                 }catch(Exception e){
235             msoLogger.error("Exception occured while executing VF-C Post Call. Exception is: \n" + e.getMessage());
236             throw new BpmnError("MSOWorkflowException")
237         }
238         return apiResponse
239     }
240     /**
241      * delete request
242      * url: the url of the request
243      * requestBody: the body of the request
244      */
245     private Response deleteRequest(DelegateExecution execution, String url, String requestBody){
246
247         msoLogger.trace("Started Execute VFC adapter Delete Process ")
248         msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody)
249                 Response r
250         try{
251
252                         URL Url = new URL(url)
253             // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7'
254             // user 'bepl' authHeader is the same with mso.db.auth
255             String basicAuthValuedb =  UrnPropertiesReader.getVariable("mso.db.auth", execution)
256             HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER)
257             httpClient.addAdditionalHeader("Accept", "application/json")
258             httpClient.addAdditionalHeader("Authorization", basicAuthValuedb)
259
260                         r = httpClient.delete(requestBody)
261
262             msoLogger.trace("Completed Execute VF-C adapter Delete Process ")
263         }catch(Exception e){
264             msoLogger.error("Exception occured while executing VF-C Post Call. Exception is: \n" + e.getMessage());
265             throw new BpmnError("MSOWorkflowException")
266         }
267         return r
268     }
269 }