0069bf4f0af64ccca95a4f52b35b2e3c66629bc6
[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 static org.apache.commons.lang3.StringUtils.*
24
25 import org.apache.commons.lang3.*
26 import org.camunda.bpm.engine.delegate.BpmnError 
27 import org.camunda.bpm.engine.delegate.DelegateExecution
28 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor 
29 import org.onap.so.bpmn.common.scripts.ExceptionUtil 
30 import org.onap.so.bpmn.common.scripts.MsoUtils
31 import org.onap.so.bpmn.core.json.JsonUtils 
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
38 import groovy.json.*
39
40 /**
41  * This groovy class supports the <class>DoDeleteVFCNetworkServiceInstance.bpmn</class> process.
42  * flow for E2E ServiceInstance Delete
43  */
44 public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProcessor {
45         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVFCNetworkServiceInstance.class);
46
47             
48     String vfcUrl = "/vfc/rest/v1/vfcadapter"
49     
50     String host = "http://mso.mso.testlab.openecomp.org:8080"
51     
52     ExceptionUtil exceptionUtil = new ExceptionUtil()
53
54     JsonUtils jsonUtil = new JsonUtils()
55
56     /**
57      * Pre Process the BPMN Flow Request
58      * Inclouds:
59      * generate the nsOperationKey
60      */
61     public void preProcessRequest (DelegateExecution execution) {
62
63         String msg = ""
64         msoLogger.trace("preProcessRequest() ")
65         try {
66             //deal with operation key
67             String globalSubscriberId = execution.getVariable("globalSubscriberId")
68             msoLogger.info("globalSubscriberId:" + globalSubscriberId)
69             String serviceType = execution.getVariable("serviceType")
70             msoLogger.info("serviceType:" + serviceType)
71             String serviceId = execution.getVariable("serviceId")
72             msoLogger.info("serviceId:" + serviceId)
73             String operationId = execution.getVariable("operationId")
74             msoLogger.info("serviceType:" + serviceType)
75             String nodeTemplateUUID = execution.getVariable("resourceTemplateId")
76             msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID)
77             String nsInstanceId = execution.getVariable("resourceInstanceId")
78             msoLogger.info("nsInstanceId:" + nsInstanceId)
79             execution.setVariable("nsInstanceId",nsInstanceId)
80             String nsOperationKey = """{
81             "globalSubscriberId":"${globalSubscriberId}",
82             "serviceType":"${serviceType}",
83             "serviceId":"${serviceId}",
84             "operationId":"${operationId}",
85             "nodeTemplateUUID":"${nodeTemplateUUID}"
86              }"""
87             execution.setVariable("nsOperationKey", nsOperationKey);
88             msoLogger.info("nsOperationKey:" + nsOperationKey)
89         } catch (BpmnError e) {
90             throw e;
91         } catch (Exception ex){
92             msg = "Exception in preProcessRequest " + ex.getMessage()
93             msoLogger.info(msg)
94             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
95         }
96         msoLogger.trace("Exit preProcessRequest ")
97         }
98
99     /**
100      * unwind NS from AAI relationship
101      */
102     public void deleteNSRelationship(DelegateExecution execution) {
103         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
104         utils.log("INFO"," ***** deleteNSRelationship *****",  isDebugEnabled)
105         String nsInstanceId = execution.getVariable("resourceInstanceId")
106         if(nsInstanceId == null || nsInstanceId == ""){
107             utils.log("INFO"," Delete NS failed",  isDebugEnabled)
108             return
109         }
110         String globalSubscriberId = execution.getVariable("globalSubscriberId")
111         String serviceType = execution.getVariable("serviceType")
112         String serviceId = execution.getVariable("serviceId")
113         String deleteRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11">
114                                             <related-to>service-instance</related-to>
115                                             <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link>
116                                             <relationship-data>
117                                                 <relationship-key>customer.global-customer-id</relationship-key>
118                                                 <relationship-value>${MsoUtils.xmlEscape(globalSubscriberId)}</relationship-value>
119                                             </relationship-data>
120                                             <relationship-data>
121                                                 <relationship-key>service-subscription.service-type</relationship-key>
122                                                 <relationship-value>${MsoUtils.xmlEscape(serviceType)}</relationship-value>
123                                             </relationship-data>
124                                            <relationship-data>
125                                                 <relationship-key>service-instance.service-instance-id</relationship-key>
126                                                 <relationship-value>${MsoUtils.xmlEscape(nsInstanceId)}</relationship-value>
127                                             </relationship-data>           
128                                         </relationship>"""
129         String endpoint = execution.getVariable("URN_aai_endpoint")
130         utils.log("INFO","Delete Relationship req:\n" + deleteRelationPayload,  isDebugEnabled)
131         String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship"
132
133         APIResponse aaiRsp = executeAAIDeleteCall(execution, url, deleteRelationPayload)
134         utils.log("INFO","aai response status code:" + aaiRsp.getStatusCode(),  isDebugEnabled)
135         utils.log("INFO","aai response content:" + aaiRsp.getResponseBodyAsString(),  isDebugEnabled)
136         utils.log("INFO"," *****Exit deleteNSRelationship *****",  isDebugEnabled)
137     }
138
139     public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url, String payload){
140         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
141         utils.log("INFO", " ======== Started Execute AAI Delete Process ======== ",  isDebugEnabled)
142         APIResponse apiResponse = null
143         try{
144             String uuid = utils.getRequestID()
145             utils.log("INFO","Generated uuid is: " + uuid,  isDebugEnabled)
146             utils.log("INFO","URL to be used is: " + url,  isDebugEnabled)
147             String userName = execution.getVariable("URN_aai_auth")
148             String password = execution.getVariable("URN_mso_msoKey")
149             String basicAuthCred = utils.getBasicAuth(userName,password)
150             RESTConfig config = new RESTConfig(url);
151             RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml");
152             if (basicAuthCred != null && !"".equals(basicAuthCred)) {
153                 client.addAuthorizationHeader(basicAuthCred)
154             }
155             apiResponse = client.httpDelete(payload)
156             utils.log("INFO","======== Completed Execute AAI Delete Process ======== ",  isDebugEnabled)
157         }catch(Exception e){
158             utils.log("ERROR","Exception occured while executing AAI Put Call. Exception is: \n" + e,  isDebugEnabled)
159             throw new BpmnError("MSOWorkflowException")
160         }
161         return apiResponse
162     }
163
164     /**
165      * delete NS task
166      */
167     public void deleteNetworkService(DelegateExecution execution) {
168
169         msoLogger.trace("deleteNetworkService  start ")
170         String nsOperationKey = execution.getVariable("nsOperationKey");
171         String url = host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") 
172         APIResponse apiResponse = deleteRequest(execution, url, nsOperationKey)
173         String returnCode = apiResponse.getStatusCode()
174         String apiResponseAsString = apiResponse.getResponseBodyAsString()
175         String operationStatus = "error";
176         if(returnCode== "200" || returnCode== "202"){
177             operationStatus = "finished"
178         }
179         execution.setVariable("operationStatus", operationStatus)
180         
181         msoLogger.trace("deleteNetworkService  end ")
182     }
183
184     /**
185      * instantiate NS task
186      */
187     public void terminateNetworkService(DelegateExecution execution) {
188
189         msoLogger.trace("terminateNetworkService  start ")
190         String nsOperationKey = execution.getVariable("nsOperationKey") 
191         String url =  host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") + "/terminate"
192         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)
193         String returnCode = apiResponse.getStatusCode()
194         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
195         String jobId = "";
196         if(returnCode== "200" || returnCode== "202"){
197             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
198         }
199         execution.setVariable("jobId", jobId)   
200         msoLogger.trace("terminateNetworkService  end ")
201     }
202
203     /**
204      * query NS task
205      */
206     public void queryNSProgress(DelegateExecution execution) {
207
208         msoLogger.trace("queryNSProgress  start ")
209         String jobId = execution.getVariable("jobId")
210         String nsOperationKey = execution.getVariable("nsOperationKey");
211         String url =  host + vfcUrl + "/jobs/" +  execution.getVariable("jobId") 
212         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)
213         String returnCode = apiResponse.getStatusCode()
214         String apiResponseAsString = apiResponse.getResponseBodyAsString()
215         String operationProgress = "100"
216         if(returnCode== "200"){
217             operationProgress = jsonUtil.getJsonValue(apiResponseAsString, "responseDescriptor.progress")
218         }
219         execution.setVariable("operationProgress", operationProgress)
220         msoLogger.trace("queryNSProgress  end ")
221     }
222
223     /**
224      * delay 5 sec 
225      */
226     public void timeDelay(DelegateExecution execution) {
227         try {
228             Thread.sleep(5000);
229         } catch(InterruptedException e) {           
230             msoLogger.info("Time Delay exception" + e)
231         }
232     }
233
234     /**
235      * finish NS task
236      */
237     public void finishNSDelete(DelegateExecution execution) {
238         //no need to do anything util now
239     }
240
241     /**
242      * post request
243      * url: the url of the request
244      * requestBody: the body of the request
245      */
246     private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){
247
248         msoLogger.trace("Started Execute VFC adapter Post Process ")
249         msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody)
250         APIResponse apiResponse = null
251         try{
252             RESTConfig config = new RESTConfig(url);
253             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");;
254             apiResponse = client.httpPost(requestBody)
255             msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString())
256             msoLogger.trace("Completed Execute VF-C adapter Post Process ")
257         }catch(Exception e){
258             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
259             throw new BpmnError("MSOWorkflowException")
260         }        
261         return apiResponse
262     }
263     /**
264      * delete request
265      * url: the url of the request
266      * requestBody: the body of the request
267      */
268     private APIResponse deleteRequest(DelegateExecution execution, String url, String requestBody){
269
270         msoLogger.trace("Started Execute VFC adapter Delete Process ")       
271         msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody)
272         APIResponse apiResponse = null
273         try{
274             RESTConfig config = new RESTConfig(url);
275             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");
276             apiResponse = client.httpDelete(requestBody)
277             msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) 
278             msoLogger.trace("Completed Execute VF-C adapter Delete Process ") 
279         }catch(Exception e){
280             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); 
281             throw new BpmnError("MSOWorkflowException")
282         }        
283         return apiResponse
284     }
285 }