901964f465066faa5039574830609932e750d5a1
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - SO
4  * ================================================================================
5  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License")
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts
24
25 import org.onap.so.client.HttpClientFactory
26 import org.onap.so.client.aai.AAIObjectType
27 import org.onap.so.client.aai.entities.uri.AAIResourceUri
28 import org.onap.so.client.aai.entities.uri.AAIUriFactory
29 import org.camunda.bpm.engine.delegate.BpmnError
30 import org.camunda.bpm.engine.delegate.DelegateExecution
31 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
32 import org.onap.so.bpmn.common.scripts.ExceptionUtil
33 import org.onap.so.bpmn.core.json.JsonUtils
34 import org.onap.so.client.HttpClient
35 import org.slf4j.Logger
36 import org.slf4j.LoggerFactory
37 import org.onap.so.bpmn.core.UrnPropertiesReader
38
39 import javax.ws.rs.core.Response
40 import org.onap.so.utils.TargetEntity
41
42 /**
43  * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process.
44  * flow for VFC Network Service Create
45  */
46 public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
47     private static final Logger logger = LoggerFactory.getLogger( CreateVFCNSResource.class)
48
49     ExceptionUtil exceptionUtil = new ExceptionUtil()
50
51     JsonUtils jsonUtil = new JsonUtils()
52
53     /**
54      * CreateVFCNSResource
55      * Pre Process the BPMN Flow Request
56      * Inclouds:
57      * generate the nsOperationKey
58      * generate the nsParameters
59      */
60     public void preProcessRequest (DelegateExecution execution) {
61         JsonUtils jsonUtil = new JsonUtils()
62
63        String msg = ""
64        logger.trace("preProcessRequest() ")
65        try {
66            //deal with nsName and Description
67            String resourceInput = execution.getVariable("resourceInput")
68
69            String resourceParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
70            // get service name
71            String resourceName = jsonUtil.getJsonValue(resourceInput, "resourceInstanceName")
72            execution.setVariable("nsServiceName", resourceName)
73
74            String nsServiceDescription = execution.getVariable("nsServiceDescription")
75            logger.info("nsServiceName:" + resourceName + " nsServiceDescription:" + nsServiceDescription)
76            //deal with operation key
77            String globalSubscriberId = jsonUtil.getJsonValue(resourceInput, "globalSubscriberId")
78            logger.info("globalSubscriberId:" + globalSubscriberId)
79            //set local globalSubscriberId variable
80            execution.setVariable("globalSubscriberId", globalSubscriberId)
81            String serviceType = execution.getVariable("serviceType")
82            logger.info("serviceType:" + serviceType)
83
84            String serviceId = execution.getVariable("serviceInstanceId")
85            logger.info("serviceId:" + serviceId)
86
87            String operationId = jsonUtil.getJsonValue(resourceInput, "operationId")
88            logger.info("serviceType:" + serviceType)
89
90            String nodeTemplateUUID = jsonUtil.getJsonValue(resourceInput, "resourceModelInfo.modelCustomizationUuid")
91            String nsServiceModelUUID = jsonUtil.getJsonValue(resourceParameters, "requestInputs.nsd0_providing_service_uuid")
92            logger.info("nodeTemplateUUID:" + nodeTemplateUUID)
93            /*
94             * segmentInformation needed as a object of segment
95             * {
96             *     "domain":"",
97             *     "nodeTemplateName":"",
98             *     "nodeType":"",
99             *     "nsParameters":{
100             *       //this is the nsParameters sent to VF-C
101             *     }
102             * }
103             */
104            String nsParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
105            logger.info("nsParameters:" + nsParameters)
106            String nsOperationKey = """{
107                    "globalSubscriberId":"${globalSubscriberId}",
108                    "serviceType":"${serviceType}",
109                    "serviceId":"${serviceId}",
110                    "operationId":"${operationId}",
111                    "nodeTemplateUUID":"${nodeTemplateUUID}"
112                     }"""
113            execution.setVariable("nsOperationKey", nsOperationKey)
114            execution.setVariable("nsParameters", nsParameters)
115            execution.setVariable("nsServiceModelUUID", nsServiceModelUUID)
116
117            String vfcAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.vfc.rest.endpoint", execution)
118                    
119            if (vfcAdapterUrl == null || vfcAdapterUrl.isEmpty()) {
120                   msg = getProcessKey(execution) + ': mso:adapters:vfcc:rest:endpoint URN mapping is not defined'
121                   logger.debug(msg)
122            }
123
124            while (vfcAdapterUrl.endsWith('/')) {
125                   vfcAdapterUrl = vfcAdapterUrl.substring(0, vfcAdapterUrl.length()-1)
126            }               
127                    
128            execution.setVariable("vfcAdapterUrl", vfcAdapterUrl)
129
130        } catch (BpmnError e) {
131            throw e
132        } catch (Exception ex){
133            msg = "Exception in preProcessRequest " + ex.getMessage()
134            logger.info(msg)
135            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
136        }
137        logger.trace("Exit preProcessRequest ")
138         }
139
140     /**
141      * create NS task
142      */
143     public void createNetworkService(DelegateExecution execution) {
144         logger.trace("createNetworkService ")
145         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
146         String nsOperationKey = execution.getVariable("nsOperationKey")
147         String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID")
148         String nsParameters = execution.getVariable("nsParameters")
149         String nsServiceName = execution.getVariable("nsServiceName")
150         String nsServiceDescription = execution.getVariable("nsServiceDescription")
151         String locationConstraints = jsonUtil.getJsonValue(nsParameters, "locationConstraints")
152         String requestInputs = jsonUtil.getJsonValue(nsParameters, "requestInputs")
153         String reqBody ="""{
154                 "nsServiceName":"${nsServiceName}",
155                 "nsServiceDescription":"${nsServiceDescription}",
156                 "nsServiceModelUUID":"${nsServiceModelUUID}",
157                 "nsOperationKey":${nsOperationKey},
158                 "nsParameters":{
159                      "locationConstraints":${locationConstraints},
160                      "additionalParamForNs":${requestInputs}
161                 }
162                }"""
163         Response apiResponse = postRequest(execution, vfcAdapterUrl + "/ns", reqBody)
164         String returnCode = apiResponse.getStatus ()
165         String aaiResponseAsString = apiResponse.readEntity(String.class)
166         String nsInstanceId = ""
167         if(returnCode== "200" || returnCode == "201"){
168             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
169         }
170         execution.setVariable("nsInstanceId", nsInstanceId)
171         logger.info(" *****Exit  createNetworkService *****")
172     }
173
174     /**
175      * instantiate NS task
176      */
177     public void instantiateNetworkService(DelegateExecution execution) {
178         logger.trace("instantiateNetworkService ")
179         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
180         String nsOperationKey = execution.getVariable("nsOperationKey")
181         String nsParameters = execution.getVariable("nsParameters")
182         String nsServiceName = execution.getVariable("nsServiceName")
183         String nsServiceDescription = execution.getVariable("nsServiceDescription")
184         String reqBody ="""{
185         "nsServiceName":"${nsServiceName}",
186         "nsServiceDescription":"${nsServiceDescription}",
187         "nsOperationKey":${nsOperationKey},
188         "nsParameters":${nsParameters}
189        }"""
190         String nsInstanceId = execution.getVariable("nsInstanceId")
191         String url = vfcAdapterUrl + "/ns/" +nsInstanceId + "/instantiate"
192         Response apiResponse = postRequest(execution, url, reqBody)
193         String returnCode = apiResponse.getStatus()
194         String aaiResponseAsString = apiResponse.readEntity(String.class)
195         String jobId = ""
196         if(returnCode== "200"|| returnCode == "201"){
197             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
198         }
199         execution.setVariable("jobId", jobId)
200         logger.info(" *****Exit  instantiateNetworkService *****")
201     }
202
203     /**
204      * query NS task
205      */
206     public void queryNSProgress(DelegateExecution execution) {
207         logger.trace("queryNSProgress ")
208         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
209         String jobId = execution.getVariable("jobId")
210         String nsOperationKey = execution.getVariable("nsOperationKey")
211         String url = vfcAdapterUrl + "/jobs/" + jobId
212         Response apiResponse = postRequest(execution, url, nsOperationKey)
213         String returnCode = apiResponse.getStatus()
214         String aaiResponseAsString = apiResponse.readEntity(String.class)
215         String operationStatus = "error"
216         if(returnCode== "200"|| returnCode == "201"){
217             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
218         }
219         execution.setVariable("operationStatus", operationStatus)
220         logger.info(" *****Exit  queryNSProgress *****")
221     }
222
223     /**
224      * delay 5 sec
225      */
226     public void timeDelay(DelegateExecution execution) {
227         try {
228             Thread.sleep(5000)
229         } catch(InterruptedException e) {
230             logger.error("Time Delay exception" + e.getMessage())
231         }
232     }
233
234     /**
235      * finish NS task
236      */
237     public void addNSRelationship(DelegateExecution execution) {
238         logger.trace("addNSRelationship ")
239         String nsInstanceId = execution.getVariable("nsInstanceId")
240         if(nsInstanceId == null || nsInstanceId == ""){
241             logger.info(" create NS failed, so do not need to add relationship")
242             return
243         }
244         String globalSubscriberId = execution.getVariable("globalSubscriberId")
245         String serviceType = execution.getVariable("serviceType")
246         String serviceId = execution.getVariable("serviceInstanceId")
247
248         AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,nsInstanceId)
249         AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,serviceId)
250
251         try{
252             getAAIClient().connect(nsUri,relatedServiceUri)
253             logger.info("NS relationship to Service added successfully")
254         }catch(Exception e){
255             logger.error("Exception occured while Creating NS relationship."+ e.getMessage())
256             throw new BpmnError("MSOWorkflowException")
257         }
258     }
259
260     /**
261      * post request
262      * url: the url of the request
263      * requestBody: the body of the request
264      */
265     private Response postRequest(DelegateExecution execution, String urlString, String requestBody){
266         logger.trace("Started Execute VFC adapter Post Process ")
267         logger.info("url:" + urlString +"\nrequestBody:"+ requestBody)
268         Response apiResponse = null
269         try{
270
271             URL url = new URL(urlString)
272             
273             // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7'
274             // user 'bepl' authHeader is the same with mso.db.auth
275             String basicAuthValuedb =  UrnPropertiesReader.getVariable("mso.db.auth", execution)
276             HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.VNF_ADAPTER)
277             httpClient.addAdditionalHeader("Accept", "application/json")
278             httpClient.addAdditionalHeader("Authorization", basicAuthValuedb)
279
280             apiResponse = httpClient.post(requestBody)
281             
282             logger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class))
283
284         }catch(Exception e){
285             logger.error("VFC Aatpter Post Call Exception:" + e.getMessage())
286             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VFC Aatpter Post Call Exception")
287         }               
288                 
289         logger.trace("Completed Execute VF-C adapter Post Process ")
290         
291         return apiResponse
292     }
293
294         public void sendSyncResponse (DelegateExecution execution) {
295                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
296                 logger.debug( " *** sendSyncResponse *** ")
297
298                 try {
299                         String operationStatus = execution.getVariable("operationStatus")
300                         // RESTResponse for main flow
301                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
302                         logger.debug( " sendSyncResponse to APIH:" + "\n" + resourceOperationResp)
303                         sendWorkflowResponse(execution, 202, resourceOperationResp)
304                         execution.setVariable("sentSyncResponse", true)
305
306                 } catch (Exception ex) {
307                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
308                         logger.debug( msg)
309                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
310                 }
311                 logger.debug(" ***** Exit sendSyncResopnse *****")
312         }
313
314 }