Get Csar file bug fix
[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
36 import javax.ws.rs.core.Response
37 /**
38  * This groovy class supports the <class>DoDeleteVFCNetworkServiceInstance.bpmn</class> process.
39  * flow for E2E ServiceInstance Delete
40  */
41 public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProcessor {
42         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVFCNetworkServiceInstance.class);
43
44
45     String vfcUrl = "/vfc/rest/v1/vfcadapter"
46
47     String host = "http://mso.mso.testlab.openecomp.org:8080"
48
49     ExceptionUtil exceptionUtil = new ExceptionUtil()
50
51     JsonUtils jsonUtil = new JsonUtils()
52
53     /**
54      * Pre Process the BPMN Flow Request
55      * Inclouds:
56      * generate the nsOperationKey
57      */
58     public void preProcessRequest (DelegateExecution execution) {
59
60         String msg = ""
61         msoLogger.trace("preProcessRequest() ")
62         try {
63             //deal with operation key
64             String globalSubscriberId = execution.getVariable("globalSubscriberId")
65             msoLogger.info("globalSubscriberId:" + globalSubscriberId)
66             String serviceType = execution.getVariable("serviceType")
67             msoLogger.info("serviceType:" + serviceType)
68             String serviceId = execution.getVariable("serviceId")
69             msoLogger.info("serviceId:" + serviceId)
70             String operationId = execution.getVariable("operationId")
71             msoLogger.info("serviceType:" + serviceType)
72             String nodeTemplateUUID = execution.getVariable("resourceTemplateId")
73             msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID)
74             String nsInstanceId = execution.getVariable("resourceInstanceId")
75             msoLogger.info("nsInstanceId:" + nsInstanceId)
76             execution.setVariable("nsInstanceId",nsInstanceId)
77             String nsOperationKey = """{
78             "globalSubscriberId":"${globalSubscriberId}",
79             "serviceType":"${serviceType}",
80             "serviceId":"${serviceId}",
81             "operationId":"${operationId}",
82             "nodeTemplateUUID":"${nodeTemplateUUID}"
83              }"""
84             execution.setVariable("nsOperationKey", nsOperationKey);
85             msoLogger.info("nsOperationKey:" + nsOperationKey)
86         } catch (BpmnError e) {
87             throw e;
88         } catch (Exception ex){
89             msg = "Exception in preProcessRequest " + ex.getMessage()
90             msoLogger.info(msg)
91             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
92         }
93         msoLogger.trace("Exit preProcessRequest ")
94         }
95
96     /**
97      * unwind NS from AAI relationship
98      */
99     public void deleteNSRelationship(DelegateExecution execution) {
100         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
101         utils.log("INFO"," ***** deleteNSRelationship *****",  isDebugEnabled)
102         String nsInstanceId = execution.getVariable("resourceInstanceId")
103         if(nsInstanceId == null || nsInstanceId == ""){
104             utils.log("INFO"," Delete NS failed",  isDebugEnabled)
105             return
106         }
107         String globalSubscriberId = execution.getVariable("globalSubscriberId")
108         String serviceType = execution.getVariable("serviceType")
109         String serviceId = execution.getVariable("serviceId")
110         AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceId)
111         AAIResourceUri nsServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, nsInstanceId)
112         try {
113             getAAIClient().disconnect(serviceInstanceUri, nsServiceInstanceUri)
114         }catch(Exception e){
115             exceptionUtil.buildAndThrowWorkflowException(execution,25000,"Exception occured while NS disconnect call: " + e.getMessage())
116         }
117         utils.log("INFO"," *****Exit deleteNSRelationship *****",  isDebugEnabled)
118     }
119
120     /**
121      * delete NS task
122      */
123     public void deleteNetworkService(DelegateExecution execution) {
124
125         msoLogger.trace("deleteNetworkService  start ")
126         String nsOperationKey = execution.getVariable("nsOperationKey");
127         String url = host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId")
128         Response apiResponse = deleteRequest(execution, url, nsOperationKey)
129         String returnCode = apiResponse.getStatus()
130         String operationStatus = "error";
131         if(returnCode== "200" || returnCode== "202"){
132             operationStatus = "finished"
133         }
134         execution.setVariable("operationStatus", operationStatus)
135
136         msoLogger.trace("deleteNetworkService  end ")
137     }
138
139     /**
140      * instantiate NS task
141      */
142     public void terminateNetworkService(DelegateExecution execution) {
143
144         msoLogger.trace("terminateNetworkService  start ")
145         String nsOperationKey = execution.getVariable("nsOperationKey")
146         String url =  host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") + "/terminate"
147         Response apiResponse = postRequest(execution, url, nsOperationKey)
148         String returnCode = apiResponse.getStatus()
149         String aaiResponseAsString = apiResponse.readEntity(String.class)
150         String jobId = "";
151         if(returnCode== "200" || returnCode== "202"){
152             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
153         }
154         execution.setVariable("jobId", jobId)
155         msoLogger.trace("terminateNetworkService  end ")
156     }
157
158     /**
159      * query NS task
160      */
161     public void queryNSProgress(DelegateExecution execution) {
162
163         msoLogger.trace("queryNSProgress  start ")
164         String jobId = execution.getVariable("jobId")
165         String nsOperationKey = execution.getVariable("nsOperationKey");
166         String url =  host + vfcUrl + "/jobs/" +  execution.getVariable("jobId")
167         Response apiResponse = postRequest(execution, url, nsOperationKey)
168         String returnCode = apiResponse.getStatus()
169         String apiResponseAsString = apiResponse.readEntity(String.class)
170         String operationProgress = "100"
171         if(returnCode== "200"){
172             operationProgress = jsonUtil.getJsonValue(apiResponseAsString, "responseDescriptor.progress")
173         }
174         execution.setVariable("operationProgress", operationProgress)
175         msoLogger.trace("queryNSProgress  end ")
176     }
177
178     /**
179      * delay 5 sec
180      */
181     public void timeDelay(DelegateExecution execution) {
182         try {
183             Thread.sleep(5000);
184         } catch(InterruptedException e) {
185             msoLogger.info("Time Delay exception" + e)
186         }
187     }
188
189     /**
190      * finish NS task
191      */
192     public void finishNSDelete(DelegateExecution execution) {
193         //no need to do anything util now
194     }
195
196     /**
197      * post request
198      * url: the url of the request
199      * requestBody: the body of the request
200      */
201     private Response postRequest(DelegateExecution execution, String urlString, String requestBody){
202
203                 msoLogger.trace("Started Execute VFC adapter Post Process ")
204                 msoLogger.info("url:"+urlString +"\nrequestBody:"+ requestBody)
205                 Response apiResponse = null
206                 try{
207                         URL url = new URL(urlString);
208
209                         HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER)
210                         httpClient.addAdditionalHeader("Accept", "application/json")
211                         httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk")
212
213                         apiResponse = httpClient.post(requestBody)
214
215                         msoLogger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class))
216
217                         msoLogger.trace("Completed Execute VF-C adapter Post Process ")
218                 }catch(Exception e){
219             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);
220             throw new BpmnError("MSOWorkflowException")
221         }
222         return apiResponse
223     }
224     /**
225      * delete request
226      * url: the url of the request
227      * requestBody: the body of the request
228      */
229     private Response deleteRequest(DelegateExecution execution, String url, String requestBody){
230
231         msoLogger.trace("Started Execute VFC adapter Delete Process ")
232         msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody)
233                 Response r
234         try{
235
236                         URL Url = new URL(url)
237                         HttpClient httpClient = new HttpClient(Url, "application/json", TargetEntity.VNF_ADAPTER)
238                         httpClient.addAdditionalHeader("Accept", "application/json")
239                         httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk")
240                         r = httpClient.delete(requestBody)
241
242             msoLogger.trace("Completed Execute VF-C adapter Delete Process ")
243         }catch(Exception e){
244             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);
245             throw new BpmnError("MSOWorkflowException")
246         }
247         return r
248     }
249 }