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