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