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