34f2f0157d72a74e9e8acd54a030bee31f097a84
[so.git] /
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 org.onap.so.client.aai.AAIObjectType
24 import org.onap.so.client.aai.entities.uri.AAIResourceUri
25 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
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.core.json.JsonUtils
31 //import org.onap.so.client.HttpClient
32 //import org.onap.so.client.RestRequest
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 import org.onap.so.bpmn.core.UrnPropertiesReader
39
40 import groovy.json.*
41 //import javax.ws.rs.core.Response
42 import org.onap.so.utils.TargetEntity
43
44 /**
45  * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process.
46  * flow for VFC Network Service Create
47  */
48 public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
49         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVFCNSResource.class);
50
51 //    String vfcUrl = "/vfc/rest/v1/vfcadapter"
52
53 //    String host = "http://mso.mso.testlab.openecomp.org:8080"
54         
55     ExceptionUtil exceptionUtil = new ExceptionUtil()
56
57     JsonUtils jsonUtil = new JsonUtils()
58
59     /**
60      * CreateVFCNSResource
61      * Pre Process the BPMN Flow Request
62      * Inclouds:
63      * generate the nsOperationKey
64      * generate the nsParameters
65      */
66     public void preProcessRequest (DelegateExecution execution) {
67         JsonUtils jsonUtil = new JsonUtils()
68
69        String msg = ""
70        msoLogger.trace("preProcessRequest() ")
71        try {
72            //deal with nsName and Description
73            String resourceInput = execution.getVariable("resourceInput")
74
75            String resourceParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
76            // get service name
77            String resourceName = jsonUtil.getJsonValue(resourceInput, "resourceInstanceName")
78            execution.setVariable("nsServiceName", resourceName)
79
80            String nsServiceDescription = execution.getVariable("nsServiceDescription")
81            msoLogger.info("nsServiceName:" + resourceName + " nsServiceDescription:" + nsServiceDescription)
82            //deal with operation key
83            String globalSubscriberId = jsonUtil.getJsonValue(resourceInput, "globalSubscriberId")
84            msoLogger.info("globalSubscriberId:" + globalSubscriberId)
85            //set local globalSubscriberId variable
86            execution.setVariable("globalSubscriberId", globalSubscriberId);
87            String serviceType = execution.getVariable("serviceType")
88            msoLogger.info("serviceType:" + serviceType)
89
90            String serviceId = execution.getVariable("serviceInstanceId")
91            msoLogger.info("serviceId:" + serviceId)
92
93            String operationId = jsonUtil.getJsonValue(resourceInput, "operationId")
94            msoLogger.info("serviceType:" + serviceType)
95
96            String nodeTemplateUUID = jsonUtil.getJsonValue(resourceInput, "resourceModelInfo.modelCustomizationUuid")
97            String nsServiceModelUUID = jsonUtil.getJsonValue(resourceParameters, "requestInputs.nsd0_providing_service_uuid")
98            msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID)
99            /*
100             * segmentInformation needed as a object of segment
101             * {
102             *     "domain":"",
103             *     "nodeTemplateName":"",
104             *     "nodeType":"",
105             *     "nsParameters":{
106             *       //this is the nsParameters sent to VF-C
107             *     }
108             * }
109             */
110            String nsParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
111            msoLogger.info("nsParameters:" + nsParameters)
112            String nsOperationKey = """{
113                    "globalSubscriberId":"${globalSubscriberId}",
114                    "serviceType":"${serviceType}",
115                    "serviceId":"${serviceId}",
116                    "operationId":"${operationId}",
117                    "nodeTemplateUUID":"${nodeTemplateUUID}"
118                     }"""
119            execution.setVariable("nsOperationKey", nsOperationKey);
120            execution.setVariable("nsParameters", nsParameters)
121            execution.setVariable("nsServiceModelUUID", nsServiceModelUUID);
122
123            String vfcAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.vfc.rest.endpoint", execution)
124                    
125            if (vfcAdapterUrl == null || vfcAdapterUrl.isEmpty()) {
126                   msg = getProcessKey(execution) + ': mso:adapters:vfcc:rest:endpoint URN mapping is not defined'
127                   msoLogger.debug(msg)
128            }
129
130            while (vfcAdapterUrl.endsWith('/')) {
131                   vfcAdapterUrl = vfcAdapterUrl.substring(0, vfcAdapterUrl.length()-1)
132            }               
133                    
134            execution.setVariable("vfcAdapterUrl", vfcAdapterUrl)
135
136        } catch (BpmnError e) {
137            throw e;
138        } catch (Exception ex){
139            msg = "Exception in preProcessRequest " + ex.getMessage()
140            msoLogger.info(msg)
141            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
142        }
143        msoLogger.trace("Exit preProcessRequest ")
144         }
145
146     /**
147      * create NS task
148      */
149     public void createNetworkService(DelegateExecution execution) {
150         msoLogger.trace("createNetworkService ")
151         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
152         String nsOperationKey = execution.getVariable("nsOperationKey");
153         String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID");
154         String nsParameters = execution.getVariable("nsParameters");
155         String nsServiceName = execution.getVariable("nsServiceName")
156         String nsServiceDescription = execution.getVariable("nsServiceDescription")
157         String locationConstraints = jsonUtil.getJsonValue(nsParameters, "locationConstraints")
158         String requestInputs = jsonUtil.getJsonValue(nsParameters, "requestInputs")
159         String reqBody ="""{
160                 "nsServiceName":"${nsServiceName}",
161                 "nsServiceDescription":"${nsServiceDescription}",
162                 "nsServiceModelUUID":"${nsServiceModelUUID}",
163                 "nsOperationKey":${nsOperationKey},
164                 "nsParameters":{
165                      "locationConstraints":${locationConstraints},
166                      "additionalParamForNs":${requestInputs}
167                 }
168                }"""
169         APIResponse apiResponse = postRequest(execution, vfcAdapterUrl + "/ns", reqBody)
170         String returnCode = apiResponse.getStatusCode()
171         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
172         String nsInstanceId = "";
173         if(returnCode== "200" || returnCode == "201"){
174             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
175         }
176         execution.setVariable("nsInstanceId", nsInstanceId)
177         msoLogger.info(" *****Exit  createNetworkService *****")
178     }
179
180     /**
181      * instantiate NS task
182      */
183     public void instantiateNetworkService(DelegateExecution execution) {
184         msoLogger.trace("instantiateNetworkService ")
185         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
186         String nsOperationKey = execution.getVariable("nsOperationKey");
187         String nsParameters = execution.getVariable("nsParameters");
188         String nsServiceName = execution.getVariable("nsServiceName")
189         String nsServiceDescription = execution.getVariable("nsServiceDescription")
190         String reqBody ="""{
191         "nsServiceName":"${nsServiceName}",
192         "nsServiceDescription":"${nsServiceDescription}",
193         "nsOperationKey":${nsOperationKey},
194         "nsParameters":${nsParameters}
195        }"""
196         String nsInstanceId = execution.getVariable("nsInstanceId")
197         String url = vfcAdapterUrl + "/ns/" +nsInstanceId + "/instantiate"
198         APIResponse apiResponse = postRequest(execution, url, reqBody)
199         String returnCode = apiResponse.getStatusCode()
200         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
201         String jobId = "";
202         if(returnCode== "200"|| returnCode == "201"){
203             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
204         }
205         execution.setVariable("jobId", jobId)
206         msoLogger.info(" *****Exit  instantiateNetworkService *****")
207     }
208
209     /**
210      * query NS task
211      */
212     public void queryNSProgress(DelegateExecution execution) {
213         msoLogger.trace("queryNSProgress ")
214         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
215         String jobId = execution.getVariable("jobId")
216         String nsOperationKey = execution.getVariable("nsOperationKey");
217         String url = vfcAdapterUrl + "/jobs/" + jobId
218         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)
219         String returnCode = apiResponse.getStatusCode()
220         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
221         String operationStatus = "error"
222         if(returnCode== "200"|| returnCode == "201"){
223             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
224         }
225         execution.setVariable("operationStatus", operationStatus)
226         msoLogger.info(" *****Exit  queryNSProgress *****")
227     }
228
229     /**
230      * delay 5 sec
231      */
232     public void timeDelay(DelegateExecution execution) {
233         try {
234             Thread.sleep(5000);
235         } catch(InterruptedException e) {
236             msoLogger.error( "Time Delay exception" + e.getMessage());
237         }
238     }
239
240     /**
241      * finish NS task
242      */
243     public void addNSRelationship(DelegateExecution execution) {
244         msoLogger.trace("addNSRelationship ")
245         String nsInstanceId = execution.getVariable("nsInstanceId")
246         if(nsInstanceId == null || nsInstanceId == ""){
247             msoLogger.info(" create NS failed, so do not need to add relationship")
248             return
249         }
250         String globalSubscriberId = execution.getVariable("globalSubscriberId")
251         String serviceType = execution.getVariable("serviceType")
252         String serviceId = execution.getVariable("serviceInstanceId")
253
254         AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,nsInstanceId)
255         AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,serviceId)
256
257         try{
258             getAAIClient().connect(nsUri,relatedServiceUri)
259             msoLogger.info("NS relationship to Service added successfully")
260         }catch(Exception e){
261             msoLogger.error("Exception occured while Creating NS relationship."+ e.getMessage());
262             throw new BpmnError("MSOWorkflowException")
263         }
264     }
265
266     /**
267      * post request
268      * url: the url of the request
269      * requestBody: the body of the request
270      */
271     private APIResponse postRequest(DelegateExecution execution, String urlString, String requestBody){
272         msoLogger.trace("Started Execute VFC adapter Post Process ")
273         msoLogger.info("url:" + urlString +"\nrequestBody:"+ requestBody)
274         APIResponse apiResponse = null
275 //        try{
276
277 //                      URL url = new URL(urlString);
278
279 //                      HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER)
280 //                      httpClient.addAdditionalHeader("Accept", "application/json")
281 //                      httpClient.addAdditionalHeader("Authorization", "Basic YnBlbDpwYXNzd29yZDEk")
282
283 //                      apiResponse = httpClient.post(requestBody)
284 //                      msoLogger.info("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class))
285
286                 // Get the Basic Auth credentials for the VFCAdapter (yes... we ARE using the PO adapters credentials)
287                 String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution)
288                 
289                 msoLogger.debug("basicAuthValuePO: " + basicAuthValuePO)
290                 if (basicAuthValuePO == null || basicAuthValuePO.isEmpty()) {
291                         msoLogger.debug("mso:adapters:po:auth URN mapping is not defined")
292                 }                       
293
294                 RESTConfig config = new RESTConfig(urlString)
295                 RESTClient client = null;
296                 int statusCode = 0;
297                 try {
298                         client = new RESTClient(config).addHeader("Accept", "application/json").addAuthorizationHeader(basicAuthValuePO)
299
300                         apiResponse = client.httpPost(requestBody)
301                         
302                         statusCode = apiResponse.getStatusCode()
303                         
304                         if(statusCode == 200 || statusCode == 201) {
305                                 return apiResponse
306                         }
307                 }catch(Exception e){
308                         msoLogger.error("VFC Aatpter Post Call Exception using mso.adapters.po.auth:" + e.getMessage());
309                 }
310                 
311                 msoLogger.debug("response code:"+ statusCode +"\nresponse body:"+ apiResponse.getResponseBodyAsString())
312                 
313                 msoLogger.debug("VFC Aatpter Post Call using mso.msoKey")
314                 String basicAuthValue =  UrnPropertiesReader.getVariable("mso.msoKey", execution)
315                 msoLogger.debug("basicAuthValue: " + basicAuthValue)
316                 if (basicAuthValue == null || basicAuthValue.isEmpty()) {
317                         msoLogger.debug("mso:msoKey URN mapping is not defined")
318                 }
319                 try {
320                         client = new RESTClient(config).addHeader("Accept", "application/json").addAuthorizationHeader(basicAuthValue)
321
322                         apiResponse = client.httpPost(requestBody)
323                         
324                         statusCode = apiResponse.getStatusCode()
325                         
326                         if(statusCode == 200 || statusCode == 201) {
327                                 return apiResponse
328                         }
329                 }catch(Exception e){
330                         msoLogger.error("VFC Aatpter Post Call Exception using mso.msoKey:" + e.getMessage());
331                         
332                 }
333                                         
334                 msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString())
335                 
336                 msoLogger.debug("VFC Aatpter Post Call using mso.db.auth")
337                 String basicAuthValuedb =  UrnPropertiesReader.getVariable("mso.db.auth", execution)
338                 msoLogger.debug("basicAuthValuedb: " + basicAuthValuedb)
339                 if (basicAuthValuedb == null || basicAuthValuedb.isEmpty()) {
340                         msoLogger.debug("mso:db.auth URN mapping is not defined")
341                 }
342                 try {
343                         client = new RESTClient(config).addHeader("Accept", "application/json").addAuthorizationHeader(basicAuthValuedb)
344
345                         apiResponse = client.httpPost(requestBody)
346                         statusCode = apiResponse.getStatusCode()
347                         
348                         if(statusCode == 200 || statusCode == 201) {
349                                 return apiResponse
350                         }
351                 }catch(Exception e){
352                         msoLogger.error("VFC Aatpter Post Call Exception using mso.msoKey:" + e.getMessage());
353                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VFC Aatpter Post Call Exception by using mso.msoKey or mso.adapters.po.auth")
354                 }
355         
356                         
357                 msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString())
358                 String auth = "Basic QlBFTENsaWVudDpwYXNzd29yZDEk"
359                 msoLogger.debug("auth: " + basicAuthValuedb)
360                 client = new RESTClient(config).addHeader("Accept", "application/json").addAuthorizationHeader(auth)
361                 
362                 apiResponse = client.httpPost(requestBody)
363                 
364                 msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString())
365                 
366                 msoLogger.trace("Completed Execute VF-C adapter Post Process ")
367         
368         return apiResponse
369     }
370
371         public void sendSyncResponse (DelegateExecution execution) {
372                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
373                 utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
374
375                 try {
376                         String operationStatus = execution.getVariable("operationStatus")
377                         // RESTResponse for main flow
378                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
379                         utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled)
380                         sendWorkflowResponse(execution, 202, resourceOperationResp)
381                         execution.setVariable("sentSyncResponse", true)
382
383                 } catch (Exception ex) {
384                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
385                         utils.log("DEBUG", msg, isDebugEnabled)
386                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
387                 }
388                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
389         }
390
391 }