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