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