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