10f6acd40348035f19e2bb95ee82c21fb4d2f2bf
[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 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.UrnPropertiesReader;
32 import org.onap.so.bpmn.core.json.JsonUtils 
33 import org.onap.so.logger.MessageEnum
34 import org.onap.so.logger.MsoLogger
35 import org.onap.so.rest.APIResponse
36 import org.onap.so.rest.RESTClient 
37 import org.onap.so.rest.RESTConfig
38
39 import groovy.json.*
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     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      * Pre Process the BPMN Flow Request
58      * Inclouds:
59      * generate the nsOperationKey
60      * generate the nsParameters
61      */
62     public void preProcessRequest (DelegateExecution execution) {
63        String msg = ""
64        msoLogger.trace("preProcessRequest()")
65        try {
66            //deal with nsName and Description
67            String nsServiceName = execution.getVariable("nsServiceName")
68            String nsServiceDescription = execution.getVariable("nsServiceDescription")
69            msoLogger.debug("nsServiceName:" + nsServiceName + " nsServiceDescription:" + nsServiceDescription)
70            //deal with operation key
71            String globalSubscriberId = execution.getVariable("globalSubscriberId")
72            msoLogger.debug("globalSubscriberId:" + globalSubscriberId)
73            String serviceType = execution.getVariable("serviceType")
74            msoLogger.debug("serviceType:" + serviceType)
75            String serviceId = execution.getVariable("serviceId")
76            msoLogger.debug("serviceId:" + serviceId)
77            String operationId = execution.getVariable("operationId")
78            msoLogger.debug("serviceType:" + serviceType)
79            String nodeTemplateUUID = execution.getVariable("resourceUUID")
80            msoLogger.debug("nodeTemplateUUID:" + nodeTemplateUUID)
81            /*
82             * segmentInformation needed as a object of segment
83             * {
84             *     "domain":"",
85             *     "nodeTemplateName":"",
86             *     "nodeType":"",
87             *     "nsParameters":{
88             *       //this is the nsParameters sent to VF-C
89             *     }
90             * }
91             */
92            String nsParameters = execution.getVariable("resourceParameters")
93            msoLogger.debug("nsParameters:" + nsParameters)
94            String nsOperationKey = """{
95                    "globalSubscriberId":"${globalSubscriberId}",
96                    "serviceType":"${serviceType}",
97                    "serviceId":"${serviceId}",
98                    "operationId":"${operationId}",
99                    "nodeTemplateUUID":"${nodeTemplateUUID}"
100                     }"""
101            execution.setVariable("nsOperationKey", nsOperationKey);
102            execution.setVariable("nsParameters", nsParameters)
103            
104
105        } catch (BpmnError e) {
106            throw e;
107        } catch (Exception ex){
108            msg = "Exception in preProcessRequest " + ex.getMessage()
109            msoLogger.debug(msg)
110            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
111        }
112        msoLogger.trace("Exit preProcessRequest")
113         }
114
115     /**
116      * create NS task
117      */
118     public void createNetworkService(DelegateExecution execution) {
119         msoLogger.trace("createNetworkService")
120         String nsOperationKey = execution.getVariable("nsOperationKey");
121         String nsParameters = execution.getVariable("nsParameters");
122         String nsServiceName = execution.getVariable("nsServiceName")
123         String nsServiceDescription = execution.getVariable("nsServiceDescription")
124         String reqBody ="""{
125                 "nsServiceName":"${nsServiceName}",
126                 "nsServiceDescription":"${nsServiceDescription}",
127                 "nsOperationKey":${nsOperationKey},
128                 "nsParameters":${nsParameters}
129                }"""
130         APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody)
131         String returnCode = apiResponse.getStatusCode()
132         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
133         String nsInstanceId = "";
134         if(returnCode== "200" || returnCode == "201"){
135             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
136         }
137         execution.setVariable("nsInstanceId", nsInstanceId)
138         msoLogger.trace("Exit  createNetworkService")
139     }
140
141     /**
142      * instantiate NS task
143      */
144     public void instantiateNetworkService(DelegateExecution execution) {
145         msoLogger.trace("instantiateNetworkService")
146         String nsOperationKey = execution.getVariable("nsOperationKey");
147         String nsParameters = execution.getVariable("nsParameters");
148         String nsServiceName = execution.getVariable("nsServiceName")
149         String nsServiceDescription = execution.getVariable("nsServiceDescription")
150         String reqBody ="""{
151         "nsServiceName":"${nsServiceName}",
152         "nsServiceDescription":"${nsServiceDescription}",
153         "nsOperationKey":${nsOperationKey},
154         "nsParameters":${nsParameters}
155        }"""
156         String nsInstanceId = execution.getVariable("nsInstanceId")
157         String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate"
158         APIResponse apiResponse = postRequest(execution, url, reqBody)
159         String returnCode = apiResponse.getStatusCode()
160         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
161         String jobId = "";
162         if(returnCode== "200"|| returnCode == "201"){
163             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
164         }
165         execution.setVariable("jobId", jobId)
166         msoLogger.trace("Exit  instantiateNetworkService")
167     }
168
169     /**
170      * query NS task
171      */
172     public void queryNSProgress(DelegateExecution execution) {
173         msoLogger.trace("queryNSProgress")
174         String jobId = execution.getVariable("jobId")
175         String nsOperationKey = execution.getVariable("nsOperationKey");
176         String url = host + vfcUrl + "/jobs/" + jobId
177         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)
178         String returnCode = apiResponse.getStatusCode()
179         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
180         String operationStatus = "error"
181         if(returnCode== "200"|| returnCode == "201"){
182             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
183         }
184         execution.setVariable("operationStatus", operationStatus)
185         msoLogger.trace("Exit  queryNSProgress")
186     }
187
188     /**
189      * delay 5 sec 
190      */
191     public void timeDelay(DelegateExecution execution) {
192         try {
193             Thread.sleep(5000);
194         } catch(InterruptedException e) {           
195            msoLogger.debug("Time Delay exception" + e )
196         }
197     }
198
199     /**
200      * finish NS task
201      */
202     public void addNSRelationship(DelegateExecution execution) {
203         msoLogger.trace("addNSRelationship")
204         String nsInstanceId = execution.getVariable("nsInstanceId")
205         if(nsInstanceId == null || nsInstanceId == ""){
206             msoLogger.debug(" create NS failed, so do not need to add relationship")
207             return
208         }
209         String globalSubscriberId = execution.getVariable("globalSubscriberId")
210         String serviceType = execution.getVariable("serviceType")
211         String serviceId = execution.getVariable("serviceId")
212         String addRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11">
213                                             <related-to>service-instance</related-to>
214                                             <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link>
215                                             <relationship-data>
216                                                 <relationship-key>customer.global-customer-id</relationship-key>
217                                                 <relationship-value>${MsoUtils.xmlEscape(globalSubscriberId)}</relationship-value>
218                                             </relationship-data>
219                                             <relationship-data>
220                                                 <relationship-key>service-subscription.service-type</relationship-key>
221                                                 <relationship-value>${MsoUtils.xmlEscape(serviceType)}</relationship-value>
222                                             </relationship-data>
223                                            <relationship-data>
224                                                 <relationship-key>service-instance.service-instance-id</relationship-key>
225                                                 <relationship-value>${MsoUtils.xmlEscape(nsInstanceId)}</relationship-value>
226                                             </relationship-data>           
227                                         </relationship>"""
228         String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
229         msoLogger.debug("Add Relationship req:\n" + addRelationPayload)
230         String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship"
231         APIResponse aaiRsp = executeAAIPutCall(execution, url, addRelationPayload)
232         msoLogger.debug("aai response status code:" + aaiRsp.getStatusCode())
233         msoLogger.debug("aai response content:" + aaiRsp.getResponseBodyAsString())
234         msoLogger.trace("Exit addNSRelationship")
235     }
236     
237     public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){
238         msoLogger.trace("Started Execute AAI Put Process") 
239         APIResponse apiResponse = null
240         try{
241             String uuid = utils.getRequestID()
242             msoLogger.debug("Generated uuid is: " + uuid) 
243             msoLogger.debug("URL to be used is: " + url) 
244             String userName = UrnPropertiesReader.getVariable("aai.auth", execution)
245             String password = UrnPropertiesReader.getVariable("mso.msoKey", execution)
246             String basicAuthCred = utils.getBasicAuth(userName,password)
247             RESTConfig config = new RESTConfig(url);
248             RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml");
249             if (basicAuthCred != null && !"".equals(basicAuthCred)) {
250                 client.addAuthorizationHeader(basicAuthCred)
251             }
252             apiResponse = client.httpPut(payload)
253             msoLogger.trace("Completed Execute AAI Put Process") 
254         }catch(Exception e){
255                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
256             throw new BpmnError("MSOWorkflowException")
257         }
258         return apiResponse
259     }
260
261     /**
262      * post request
263      * url: the url of the request
264      * requestBody: the body of the request
265      */
266     private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){
267         msoLogger.trace("Started Execute VFC adapter Post Process")
268         msoLogger.debug("url:"+url +"\nrequestBody:"+ requestBody)
269         APIResponse apiResponse = null
270         try{
271             RESTConfig config = new RESTConfig(url);
272             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");
273             apiResponse = client.httpPost(requestBody)
274             msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString())    
275             msoLogger.trace("Completed Execute VF-C adapter Post Process")
276         }catch(Exception e){
277                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
278             throw new BpmnError("MSOWorkflowException")
279         }        
280         return apiResponse
281     }
282 }