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