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