b17b0a37b766c16da37afbf15fcff8454495268b
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateVFCNetworkServiceInstance.groovy
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.onap.so.client.HttpClientFactory
26 import org.onap.so.client.aai.AAIObjectType
27 import org.onap.so.client.aai.entities.uri.AAIResourceUri
28 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
29 import org.camunda.bpm.engine.delegate.BpmnError
30 import org.camunda.bpm.engine.delegate.DelegateExecution
31 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
32 import org.onap.so.bpmn.common.scripts.ExceptionUtil
33 import org.onap.so.bpmn.core.json.JsonUtils
34 import org.onap.so.client.HttpClient
35 import org.onap.so.logger.MessageEnum
36 import org.onap.so.logger.MsoLogger
37 import org.slf4j.Logger
38 import org.slf4j.LoggerFactory
39 import org.onap.so.bpmn.core.UrnPropertiesReader
40
41 import org.onap.so.utils.TargetEntity
42
43 import javax.ws.rs.core.Response
44
45 /**
46  * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process.
47  * flow for VFC Network Service Create
48  */
49 public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProcessor {
50     private static final Logger logger = LoggerFactory.getLogger( DoCreateVFCNetworkServiceInstance.class);
51
52
53     ExceptionUtil exceptionUtil = new ExceptionUtil()
54
55     JsonUtils jsonUtil = new JsonUtils()
56
57     /**
58      * Pre Process the BPMN Flow Request
59      * Inclouds:
60      * generate the nsOperationKey
61      * generate the nsParameters
62      */
63     public void preProcessRequest (DelegateExecution execution) {
64        String msg = ""
65        logger.trace("preProcessRequest()")
66        try {
67            //deal with nsName and Description
68            String nsServiceName = execution.getVariable("nsServiceName")
69            String nsServiceDescription = execution.getVariable("nsServiceDescription")
70            logger.debug("nsServiceName:" + nsServiceName + " nsServiceDescription:" + nsServiceDescription)
71            //deal with operation key
72            String globalSubscriberId = execution.getVariable("globalSubscriberId")
73            logger.debug("globalSubscriberId:" + globalSubscriberId)
74            String serviceType = execution.getVariable("serviceType")
75            logger.debug("serviceType:" + serviceType)
76            String serviceId = execution.getVariable("serviceId")
77            logger.debug("serviceId:" + serviceId)
78            String operationId = execution.getVariable("operationId")
79            logger.debug("serviceType:" + serviceType)
80            String nodeTemplateUUID = execution.getVariable("resourceUUID")
81            logger.debug("nodeTemplateUUID:" + nodeTemplateUUID)
82            /*
83             * segmentInformation needed as a object of segment
84             * {
85             *     "domain":"",
86             *     "nodeTemplateName":"",
87             *     "nodeType":"",
88             *     "nsParameters":{
89             *       //this is the nsParameters sent to VF-C
90             *     }
91             * }
92             */
93            String nsParameters = execution.getVariable("resourceParameters")
94            logger.debug("nsParameters:" + nsParameters)
95            String nsOperationKey = """{
96                    "globalSubscriberId":"${globalSubscriberId}",
97                    "serviceType":"${serviceType}",
98                    "serviceId":"${serviceId}",
99                    "operationId":"${operationId}",
100                    "nodeTemplateUUID":"${nodeTemplateUUID}"
101                     }"""
102            execution.setVariable("nsOperationKey", nsOperationKey);
103            execution.setVariable("nsParameters", nsParameters)
104
105            String vfcAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.vfc.rest.endpoint", execution)
106                    
107            if (vfcAdapterUrl == null || vfcAdapterUrl.isEmpty()) {
108                msg = getProcessKey(execution) + ': mso:adapters:vfcc:rest:endpoint URN mapping is not defined'
109                logger.debug(msg)
110            }
111
112            while (vfcAdapterUrl.endsWith('/')) {
113                vfcAdapterUrl = vfcAdapterUrl.substring(0, vfcAdapterUrl.length()-1)
114            }
115                    
116            execution.setVariable("vfcAdapterUrl", vfcAdapterUrl)
117
118
119        } catch (BpmnError e) {
120            throw e;
121        } catch (Exception ex){
122            msg = "Exception in preProcessRequest " + ex.getMessage()
123            logger.debug(msg)
124            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
125        }
126        logger.trace("Exit preProcessRequest")
127         }
128
129     /**
130      * create NS task
131      */
132     public void createNetworkService(DelegateExecution execution) {
133         logger.trace("createNetworkService")
134         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
135         String nsOperationKey = execution.getVariable("nsOperationKey");
136         String nsParameters = execution.getVariable("nsParameters");
137         String nsServiceName = execution.getVariable("nsServiceName")
138         String nsServiceDescription = execution.getVariable("nsServiceDescription")
139         String reqBody ="""{
140                 "nsServiceName":"${nsServiceName}",
141                 "nsServiceDescription":"${nsServiceDescription}",
142                 "nsOperationKey":${nsOperationKey},
143                 "nsParameters":${nsParameters}
144                }"""
145         Response apiResponse = postRequest(execution, vfcAdapterUrl + "/ns", reqBody)
146         String returnCode = apiResponse.getStatus()
147         String aaiResponseAsString = apiResponse.readEntity(String.class)
148         String nsInstanceId = "";
149         if(returnCode== "200" || returnCode == "201"){
150             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
151         }
152         execution.setVariable("nsInstanceId", nsInstanceId)
153         logger.trace("Exit  createNetworkService")
154     }
155
156     /**
157      * instantiate NS task
158      */
159     public void instantiateNetworkService(DelegateExecution execution) {
160         logger.trace("instantiateNetworkService")
161         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
162         String nsOperationKey = execution.getVariable("nsOperationKey");
163         String nsParameters = execution.getVariable("nsParameters");
164         String nsServiceName = execution.getVariable("nsServiceName")
165         String nsServiceDescription = execution.getVariable("nsServiceDescription")
166         String reqBody ="""{
167         "nsServiceName":"${nsServiceName}",
168         "nsServiceDescription":"${nsServiceDescription}",
169         "nsOperationKey":${nsOperationKey},
170         "nsParameters":${nsParameters}
171        }"""
172         String nsInstanceId = execution.getVariable("nsInstanceId")
173         String url = vfcAdapterUrl + "/ns/" +nsInstanceId + "/instantiate"
174         Response apiResponse = postRequest(execution, url, reqBody)
175         String returnCode = apiResponse.getStatus()
176         String aaiResponseAsString = apiResponse.readEntity(String.class)
177         String jobId = "";
178         if(returnCode== "200"|| returnCode == "201"){
179             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
180         }
181         execution.setVariable("jobId", jobId)
182         logger.trace("Exit  instantiateNetworkService")
183     }
184
185     /**
186      * query NS task
187      */
188     public void queryNSProgress(DelegateExecution execution) {
189         logger.trace("queryNSProgress")
190         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
191         String jobId = execution.getVariable("jobId")
192         String nsOperationKey = execution.getVariable("nsOperationKey");
193         String url = vfcAdapterUrl + "/jobs/" + jobId
194         Response apiResponse = postRequest(execution, url, nsOperationKey)
195         String returnCode = apiResponse.getStatus()
196         String aaiResponseAsString = apiResponse.readEntity(String.class)
197         String operationStatus = "error"
198         if(returnCode== "200"|| returnCode == "201"){
199             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
200         }
201         execution.setVariable("operationStatus", operationStatus)
202         logger.trace("Exit  queryNSProgress")
203     }
204
205     /**
206      * delay 5 sec
207      */
208     public void timeDelay(DelegateExecution execution) {
209         try {
210             Thread.sleep(5000);
211         } catch(InterruptedException e) {
212            logger.debug("Time Delay exception" + e )
213         }
214     }
215
216     /**
217      * finish NS task
218      */
219     public void addNSRelationship(DelegateExecution execution) {
220         logger.trace("addNSRelationship")
221         String nsInstanceId = execution.getVariable("nsInstanceId")
222         if(nsInstanceId == null || nsInstanceId == ""){
223             logger.debug(" create NS failed, so do not need to add relationship")
224             return
225         }
226         String globalSubscriberId = execution.getVariable("globalSubscriberId")
227         String serviceType = execution.getVariable("serviceType")
228         String serviceId = execution.getVariable("serviceId")
229
230         AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,nsInstanceId)
231         AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,serviceId)
232
233         try{
234             getAAIClient().connect(nsUri,relatedServiceUri)
235             logger.info("NS relationship to Service added successfully")
236         }catch(Exception e){
237             logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
238                     "Exception occured while executing AAI Put Call", "BPMN", MsoLogger.getServiceName(),
239                     MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
240             throw new BpmnError("MSOWorkflowException")
241         }
242     }
243
244     /**
245      * post request
246      * url: the url of the request
247      * requestBody: the body of the request
248      */
249     private Response postRequest(DelegateExecution execution, String urlString, String requestBody){
250         logger.trace("Started Execute VFC adapter Post Process")
251         logger.debug("url:"+urlString +"\nrequestBody:"+ requestBody)
252         Response apiResponse = null
253         try{
254
255                         URL url = new URL(urlString);
256             
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 = new HttpClientFactory().newJsonClient(url, TargetEntity.VNF_ADAPTER)
261             httpClient.addAdditionalHeader("Accept", "application/json")
262             httpClient.addAdditionalHeader("Authorization", basicAuthValuedb)
263
264             apiResponse = httpClient.post(requestBody)
265
266             logger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class))
267             logger.trace("Completed Execute VF-C adapter Post Process")
268         }catch(Exception e){
269                         logger.error("Exception occured while executing VFC Adapter Post Call"  + e.getMessage ());
270             throw new BpmnError("MSOWorkflowException")
271         }
272         return apiResponse
273     }
274 }