Merge "Add Ref Data" into casablanca
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / CreateDeviceResource.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - SO
4  * ================================================================================
5  * Copyright (C) 2018 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.json.JSONObject
24 import org.json.XML;
25
26 import static org.apache.commons.lang3.StringUtils.*;
27 import groovy.xml.XmlUtil
28 import groovy.json.*
29 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
30 import org.onap.so.bpmn.common.scripts.ExceptionUtil
31 import org.onap.so.bpmn.common.recipe.ResourceInput;
32 import org.onap.so.bpmn.common.resource.ResourceRequestBuilder
33 import org.onap.so.bpmn.core.WorkflowException
34 import org.onap.so.bpmn.core.domain.ModelInfo
35 import org.onap.so.bpmn.core.domain.VnfResource
36 import org.onap.so.bpmn.core.json.JsonUtils
37 import org.onap.so.bpmn.core.UrnPropertiesReader
38 import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder
39 import org.onap.so.logger.MsoLogger
40 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
41
42 import java.util.UUID;
43
44 import org.camunda.bpm.engine.delegate.BpmnError
45 import org.camunda.bpm.engine.delegate.DelegateExecution
46 import org.apache.commons.lang3.*
47 import org.apache.commons.codec.binary.Base64
48
49
50 /**
51  * This groovy class supports the <class>CreateDeviceResource.bpmn</class> process.
52  * flow for Device Resource Create
53  */
54 public class CreateDeviceResource extends AbstractServiceTaskProcessor {
55
56     String Prefix="CREDEVRES_"
57
58     ExceptionUtil exceptionUtil = new ExceptionUtil()
59
60     JsonUtils jsonUtil = new JsonUtils()
61
62     private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateDeviceResource.class)
63
64     public void preProcessRequest(DelegateExecution execution){
65         msoLogger.info(" ***** Started preProcessRequest *****")
66         String msg = ""
67         try {
68
69             //get bpmn inputs from resource request.
70             String requestId = execution.getVariable("mso-request-id")
71             String requestAction = execution.getVariable("requestAction")
72             msoLogger.info("The requestAction is: " + requestAction)
73             String recipeParamsFromRequest = execution.getVariable("recipeParams")
74             msoLogger.info("The recipeParams is: " + recipeParamsFromRequest)
75             String resourceInput = execution.getVariable("resourceInput")
76             msoLogger.info("The resourceInput is: " + resourceInput)
77             //Get ResourceInput Object
78             ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class)
79             execution.setVariable(Prefix + "ResourceInput", resourceInputObj)
80
81             String resourceInputPrameters = resourceInputObj.getResourceParameters()
82             String inputParametersJson = jsonUtil.getJsonValue(resourceInputPrameters, "requestInputs")
83             JSONObject inputParameters = new JSONObject(inputParametersJson)
84             execution.setVariable(Prefix + "ResourceRequestInputs", inputParameters)
85
86 //            String incomingRequest = resourceInputObj.getRequestsInputs()
87 //            String serviceParameters = JsonUtils.getJsonValue(incomingRequest, "service.parameters")
88 //            String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs")
89 //            JSONObject serviceInputParameters = new JSONObject(requestInputs)
90 //            execution.setVariable(Prefix + "ServiceParameters", serviceInputParameters)
91
92             //Deal with recipeParams
93             String recipeParamsFromWf = execution.getVariable("recipeParamXsd")
94             String resourceName = resourceInputObj.getResourceInstanceName()
95             if (isBlank(resourceName)) {
96                 msg = "Input resourceName is null"
97                 msoLogger.error(msg)
98             }
99             execution.setVariable("resourceName", resourceName)
100             msoLogger.info("resourceName:" + resourceName)
101
102             String resourceModelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid()
103             if (isBlank(resourceModelInvariantUuid)) {
104                 msg = "Input resourceModelInvariantUuid is null"
105                 msoLogger.error(msg)
106             }
107             execution.setVariable(Prefix + "ResourceModelInvariantUuid", resourceModelInvariantUuid)
108             msoLogger.info("resourceModelInvariantUuid:" + resourceModelInvariantUuid)
109
110             String resourceModelUuid = resourceInputObj.getResourceModelInfo().getModelUuid()
111             if (isBlank(resourceModelUuid)) {
112                 msg = "Input resourceModelUuid is null"
113                 msoLogger.error(msg)
114             }
115             execution.setVariable(Prefix + "ResourceModelUuid", resourceModelUuid)
116             msoLogger.info("resourceModelUuid:" + resourceModelUuid)
117
118             String resourceModelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
119             if (isBlank(resourceModelCustomizationUuid)) {
120                 msg = "Input resourceModelCustomizationUuid is null"
121                 msoLogger.error(msg)
122             }
123             execution.setVariable(Prefix + "ResourceModelCustomizationUuid", resourceModelCustomizationUuid)
124             msoLogger.info("resourceModelCustomizationUuid:" + resourceModelCustomizationUuid)
125
126             execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId())
127             execution.setVariable("mso-request-id", requestId)
128
129         } catch (Exception ex){
130             msg = "Exception in preProcessRequest " + ex.getMessage()
131             msoLogger.debug(msg)
132 //            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
133         }
134     }
135
136         public void checkDevType(DelegateExecution execution){
137                 msoLogger.info(" ***** Started checkDevType *****")
138                 try {
139
140                         JSONObject resourceInputParameters = execution.getVariable(Prefix + "ResourceRequestInputs")
141                         String devType = resourceInputParameters.get("device_class")
142
143                         if(StringUtils.isBlank(devType)) {
144                                 devType = "OTHER"
145                         }
146
147                         execution.setVariable("device_class", devType)
148
149                 } catch (Exception ex){
150                         String msg = "Exception in checkDevType " + ex.getMessage()
151                         msoLogger.debug(msg)
152 //                      exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
153                 }
154         }
155
156         private void setProgressUpdateVariables(DelegateExecution execution, String body) {
157                 def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
158                 execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
159                 execution.setVariable("CVFMI_updateResOperStatusRequest", body)
160         }
161
162         public void prepareUpdateProgress(DelegateExecution execution) {
163                 msoLogger.info(" ***** Started prepareUpdateProgress *****")
164                 ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput")
165                 String operType = resourceInputObj.getOperationType()
166                 String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
167                 String ServiceInstanceId = resourceInputObj.getServiceInstanceId()
168                 String modelName = resourceInputObj.getResourceModelInfo().getModelName()
169                 String operationId = resourceInputObj.getOperationId()
170                 String progress = execution.getVariable("progress")
171                 String status = execution.getVariable("status")
172                 String statusDescription = execution.getVariable("statusDescription")
173
174                 String body = """
175                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
176                         xmlns:ns="http://org.openecomp.mso/requestsdb">
177                         <soapenv:Header/>
178                 <soapenv:Body>
179                     <ns:updateResourceOperationStatus>
180                                <operType>${operType}</operType>
181                                <operationId>${operationId}</operationId>
182                                <progress>${progress}</progress>
183                                <resourceTemplateUUID>${resourceCustomizationUuid}</resourceTemplateUUID>
184                                <serviceId>${ServiceInstanceId}</serviceId>
185                                <status>${status}</status>
186                                <statusDescription>${statusDescription}</statusDescription>
187                     </ns:updateResourceOperationStatus>
188                 </soapenv:Body>
189                 </soapenv:Envelope>"""
190
191                 setProgressUpdateVariables(execution, body)
192                 msoLogger.info(" ***** Exit prepareUpdateProgress *****")
193         }
194
195         private void getVNFTemplatefromSDC(DelegateExecution execution){
196                 msoLogger.info(" ***** Started getVNFTemplatefromSDC *****")
197                 try {
198                         // To do
199
200
201                 } catch (Exception ex){
202                         String msg = "Exception in getVNFTemplatefromSDC " + ex.getMessage()
203                         msoLogger.debug(msg)
204 //                      exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
205                 }
206         }
207
208     public void prepareVnfAndModulesCreate(DelegateExecution execution) {
209         try {
210             msoLogger.trace("Inside prepareVnfAndModulesCreate of CreateDeviceResource ")
211             
212             JSONObject resourceInputParameters = execution.getVariable(Prefix + "ResourceRequestInputs")
213             String devType = resourceInputParameters.get("device_type")
214             String devVersion = resourceInputParameters.get("device_version")
215             
216             //get vnf model from SDC
217             getVNFTemplatefromSDC(execution)
218             
219             VnfResource vnf = execution.getVariable("vnfResource")
220             Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount")
221             String vnfModelInfoString = null;
222
223             if (vnf != null) {
224                 msoLogger.debug("getting model info for vnf # " + vnfsCreatedCount)
225                 ModelInfo vnfModelInfo = vnf.getModelInfo()
226                 vnfModelInfoString = vnfModelInfo.toString()
227             } else {
228                 msoLogger.debug("vnf is null")
229                 vnfModelInfoString = execution.getVariable("vnfModelInfo")
230             }
231
232             msoLogger.debug(" vnfModelInfoString :" + vnfModelInfoString)
233
234             // extract cloud configuration
235 //            String vimId = jsonUtil.getJsonValue(createVcpeServiceRequest,
236 //                    "requestDetails.cloudConfiguration.lcpCloudRegionId")
237 //            def cloudRegion = vimId.split("_")
238 //            execution.setVariable("cloudOwner", cloudRegion[0])
239 //            msoLogger.debug("cloudOwner: "+ cloudRegion[0])
240 //            execution.setVariable("cloudRegionId", cloudRegion[1])
241 //            msoLogger.debug("cloudRegionId: "+ cloudRegion[1])
242 //            execution.setVariable("lcpCloudRegionId", cloudRegion[1])
243 //            msoLogger.debug("lcpCloudRegionId: "+ cloudRegion[1])
244 //            String tenantId = jsonUtil.getJsonValue(createVcpeServiceRequest,
245 //                    "requestDetails.cloudConfiguration.tenantId")
246 //            execution.setVariable("tenantId", tenantId)
247 //            msoLogger.debug("tenantId: " + tenantId)
248             
249
250            execution.setVariable("cloudOwner", "")
251
252            execution.setVariable("cloudRegionId", "")
253        
254            execution.setVariable("lcpCloudRegionId", "")
255        
256            execution.setVariable("tenantId", "")       
257
258             String sdncVersion = execution.getVariable("sdncVersion")
259             msoLogger.debug("sdncVersion: " + sdncVersion)
260
261             msoLogger.trace("Completed prepareVnfAndModulesCreate of CreateVcpeResCustService ")
262         } catch (Exception ex) {
263             // try error in method block
264             String exceptionMessage = "Bpmn error encountered in CreateDeviceResource flow. Unexpected Error from method prepareVnfAndModulesCreate() - " + ex.getMessage()
265             msoLogger.debug(exceptionMessage)
266         }
267     }
268
269     // *******************************
270     //     Validate Vnf request Section -> increment count
271     // *******************************
272     public void validateVnfCreate(DelegateExecution execution) {
273
274         try {
275             msoLogger.trace("Inside validateVnfCreate of CreateDeviceResource ")
276
277             //Update Relationship between VNF to Device
278             addVNFAAIRelationShip(execution)
279
280             Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount")
281             vnfsCreatedCount++
282
283             execution.setVariable(Prefix + "VnfsCreatedCount", vnfsCreatedCount)
284
285             msoLogger.debug(" ***** Completed validateVnfCreate of CreateDeviceResource ***** " + " vnf # " + vnfsCreatedCount)
286         } catch (Exception ex) {
287             // try error in method block
288             String exceptionMessage = "Bpmn error encountered in CreateDeviceResource flow. Unexpected Error from method validateVnfCreate() - " + ex.getMessage()
289             msoLogger.debug(exceptionMessage)
290         }
291     }
292
293     public void addVNFAAIRelationShip(DelegateExecution execution) {
294
295         try {
296             msoLogger.trace("Inside addVNFAAIRelationShip of CreateDeviceResource ")
297
298
299
300             msoLogger.debug(" ***** Completed addVNFAAIRelationShip of CreateDeviceResource ***** ")
301         } catch (Exception ex) {
302             // try error in method block
303             String exceptionMessage = "Bpmn error encountered in CreateDeviceResource flow. Unexpected Error from method addVNFAAIRelationShip() - " + ex.getMessage()
304             msoLogger.debug(exceptionMessage)
305         }
306     }
307
308         public void sendSyncResponse (DelegateExecution execution) {
309                 msoLogger.debug(" *** sendSyncResponse *** ")
310
311                 try {
312                         String operationStatus = "finished"
313                         // RESTResponse for main flow
314                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
315                         msoLogger.debug(" sendSyncResponse to APIH:" + "\n" + resourceOperationResp)
316                         sendWorkflowResponse(execution, 202, resourceOperationResp)
317                         execution.setVariable("sentSyncResponse", true)
318
319                 } catch (Exception ex) {
320                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
321                         msoLogger.debug(msg)
322 //                      exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
323                 }
324                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****")
325         }
326 }