Get Csar file bug fix
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / CreateVFCNSResource.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
35 import groovy.json.*
36 import javax.ws.rs.core.Response
37 import org.onap.so.utils.TargetEntity
38
39 /**
40  * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process.
41  * flow for VFC Network Service Create
42  */
43 public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
44         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVFCNSResource.class);
45
46
47     String vfcUrl = "/vfc/rest/v1/vfcadapter"
48
49     String host = "http://mso.mso.testlab.openecomp.org:8080"
50
51     ExceptionUtil exceptionUtil = new ExceptionUtil()
52
53     JsonUtils jsonUtil = new JsonUtils()
54
55     /**
56      * CreateVFCNSResource
57      * Pre Process the BPMN Flow Request
58      * Inclouds:
59      * generate the nsOperationKey
60      * generate the nsParameters
61      */
62     public void preProcessRequest (DelegateExecution execution) {
63         JsonUtils jsonUtil = new JsonUtils()
64
65        String msg = ""
66        msoLogger.trace("preProcessRequest() ")
67        try {
68            //deal with nsName and Description
69            String resourceInput = execution.getVariable("resourceInput")
70
71            String resourceParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
72            // get service name
73            String resourceName = jsonUtil.getJsonValue(resourceInput, "resourceInstanceName")
74            execution.setVariable("nsServiceName", resourceName)
75
76            String nsServiceDescription = execution.getVariable("nsServiceDescription")
77            msoLogger.info("nsServiceName:" + resourceName + " nsServiceDescription:" + nsServiceDescription)
78            //deal with operation key
79            String globalSubscriberId = jsonUtil.getJsonValue(resourceInput, "globalSubscriberId")
80            msoLogger.info("globalSubscriberId:" + globalSubscriberId)
81            //set local globalSubscriberId variable
82            execution.setVariable("globalSubscriberId", globalSubscriberId);
83            String serviceType = execution.getVariable("serviceType")
84            msoLogger.info("serviceType:" + serviceType)
85
86            String serviceId = execution.getVariable("serviceInstanceId")
87            msoLogger.info("serviceId:" + serviceId)
88
89            String operationId = jsonUtil.getJsonValue(resourceInput, "operationId")
90            msoLogger.info("serviceType:" + serviceType)
91
92            String nodeTemplateUUID = jsonUtil.getJsonValue(resourceInput, "resourceModelInfo.modelCustomizationUuid")
93            String nsServiceModelUUID = jsonUtil.getJsonValue(resourceParameters, "requestInputs.nsd0_providing_service_uuid")
94            msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID)
95            /*
96             * segmentInformation needed as a object of segment
97             * {
98             *     "domain":"",
99             *     "nodeTemplateName":"",
100             *     "nodeType":"",
101             *     "nsParameters":{
102             *       //this is the nsParameters sent to VF-C
103             *     }
104             * }
105             */
106            String nsParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
107            msoLogger.info("nsParameters:" + nsParameters)
108            String nsOperationKey = """{
109                    "globalSubscriberId":"${globalSubscriberId}",
110                    "serviceType":"${serviceType}",
111                    "serviceId":"${serviceId}",
112                    "operationId":"${operationId}",
113                    "nodeTemplateUUID":"${nodeTemplateUUID}"
114                     }"""
115            execution.setVariable("nsOperationKey", nsOperationKey);
116            execution.setVariable("nsParameters", nsParameters)
117            execution.setVariable("nsServiceModelUUID", nsServiceModelUUID);
118
119
120        } catch (BpmnError e) {
121            throw e;
122        } catch (Exception ex){
123            msg = "Exception in preProcessRequest " + ex.getMessage()
124            msoLogger.info(msg)
125            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
126        }
127        msoLogger.trace("Exit preProcessRequest ")
128         }
129
130     /**
131      * create NS task
132      */
133     public void createNetworkService(DelegateExecution execution) {
134         msoLogger.trace("createNetworkService ")
135         String nsOperationKey = execution.getVariable("nsOperationKey");
136         String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID");
137         String nsParameters = execution.getVariable("nsParameters");
138         String nsServiceName = execution.getVariable("nsServiceName")
139         String nsServiceDescription = execution.getVariable("nsServiceDescription")
140         String locationConstraints = jsonUtil.getJsonValue(nsParameters, "locationConstraints")
141         String requestInputs = jsonUtil.getJsonValue(nsParameters, "requestInputs")
142         String reqBody ="""{
143                 "nsServiceName":"${nsServiceName}",
144                 "nsServiceDescription":"${nsServiceDescription}",
145                 "nsServiceModelUUID":"${nsServiceModelUUID}",
146                 "nsOperationKey":${nsOperationKey},
147                 "nsParameters":{
148                      "locationConstraints":${locationConstraints},
149                      "additionalParamForNs":${requestInputs}
150                 }
151                }"""
152         Response apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody)
153         String returnCode = apiResponse.getStatus()
154         String aaiResponseAsString = apiResponse.readEntity(String.class)
155         String nsInstanceId = "";
156         if(returnCode== "200" || returnCode == "201"){
157             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
158         }
159         execution.setVariable("nsInstanceId", nsInstanceId)
160         msoLogger.info(" *****Exit  createNetworkService *****")
161     }
162
163     /**
164      * instantiate NS task
165      */
166     public void instantiateNetworkService(DelegateExecution execution) {
167         msoLogger.trace("instantiateNetworkService ")
168         String nsOperationKey = execution.getVariable("nsOperationKey");
169         String nsParameters = execution.getVariable("nsParameters");
170         String nsServiceName = execution.getVariable("nsServiceName")
171         String nsServiceDescription = execution.getVariable("nsServiceDescription")
172         String reqBody ="""{
173         "nsServiceName":"${nsServiceName}",
174         "nsServiceDescription":"${nsServiceDescription}",
175         "nsOperationKey":${nsOperationKey},
176         "nsParameters":${nsParameters}
177        }"""
178         String nsInstanceId = execution.getVariable("nsInstanceId")
179         String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate"
180         Response apiResponse = postRequest(execution, url, reqBody)
181         String returnCode = apiResponse.getStatus()
182         String aaiResponseAsString = apiResponse.readEntity(String.class)
183         String jobId = "";
184         if(returnCode== "200"|| returnCode == "201"){
185             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
186         }
187         execution.setVariable("jobId", jobId)
188         msoLogger.info(" *****Exit  instantiateNetworkService *****")
189     }
190
191     /**
192      * query NS task
193      */
194     public void queryNSProgress(DelegateExecution execution) {
195         msoLogger.trace("queryNSProgress ")
196         String jobId = execution.getVariable("jobId")
197         String nsOperationKey = execution.getVariable("nsOperationKey");
198         String url = host + vfcUrl + "/jobs/" + jobId
199         Response apiResponse = postRequest(execution, url, nsOperationKey)
200         String returnCode = apiResponse.getStatus()
201         String aaiResponseAsString = apiResponse.readEntity(String.class)
202         String operationStatus = "error"
203         if(returnCode== "200"|| returnCode == "201"){
204             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
205         }
206         execution.setVariable("operationStatus", operationStatus)
207         msoLogger.info(" *****Exit  queryNSProgress *****")
208     }
209
210     /**
211      * delay 5 sec
212      */
213     public void timeDelay(DelegateExecution execution) {
214         try {
215             Thread.sleep(5000);
216         } catch(InterruptedException e) {
217             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Time Delay exception" + e , "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
218         }
219     }
220
221     /**
222      * finish NS task
223      */
224     public void addNSRelationship(DelegateExecution execution) {
225         msoLogger.trace("addNSRelationship ")
226         String nsInstanceId = execution.getVariable("nsInstanceId")
227         if(nsInstanceId == null || nsInstanceId == ""){
228             msoLogger.info(" create NS failed, so do not need to add relationship")
229             return
230         }
231         String globalSubscriberId = execution.getVariable("globalSubscriberId")
232         String serviceType = execution.getVariable("serviceType")
233         String serviceId = execution.getVariable("serviceInstanceId")
234
235         AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,nsInstanceId)
236         AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,serviceId)
237
238         try{
239             getAAIClient().connect(nsUri,relatedServiceUri)
240             msoLogger.info("NS relationship to Service added successfully")
241         }catch(Exception e){
242             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while Creating NS relationship.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage(),e);
243             throw new BpmnError("MSOWorkflowException")
244         }
245     }
246
247     /**
248      * post request
249      * url: the url of the request
250      * requestBody: the body of the request
251      */
252     private Response postRequest(DelegateExecution execution, String urlString, String requestBody){
253         msoLogger.trace("Started Execute VFC adapter Post Process ")
254         msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody)
255         Response apiResponse = null
256         try{
257
258                         URL url = new URL(urlString);
259
260                         HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER)
261                         httpClient.addAdditionalHeader("Accept", "application/json")
262                         httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk")
263
264                         apiResponse = httpClient.post(requestBody)
265
266             msoLogger.info("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class))
267             msoLogger.trace("Completed Execute VF-C adapter Post Process ")
268         }catch(Exception e){
269             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
270             throw new BpmnError("MSOWorkflowException")
271         }
272         return apiResponse
273     }
274
275         public void sendSyncResponse (DelegateExecution execution) {
276                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
277                 utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
278
279                 try {
280                         String operationStatus = execution.getVariable("operationStatus")
281                         // RESTResponse for main flow
282                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
283                         utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled)
284                         sendWorkflowResponse(execution, 202, resourceOperationResp)
285                         execution.setVariable("sentSyncResponse", true)
286
287                 } catch (Exception ex) {
288                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
289                         utils.log("DEBUG", msg, isDebugEnabled)
290                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
291                 }
292                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
293         }
294
295 }