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