42f4cb7bd75e1b6ed24956056adabf50c645e829
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - SO
4  * ================================================================================
5  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts
24
25 import org.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.delegate.DelegateExecution
27 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
28 import org.onap.so.bpmn.common.scripts.ExceptionUtil
29 import org.onap.so.bpmn.core.json.JsonUtils
30 import org.onap.so.client.HttpClient
31 import org.onap.so.client.HttpClientFactory
32 import org.onap.aaiclient.client.aai.AAIObjectType
33 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
34 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
35 import org.slf4j.Logger
36 import org.slf4j.LoggerFactory
37 import org.onap.logging.filter.base.ONAPComponents;
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 Logger logger = LoggerFactory.getLogger( DoDeleteVFCNetworkServiceInstance.class);
47
48     ExceptionUtil exceptionUtil = new ExceptionUtil()
49
50     JsonUtils jsonUtil = new JsonUtils()
51     private final HttpClientFactory httpClientFactory = new HttpClientFactory()
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         logger.trace("preProcessRequest() ")
62         try {
63             //deal with operation key
64             String globalSubscriberId = execution.getVariable("globalSubscriberId")
65             logger.info("globalSubscriberId:" + globalSubscriberId)
66             String serviceType = execution.getVariable("serviceType")
67             logger.info("serviceType:" + serviceType)
68             String serviceId = execution.getVariable("serviceId")
69             logger.info("serviceId:" + serviceId)
70             String operationId = execution.getVariable("operationId")
71             logger.info("serviceType:" + serviceType)
72             String nodeTemplateUUID = execution.getVariable("resourceTemplateId")
73             logger.info("nodeTemplateUUID:" + nodeTemplateUUID)
74             String nsInstanceId = execution.getVariable("resourceInstanceId")
75             logger.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             logger.info("nsOperationKey:" + nsOperationKey)
86
87             String vfcAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.vfc.rest.endpoint", execution)
88                         
89             if (vfcAdapterUrl == null || vfcAdapterUrl.isEmpty()) {
90                 msg = getProcessKey(execution) + ': mso:adapters:vfcc:rest:endpoint URN mapping is not defined'
91                 logger.debug(msg)
92             }
93  
94             while (vfcAdapterUrl.endsWith('/')) {
95                 vfcAdapterUrl = vfcAdapterUrl.substring(0, vfcAdapterUrl.length()-1)
96             }
97                         
98             execution.setVariable("vfcAdapterUrl", vfcAdapterUrl)
99
100         } catch (BpmnError e) {
101             throw e;
102         } catch (Exception ex){
103             msg = "Exception in preProcessRequest " + ex.getMessage()
104             logger.info(msg)
105             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
106         }
107         logger.trace("Exit preProcessRequest ")
108         }
109
110     /**
111      * unwind NS from AAI relationship
112      */
113     public void deleteNSRelationship(DelegateExecution execution) {
114         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
115         logger.info(" ***** deleteNSRelationship *****")
116         String nsInstanceId = execution.getVariable("resourceInstanceId")
117         if(nsInstanceId == null || nsInstanceId == ""){
118             logger.info(" Delete NS failed")
119             return
120         }
121         String globalSubscriberId = execution.getVariable("globalSubscriberId")
122         String serviceType = execution.getVariable("serviceType")
123         String serviceId = execution.getVariable("serviceId")
124         AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceId)
125         AAIResourceUri nsServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, nsInstanceId)
126         try {
127             getAAIClient().disconnect(serviceInstanceUri, nsServiceInstanceUri)
128         }catch(Exception e){
129             exceptionUtil.buildAndThrowWorkflowException(execution,25000,"Exception occured while NS disconnect call: " + e.getMessage())
130         }
131         logger.info(" *****Exit deleteNSRelationship *****")
132     }
133
134     /**
135      * delete NS task
136      */
137     public void deleteNetworkService(DelegateExecution execution) {
138
139         logger.trace("deleteNetworkService  start ")
140         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
141         String nsOperationKey = execution.getVariable("nsOperationKey");
142         String url = vfcAdapterUrl + "/ns/" + execution.getVariable("nsInstanceId")
143         Response apiResponse = deleteRequest(execution, url, nsOperationKey)
144         String returnCode = apiResponse.getStatus()
145         String operationStatus = "error";
146         if(returnCode== "200" || returnCode== "202"){
147             operationStatus = "finished"
148         }
149         execution.setVariable("operationStatus", operationStatus)
150
151         logger.trace("deleteNetworkService  end ")
152     }
153
154     /**
155      *  terminate NS task
156      */
157     public void terminateNetworkService(DelegateExecution execution) {
158
159         logger.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         Response apiResponse = postRequest(execution, url, nsOperationKey)
164         String returnCode = apiResponse.getStatus()
165         String aaiResponseAsString = apiResponse.readEntity(String.class)
166         String jobId = "";
167         if(returnCode== "200" || returnCode== "202"){
168             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
169         }
170         execution.setVariable("jobId", jobId)
171         logger.trace("terminateNetworkService  end ")
172     }
173
174     /**
175      * query NS task
176      */
177     public void queryNSProgress(DelegateExecution execution) {
178
179         logger.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         Response apiResponse = postRequest(execution, url, nsOperationKey)
185         String returnCode = apiResponse.getStatus()
186         String apiResponseAsString = apiResponse.readEntity(String.class)
187         String operationProgress = "100"
188         if(returnCode== "200"){
189             operationProgress = jsonUtil.getJsonValue(apiResponseAsString, "responseDescriptor.progress")
190         }
191         execution.setVariable("operationProgress", operationProgress)
192         logger.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             logger.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 Response postRequest(DelegateExecution execution, String urlString, String requestBody){
219
220                 logger.trace("Started Execute VFC adapter Post Process ")
221                 logger.info("url:"+urlString +"\nrequestBody:"+ requestBody)
222                 Response apiResponse = null
223                 try{
224                         URL url = new URL(urlString);
225
226                         // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7'
227             // user 'bepl' authHeader is the same with mso.db.auth
228             String basicAuthValuedb =  UrnPropertiesReader.getVariable("mso.db.auth", execution)
229             HttpClient httpClient = httpClientFactory.newJsonClient(url, ONAPComponents.VNF_ADAPTER)
230             httpClient.addAdditionalHeader("Accept", "application/json")
231             httpClient.addAdditionalHeader("Authorization", basicAuthValuedb)
232
233                         apiResponse = httpClient.post(requestBody)
234
235                         logger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class))
236
237                         logger.trace("Completed Execute VF-C adapter Post Process ")
238                 }catch(Exception e){
239             logger.error("Exception occured while executing VF-C Post Call. Exception is: \n" + e.getMessage());
240             throw new BpmnError("MSOWorkflowException")
241         }
242         return apiResponse
243     }
244     /**
245      * delete request
246      * url: the url of the request
247      * requestBody: the body of the request
248      */
249     private Response deleteRequest(DelegateExecution execution, String url, String requestBody){
250
251         logger.trace("Started Execute VFC adapter Delete Process ")
252         logger.info("url:"+url +"\nrequestBody:"+ requestBody)
253         Response r
254         try{
255
256                 URL Url = new URL(url)
257             // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7'
258             // user 'bepl' authHeader is the same with mso.db.auth
259             String basicAuthValuedb =  UrnPropertiesReader.getVariable("mso.db.auth", execution)
260             HttpClient httpClient = httpClientFactory.newJsonClient(url, ONAPComponents.VNF_ADAPTER)
261             httpClient.addAdditionalHeader("Accept", "application/json")
262             httpClient.addAdditionalHeader("Authorization", basicAuthValuedb)
263             httpClient.addAdditionalHeader("Content-Type", "application/json")
264             r = httpClient.delete(requestBody)
265                 
266             logger.trace("Completed Execute VF-C adapter Delete Process ")
267         }catch(Exception e){
268             logger.error("Exception occured while executing VF-C Post Call. Exception is: \n" + e.getMessage());
269             throw new BpmnError("MSOWorkflowException")
270         }
271         return r
272     }
273 }