970a4f7d07b7f1e333a40792493cdc70a17fc7b6
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / CreateVFCNSResource.groovy
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * OPENECOMP - SO\r
4  * ================================================================================\r
5  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.\r
6  * ================================================================================\r
7  * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * you may not use this file except in compliance with the License.\r
9  * You may obtain a copy of the License at\r
10  * \r
11  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * \r
13  * Unless required by applicable law or agreed to in writing, software\r
14  * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * See the License for the specific language governing permissions and\r
17  * limitations under the License.\r
18  * ============LICENSE_END=========================================================\r
19  */\r
20 \r
21 package org.openecomp.mso.bpmn.infrastructure.scripts;\r
22 \r
23 import static org.apache.commons.lang3.StringUtils.*;\r
24 import groovy.xml.XmlUtil\r
25 import groovy.json.*\r
26 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor \r
27 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil \r
28 import org.openecomp.mso.bpmn.core.WorkflowException \r
29 import org.openecomp.mso.bpmn.core.json.JsonUtils \r
30 import org.openecomp.mso.rest.APIResponse\r
31 \r
32 import java.util.UUID;\r
33 \r
34 import org.camunda.bpm.engine.delegate.BpmnError \r
35 import org.camunda.bpm.engine.runtime.Execution\r
36 import org.apache.commons.lang3.*\r
37 import org.apache.commons.codec.binary.Base64;\r
38 import org.springframework.web.util.UriUtils \r
39 import org.openecomp.mso.rest.RESTClient \r
40 import org.openecomp.mso.rest.RESTConfig\r
41 import org.openecomp.mso.rest.APIResponse;\r
42 \r
43 /**\r
44  * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process.\r
45  * flow for VFC Network Service Create\r
46  */\r
47 public class CreateVFCNSResource extends AbstractServiceTaskProcessor {\r
48 \r
49     String vfcUrl = "/vfc/rest/v1/vfcadapter"\r
50     \r
51     String host = "http://mso.mso.testlab.openecomp.org:8080"\r
52     \r
53     ExceptionUtil exceptionUtil = new ExceptionUtil()\r
54 \r
55     JsonUtils jsonUtil = new JsonUtils()\r
56     \r
57     /**CreateVFCNSResource\r
58      * Pre Process the BPMN Flow Request\r
59      * Inclouds:\r
60      * generate the nsOperationKey\r
61      * generate the nsParameters\r
62      */\r
63     public void preProcessRequest (Execution execution) {\r
64            def isDebugEnabled=execution.getVariable("isDebugLogEnabled")\r
65        String msg = ""\r
66        utils.log("INFO", " *** preProcessRequest() *** ", isDebugEnabled)\r
67        try {\r
68            //deal with nsName and Description\r
69            String nsServiceName = execution.getVariable("nsServiceName")\r
70            String nsServiceDescription = execution.getVariable("nsServiceDescription")\r
71            utils.log("INFO", "nsServiceName:" + nsServiceName + " nsServiceDescription:" + nsServiceDescription, isDebugEnabled)\r
72            //deal with operation key\r
73            String globalSubscriberId = execution.getVariable("globalSubscriberId")\r
74            utils.log("INFO", "globalSubscriberId:" + globalSubscriberId, isDebugEnabled)\r
75            String serviceType = execution.getVariable("serviceType")\r
76            utils.log("INFO", "serviceType:" + serviceType, isDebugEnabled)\r
77            String serviceId = execution.getVariable("serviceId")\r
78            utils.log("INFO", "serviceId:" + serviceId, isDebugEnabled)\r
79            String operationId = execution.getVariable("operationId")\r
80            utils.log("INFO", "serviceType:" + serviceType, isDebugEnabled)\r
81            String nodeTemplateUUID = execution.getVariable("resourceUUID")\r
82            utils.log("INFO", "nodeTemplateUUID:" + nodeTemplateUUID, isDebugEnabled)\r
83            /*\r
84             * segmentInformation needed as a object of segment\r
85             * {\r
86             *     "domain":"",\r
87             *     "nodeTemplateName":"",\r
88             *     "nodeType":"",\r
89             *     "nsParameters":{\r
90             *       //this is the nsParameters sent to VF-C\r
91             *     }\r
92             * }\r
93             */\r
94            String nsParameters = execution.getVariable("resourceParameters")\r
95            utils.log("INFO", "nsParameters:" + nsParameters, isDebugEnabled)\r
96            String nsOperationKey = """{\r
97                    "globalSubscriberId":"${globalSubscriberId}",\r
98                    "serviceType":"${serviceType}",\r
99                    "serviceId":"${serviceId}",\r
100                    "operationId":"${operationId}",\r
101                    "nodeTemplateUUID":"${nodeTemplateUUID}"\r
102                     }"""\r
103            execution.setVariable("nsOperationKey", nsOperationKey);\r
104            execution.setVariable("nsParameters", nsParameters)\r
105            \r
106 \r
107        } catch (BpmnError e) {\r
108            throw e;\r
109        } catch (Exception ex){\r
110            msg = "Exception in preProcessRequest " + ex.getMessage()\r
111            utils.log("INFO", msg, isDebugEnabled)\r
112            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)\r
113        }\r
114        utils.log("INFO"," ***** Exit preProcessRequest *****",  isDebugEnabled)\r
115         }\r
116 \r
117     /**\r
118      * create NS task\r
119      */\r
120     public void createNetworkService(Execution execution) {\r
121         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")\r
122         utils.log("INFO"," *****  createNetworkService *****",  isDebugEnabled)\r
123         String nsOperationKey = execution.getVariable("nsOperationKey");\r
124         String nsParameters = execution.getVariable("nsParameters");\r
125         String nsServiceName = execution.getVariable("nsServiceName")\r
126         String nsServiceDescription = execution.getVariable("nsServiceDescription")\r
127         String reqBody ="""{\r
128                 "nsServiceName":"${nsServiceName}",\r
129                 "nsServiceDescription":"${nsServiceDescription}",\r
130                 "nsOperationKey":${nsOperationKey},\r
131                 "nsParameters":${nsParameters}\r
132                }"""\r
133         APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody)\r
134         String returnCode = apiResponse.getStatusCode()\r
135         String aaiResponseAsString = apiResponse.getResponseBodyAsString()\r
136         String nsInstanceId = "";\r
137         if(returnCode== "200" || returnCode == "201"){\r
138             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")\r
139         }\r
140         execution.setVariable("nsInstanceId", nsInstanceId)\r
141         utils.log("INFO"," *****Exit  createNetworkService *****",  isDebugEnabled)\r
142     }\r
143 \r
144     /**\r
145      * instantiate NS task\r
146      */\r
147     public void instantiateNetworkService(Execution execution) {\r
148         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")\r
149         utils.log("INFO"," *****  instantiateNetworkService *****",  isDebugEnabled)\r
150         String nsOperationKey = execution.getVariable("nsOperationKey");\r
151         String nsParameters = execution.getVariable("nsParameters");\r
152         String nsServiceName = execution.getVariable("nsServiceName")\r
153         String nsServiceDescription = execution.getVariable("nsServiceDescription")\r
154         String reqBody ="""{\r
155         "nsServiceName":"${nsServiceName}",\r
156         "nsServiceDescription":"${nsServiceDescription}",\r
157         "nsOperationKey":${nsOperationKey},\r
158         "nsParameters":${nsParameters}\r
159        }"""\r
160         String nsInstanceId = execution.getVariable("nsInstanceId")\r
161         String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate"\r
162         APIResponse apiResponse = postRequest(execution, url, reqBody)\r
163         String returnCode = apiResponse.getStatusCode()\r
164         String aaiResponseAsString = apiResponse.getResponseBodyAsString()\r
165         String jobId = "";\r
166         if(returnCode== "200"|| returnCode == "201"){\r
167             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")\r
168         }\r
169         execution.setVariable("jobId", jobId)\r
170         utils.log("INFO"," *****Exit  instantiateNetworkService *****",  isDebugEnabled)\r
171     }\r
172 \r
173     /**\r
174      * query NS task\r
175      */\r
176     public void queryNSProgress(Execution execution) {\r
177         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")\r
178         utils.log("INFO"," *****  queryNSProgress *****",  isDebugEnabled)\r
179         String jobId = execution.getVariable("jobId")\r
180         String nsOperationKey = execution.getVariable("nsOperationKey");\r
181         String url = host + vfcUrl + "/jobs/" + jobId\r
182         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)\r
183         String returnCode = apiResponse.getStatusCode()\r
184         String aaiResponseAsString = apiResponse.getResponseBodyAsString()\r
185         String operationStatus = "error"\r
186         if(returnCode== "200"|| returnCode == "201"){\r
187             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")\r
188         }\r
189         execution.setVariable("operationStatus", operationStatus)\r
190         utils.log("INFO"," *****Exit  queryNSProgress *****",  isDebugEnabled)\r
191     }\r
192 \r
193     /**\r
194      * delay 5 sec \r
195      */\r
196     public void timeDelay(Execution execution) {\r
197         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")\r
198         try {\r
199             Thread.sleep(5000);\r
200         } catch(InterruptedException e) {           \r
201             utils.log("ERROR", "Time Delay exception" + e , isDebugEnabled)\r
202         }\r
203     }\r
204 \r
205     /**\r
206      * finish NS task\r
207      */\r
208     public void addNSRelationship(Execution execution) {\r
209         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")\r
210         utils.log("INFO"," ***** addNSRelationship *****",  isDebugEnabled)\r
211         String nsInstanceId = execution.getVariable("nsInstanceId")\r
212         if(nsInstanceId == null || nsInstanceId == ""){\r
213             utils.log("INFO"," create NS failed, so do not need to add relationship",  isDebugEnabled)\r
214             return\r
215         }\r
216         String globalSubscriberId = execution.getVariable("globalSubscriberId")\r
217         String serviceType = execution.getVariable("serviceType")\r
218         String serviceId = execution.getVariable("serviceId")\r
219         String addRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11">\r
220                                             <related-to>service-instance</related-to>\r
221                                             <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link>\r
222                                             <relationship-data>\r
223                                                 <relationship-key>customer.global-customer-id</relationship-key>\r
224                                                 <relationship-value>${globalSubscriberId}</relationship-value>\r
225                                             </relationship-data>\r
226                                             <relationship-data>\r
227                                                 <relationship-key>service-subscription.service-type</relationship-key>\r
228                                                 <relationship-value>${serviceType}</relationship-value>\r
229                                             </relationship-data>\r
230                                            <relationship-data>\r
231                                                 <relationship-key>service-instance.service-instance-id</relationship-key>\r
232                                                 <relationship-value>${nsInstanceId}</relationship-value>\r
233                                             </relationship-data>           \r
234                                         </relationship>"""\r
235         String endpoint = execution.getVariable("URN_aai_endpoint")  \r
236         utils.log("INFO","Add Relationship req:\n" + addRelationPayload,  isDebugEnabled)\r
237         String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship"\r
238         APIResponse aaiRsp = executeAAIPutCall(execution, url, addRelationPayload)\r
239         utils.log("INFO","aai response status code:" + aaiRsp.getStatusCode(),  isDebugEnabled)\r
240         utils.log("INFO","aai response content:" + aaiRsp.getResponseBodyAsString(),  isDebugEnabled)\r
241         utils.log("INFO"," *****Exit addNSRelationship *****",  isDebugEnabled)\r
242     }\r
243     \r
244     public APIResponse executeAAIPutCall(Execution execution, String url, String payload){\r
245         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")\r
246         utils.log("INFO", " ======== Started Execute AAI Put Process ======== ",  isDebugEnabled) \r
247         APIResponse apiResponse = null\r
248         try{\r
249             String uuid = utils.getRequestID()\r
250             utils.log("INFO","Generated uuid is: " + uuid,  isDebugEnabled) \r
251             utils.log("INFO","URL to be used is: " + url,  isDebugEnabled) \r
252             String userName = execution.getVariable("URN_aai_auth")\r
253             String password = execution.getVariable("URN_mso_msoKey")\r
254             String basicAuthCred = utils.getBasicAuth(userName,password)\r
255             RESTConfig config = new RESTConfig(url);\r
256             RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml");\r
257             if (basicAuthCred != null && !"".equals(basicAuthCred)) {\r
258                 client.addAuthorizationHeader(basicAuthCred)\r
259             }\r
260             apiResponse = client.httpPut(payload)\r
261             utils.log("INFO","======== Completed Execute AAI Put Process ======== ",  isDebugEnabled) \r
262         }catch(Exception e){\r
263             utils.log("ERROR","Exception occured while executing AAI Put Call. Exception is: \n" + e,  isDebugEnabled) \r
264             throw new BpmnError("MSOWorkflowException")\r
265         }\r
266         return apiResponse\r
267     }\r
268     \r
269     /**\r
270      * post request\r
271      * url: the url of the request\r
272      * requestBody: the body of the request\r
273      */\r
274     private APIResponse postRequest(Execution execution, String url, String requestBody){\r
275         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")\r
276         utils.log("INFO"," ***** Started Execute VFC adapter Post Process *****",  isDebugEnabled)\r
277         utils.log("INFO","url:"+url +"\nrequestBody:"+ requestBody,  isDebugEnabled)\r
278         APIResponse apiResponse = null\r
279         try{\r
280             RESTConfig config = new RESTConfig(url);\r
281             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");\r
282             apiResponse = client.httpPost(requestBody)\r
283             utils.log("INFO","response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString(),  isDebugEnabled)    \r
284             utils.log("INFO","======== Completed Execute VF-C adapter Post Process ======== ",  isDebugEnabled)\r
285         }catch(Exception e){\r
286             utils.log("ERROR","Exception occured while executing AAI Post Call. Exception is: \n" + e,  isDebugEnabled)\r
287             throw new BpmnError("MSOWorkflowException")\r
288         }        \r
289         return apiResponse\r
290     }\r
291 }\r