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