26f12831bdf098517fe2dcd9bc4b9cbf03380fc1
[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 static org.apache.commons.lang3.StringUtils.*;
24
25 import org.apache.commons.lang3.*
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.common.scripts.MsoUtils
31 import org.onap.so.bpmn.core.json.JsonUtils 
32 import org.onap.so.logger.MessageEnum
33 import org.onap.so.logger.MsoLogger
34 import org.onap.so.rest.APIResponse
35 import org.onap.so.rest.RESTClient 
36 import org.onap.so.rest.RESTConfig
37
38 import groovy.json.*
39
40 /**
41  * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process.
42  * flow for VFC Network Service Create
43  */
44 public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
45         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVFCNSResource.class);
46
47
48     String vfcUrl = "/vfc/rest/v1/vfcadapter"
49             
50     String host = "http://mso.mso.testlab.openecomp.org:8080"
51     
52     ExceptionUtil exceptionUtil = new ExceptionUtil()
53
54     JsonUtils jsonUtil = new JsonUtils()
55
56     /**
57      * CreateVFCNSResource
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         JsonUtils jsonUtil = new JsonUtils()
65
66        String msg = ""
67        msoLogger.trace("preProcessRequest() ")
68        try {
69            //deal with nsName and Description
70            String resourceInput = execution.getVariable("resourceInput")
71
72            String resourceParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
73            // get service name
74            String resourceName = jsonUtil.getJsonValue(resourceInput, "resourceInstanceName")
75            execution.setVariable("nsServiceName", resourceName)
76
77            String nsServiceDescription = execution.getVariable("nsServiceDescription")
78            msoLogger.info("nsServiceName:" + resourceName + " nsServiceDescription:" + nsServiceDescription)
79            //deal with operation key
80            String globalSubscriberId = jsonUtil.getJsonValue(resourceInput, "globalSubscriberId")
81            msoLogger.info("globalSubscriberId:" + globalSubscriberId)
82            //set local globalSubscriberId variable
83            execution.setVariable("globalSubscriberId", globalSubscriberId);
84            String serviceType = execution.getVariable("serviceType")
85            msoLogger.info("serviceType:" + serviceType)
86
87            String serviceId = execution.getVariable("serviceInstanceId")
88            msoLogger.info("serviceId:" + serviceId)
89
90            String operationId = jsonUtil.getJsonValue(resourceInput, "operationId")
91            msoLogger.info("serviceType:" + serviceType)
92
93            String nodeTemplateUUID = jsonUtil.getJsonValue(resourceInput, "resourceModelInfo.modelCustomizationUuid")
94            String nsServiceModelUUID = jsonUtil.getJsonValue(resourceParameters, "requestInputs.nsd0_providing_service_uuid")
95            msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID)
96            /*
97             * segmentInformation needed as a object of segment
98             * {
99             *     "domain":"",
100             *     "nodeTemplateName":"",
101             *     "nodeType":"",
102             *     "nsParameters":{
103             *       //this is the nsParameters sent to VF-C
104             *     }
105             * }
106             */
107            String nsParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
108            msoLogger.info("nsParameters:" + nsParameters)
109            String nsOperationKey = """{
110                    "globalSubscriberId":"${globalSubscriberId}",
111                    "serviceType":"${serviceType}",
112                    "serviceId":"${serviceId}",
113                    "operationId":"${operationId}",
114                    "nodeTemplateUUID":"${nodeTemplateUUID}"
115                     }"""
116            execution.setVariable("nsOperationKey", nsOperationKey);
117            execution.setVariable("nsParameters", nsParameters)
118            execution.setVariable("nsServiceModelUUID", nsServiceModelUUID);
119            
120
121        } catch (BpmnError e) {
122            throw e;
123        } catch (Exception ex){
124            msg = "Exception in preProcessRequest " + ex.getMessage()
125            msoLogger.info(msg)
126            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
127        }
128        msoLogger.trace("Exit preProcessRequest ")
129         }
130
131     /**
132      * create NS task
133      */
134     public void createNetworkService(DelegateExecution execution) {
135         msoLogger.trace("createNetworkService ")
136         String nsOperationKey = execution.getVariable("nsOperationKey");
137         String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID");
138         String nsParameters = execution.getVariable("nsParameters");
139         String nsServiceName = execution.getVariable("nsServiceName")
140         String nsServiceDescription = execution.getVariable("nsServiceDescription")
141         String locationConstraints = jsonUtil.getJsonValue(nsParameters, "locationConstraints")
142         String requestInputs = jsonUtil.getJsonValue(nsParameters, "requestInputs")
143         String reqBody ="""{
144                 "nsServiceName":"${nsServiceName}",
145                 "nsServiceDescription":"${nsServiceDescription}",
146                 "nsServiceModelUUID":"${nsServiceModelUUID}",
147                 "nsOperationKey":${nsOperationKey},
148                 "nsParameters":{
149                      "locationConstraints":${locationConstraints},
150                      "additionalParamForNs":${requestInputs}
151                 }
152                }"""
153         APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody)
154         String returnCode = apiResponse.getStatusCode()
155         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
156         String nsInstanceId = "";
157         if(returnCode== "200" || returnCode == "201"){
158             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
159         }
160         execution.setVariable("nsInstanceId", nsInstanceId)
161         msoLogger.info(" *****Exit  createNetworkService *****")
162     }
163
164     /**
165      * instantiate NS task
166      */
167     public void instantiateNetworkService(DelegateExecution execution) {
168         msoLogger.trace("instantiateNetworkService ")
169         String nsOperationKey = execution.getVariable("nsOperationKey");
170         String nsParameters = execution.getVariable("nsParameters");
171         String nsServiceName = execution.getVariable("nsServiceName")
172         String nsServiceDescription = execution.getVariable("nsServiceDescription")
173         String reqBody ="""{
174         "nsServiceName":"${nsServiceName}",
175         "nsServiceDescription":"${nsServiceDescription}",
176         "nsOperationKey":${nsOperationKey},
177         "nsParameters":${nsParameters}
178        }"""
179         String nsInstanceId = execution.getVariable("nsInstanceId")
180         String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate"
181         APIResponse apiResponse = postRequest(execution, url, reqBody)
182         String returnCode = apiResponse.getStatusCode()
183         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
184         String jobId = "";
185         if(returnCode== "200"|| returnCode == "201"){
186             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
187         }
188         execution.setVariable("jobId", jobId)
189         msoLogger.info(" *****Exit  instantiateNetworkService *****")
190     }
191
192     /**
193      * query NS task
194      */
195     public void queryNSProgress(DelegateExecution execution) {
196         msoLogger.trace("queryNSProgress ")
197         String jobId = execution.getVariable("jobId")
198         String nsOperationKey = execution.getVariable("nsOperationKey");
199         String url = host + vfcUrl + "/jobs/" + jobId
200         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)
201         String returnCode = apiResponse.getStatusCode()
202         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
203         String operationStatus = "error"
204         if(returnCode== "200"|| returnCode == "201"){
205             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
206         }
207         execution.setVariable("operationStatus", operationStatus)
208         msoLogger.info(" *****Exit  queryNSProgress *****")
209     }
210
211     /**
212      * delay 5 sec 
213      */
214     public void timeDelay(DelegateExecution execution) {
215         try {
216             Thread.sleep(5000);
217         } catch(InterruptedException e) {           
218             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Time Delay exception" + e , "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
219         }
220     }
221
222     /**
223      * finish NS task
224      */
225     public void addNSRelationship(DelegateExecution execution) {
226         msoLogger.trace("addNSRelationship ")
227         String nsInstanceId = execution.getVariable("nsInstanceId")
228         if(nsInstanceId == null || nsInstanceId == ""){
229             msoLogger.info(" create NS failed, so do not need to add relationship")
230             return
231         }
232         String globalSubscriberId = execution.getVariable("globalSubscriberId")
233         String serviceType = execution.getVariable("serviceType")
234         String serviceId = execution.getVariable("serviceInstanceId")
235         String addRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11">
236                                             <related-to>service-instance</related-to>
237                                             <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link>
238                                             <relationship-data>
239                                                 <relationship-key>customer.global-customer-id</relationship-key>
240                                                 <relationship-value>${MsoUtils.xmlEscape(globalSubscriberId)}</relationship-value>
241                                             </relationship-data>
242                                             <relationship-data>
243                                                 <relationship-key>service-subscription.service-type</relationship-key>
244                                                 <relationship-value>${MsoUtils.xmlEscape(serviceType)}</relationship-value>
245                                             </relationship-data>
246                                            <relationship-data>
247                                                 <relationship-key>service-instance.service-instance-id</relationship-key>
248                                                 <relationship-value>${MsoUtils.xmlEscape(nsInstanceId)}</relationship-value>
249                                             </relationship-data>           
250                                         </relationship>"""
251         String endpoint = execution.getVariable("URN_aai_endpoint")  
252         msoLogger.info("Add Relationship req:\n" + addRelationPayload)
253         String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship"
254         APIResponse aaiRsp = executeAAIPutCall(execution, url, addRelationPayload)
255         msoLogger.info("aai response status code:" + aaiRsp.getStatusCode())
256         msoLogger.info("aai response content:" + aaiRsp.getResponseBodyAsString())
257         msoLogger.info(" *****Exit addNSRelationship *****")
258     }
259     
260     public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){
261         msoLogger.trace("Started Execute AAI Put Process ") 
262         APIResponse apiResponse = null
263         try{
264             String uuid = utils.getRequestID()
265             msoLogger.info("Generated uuid is: " + uuid) 
266             msoLogger.info("URL to be used is: " + url) 
267             String userName = execution.getVariable("URN_aai_auth")
268             String password = execution.getVariable("URN_mso_msoKey")
269             String basicAuthCred = utils.getBasicAuth(userName,password)
270             RESTConfig config = new RESTConfig(url);
271             RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml");
272             if (basicAuthCred != null && !"".equals(basicAuthCred)) {
273                 client.addAuthorizationHeader(basicAuthCred)
274             }
275             apiResponse = client.httpPut(payload)
276             msoLogger.trace("Completed Execute AAI Put Process ") 
277         }catch(Exception e){
278             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); 
279             throw new BpmnError("MSOWorkflowException")
280         }
281         return apiResponse
282     }
283
284     /**
285      * post request
286      * url: the url of the request
287      * requestBody: the body of the request
288      */
289     private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){
290         msoLogger.trace("Started Execute VFC adapter Post Process ")
291         msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody)
292         APIResponse apiResponse = null
293         try{
294             RESTConfig config = new RESTConfig(url);
295             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");
296             apiResponse = client.httpPost(requestBody)
297             msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString())    
298             msoLogger.trace("Completed Execute VF-C adapter Post Process ")
299         }catch(Exception e){
300             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
301             throw new BpmnError("MSOWorkflowException")
302         }        
303         return apiResponse
304     }
305     
306         public void sendSyncResponse (DelegateExecution execution) {
307                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
308                 utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
309
310                 try {
311                         String operationStatus = execution.getVariable("operationStatus")
312                         // RESTResponse for main flow
313                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
314                         utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled)
315                         sendWorkflowResponse(execution, 202, resourceOperationResp)
316                         execution.setVariable("sentSyncResponse", true)
317
318                 } catch (Exception ex) {
319                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
320                         utils.log("DEBUG", msg, isDebugEnabled)
321                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
322                 }
323                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
324         }
325
326 }