Containerization feature of SO
[so.git] / bpmn / mso-infrastructure-bpmn / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / CreateActivateSDNCResource.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.json.JsonUtils
35 import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder
36 import org.onap.so.rest.APIResponse
37 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
38 import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory
39 import java.util.UUID;
40
41 import org.camunda.bpm.engine.runtime.Execution
42 import org.camunda.bpm.engine.delegate.BpmnError 
43 import org.camunda.bpm.engine.delegate.DelegateExecution
44 import org.apache.commons.lang3.*
45 import org.apache.commons.codec.binary.Base64;
46 import org.springframework.web.util.UriUtils 
47 import org.onap.so.rest.RESTClient 
48 import org.onap.so.rest.RESTConfig
49
50 /**
51  * This groovy class supports the <class>CreateActivateSDNCResource.bpmn</class> process.
52  * flow for SDNC Network Resource Create
53  */
54 public class CreateActivateSDNCResource extends AbstractServiceTaskProcessor {
55
56     String Prefix="CRESDNCRES_"
57             
58     ExceptionUtil exceptionUtil = new ExceptionUtil()
59
60     JsonUtils jsonUtil = new JsonUtils()
61
62     SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
63     
64     public void preProcessRequest(DelegateExecution execution){
65         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
66         utils.log("INFO"," ***** Started preProcessRequest *****",  isDebugEnabled)
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             utils.log("INFO","The requestAction is: " + requestAction,  isDebugEnabled)
73             String recipeParamsFromRequest = execution.getVariable("recipeParams")
74             utils.log("INFO","The recipeParams is: " + recipeParamsFromRequest,  isDebugEnabled)
75             String resourceInput = execution.getVariable("resourceInput")
76             utils.log("INFO","The resourceInput is: " + resourceInput,  isDebugEnabled)
77             //Get ResourceInput Object
78             ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class)
79             execution.setVariable(Prefix + "resourceInput", resourceInputObj)
80             
81             //Deal with recipeParams
82             String recipeParamsFromWf = execution.getVariable("recipeParamXsd")
83             String resourceName = resourceInputObj.getResourceInstanceName()            
84             //For sdnc requestAction default is "createNetworkInstance"
85             String operationType = "Network"
86             String apiType = "network"
87             if(!StringUtils.isBlank(recipeParamsFromRequest)){
88                 //the operationType from worflow(first node) is second priority.
89                 operationType = jsonUtil.getJsonValue(recipeParamsFromRequest, "operationType")
90                 apiType = jsonUtil.getJsonValue(recipeParamsFromRequest, "apiType")
91             }
92             if(!StringUtils.isBlank(recipeParamsFromWf)){
93                 //the operationType from worflow(first node) is highest priority.
94                 operationType = jsonUtil.getJsonValue(recipeParamsFromWf, "operationType")
95                 apiType = jsonUtil.getJsonValue(recipeParamsFromRequest, "apiType")
96             }
97                   
98             execution.setVariable(Prefix + "operationType", operationType)        
99             execution.setVariable(Prefix + "apiType", apiType)
100             execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId())
101             execution.setVariable("mso-request-id", requestId)
102             execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId())
103             //TODO Here build networkrequest
104             
105         } catch (BpmnError e) {
106             throw e;
107         } catch (Exception ex){
108             String msg = "Exception in preProcessRequest " + ex.getMessage()
109             utils.log("DEBUG", msg, isDebugEnabled)
110             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
111         }
112     }
113
114     String customizeResourceParam(String netowrkInputParametersJson) {
115         List<Map<String, Object>> paramList = new ArrayList();
116         JSONObject jsonObject = new JSONObject(netowrkInputParametersJson);
117         Iterator iterator = jsonObject.keys();
118         while (iterator.hasNext()) {
119             String key = iterator.next();
120             HashMap<String, String> hashMap = new HashMap();
121             hashMap.put("name", key);
122             hashMap.put("value", jsonObject.get(key))
123             paramList.add(hashMap)
124         }
125         Map<String, List<Map<String, Object>>> paramMap = new HashMap();
126         paramMap.put("param", paramList);
127
128         return  new JSONObject(paramMap).toString();
129     }
130     
131     public void prepareSDNCRequest (DelegateExecution execution) {
132         String svcAction = "create"
133         prepareSDNCRequestReq(execution, svcAction, "")        
134     }
135     
136
137     public void prepareSDNCActivateRequest (DelegateExecution execution) {
138         String svcAction = "activate"
139         String sndcResourceId = execution.getVariable(Prefix + "sdncResourceId")
140         prepareSDNCRequestReq(execution, svcAction, sndcResourceId)
141     }
142     /**
143      * Pre Process the BPMN Flow Request
144      * Inclouds:
145      * generate the nsOperationKey
146      * generate the nsParameters
147      */
148     public void prepareSDNCRequestReq (DelegateExecution execution, String svcAction, String sdncResourceId) {
149         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
150         utils.log("INFO"," ***** Started prepareSDNCRequest *****",  isDebugEnabled)
151
152         try {
153             // get variables
154             String operationType = execution.getVariable(Prefix + "operationType")   
155             String sdnc_apiType = execution.getVariable(Prefix + "apiType")
156             String sdnc_svcAction = svcAction
157             String sdnc_requestAction = StringUtils.capitalize(sdnc_svcAction) + operationType +"Instance"  
158
159             String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback")
160             String createNetworkInput = execution.getVariable(Prefix + "networkRequest")
161
162             String hdrRequestId = execution.getVariable("mso-request-id")
163             String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId")
164             String source = execution.getVariable("source")
165             String sdnc_service_id = execution.getVariable(Prefix + "sdncServiceId")
166             ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput")
167             String serviceType = resourceInputObj.getServiceType()
168             String serviceModelInvariantUuid = resourceInputObj.getServiceModelInfo().getModelInvariantUuid()
169             String serviceModelUuid = resourceInputObj.getServiceModelInfo().getModelUuid()
170             String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion()
171             String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName()
172             String globalCustomerId = resourceInputObj.getGlobalSubscriberId()
173             String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid();
174             String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
175             String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid()
176             String modelName = resourceInputObj.getResourceModelInfo().getModelName()
177             String modelVersion = resourceInputObj.getResourceModelInfo().getModelVersion()
178             String resourceInputPrameters = resourceInputObj.getResourceParameters()
179             String netowrkInputParametersJson = jsonUtil.getJsonValue(resourceInputPrameters, "requestInputs")
180             //here convert json string to xml string
181             String netowrkInputParameters = XML.toString(new JSONObject(customizeResourceParam(netowrkInputParametersJson)))
182
183             // 1. prepare assign topology via SDNC Adapter SUBFLOW call
184             String sndcTopologyCreateRequest =
185                     """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
186                                                               xmlns:sdncadapter="http://org.openecomp.mso/workflow/sdnc/adapter/schema/v1" 
187                                                               xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1">
188                                  <sdncadapter:RequestHeader>
189                                     <sdncadapter:RequestId>${hdrRequestId}</sdncadapter:RequestId>
190                                     <sdncadapter:SvcInstanceId>${serviceInstanceId}</sdncadapter:SvcInstanceId>
191                                     <sdncadapter:SvcAction>${sdnc_svcAction}</sdncadapter:SvcAction>
192                                     <sdncadapter:SvcOperation>${sdnc_apiType}-topology-operation</sdncadapter:SvcOperation>
193                                     <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl>
194                                     <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
195                                  </sdncadapter:RequestHeader>
196                                  <sdncadapterworkflow:SDNCRequestData>
197                                      <request-information>
198                                         <request-id>${hdrRequestId}</request-id>
199                                         <request-action>${sdnc_requestAction}</request-action>
200                                         <source>${source}</source>
201                                         <notification-url></notification-url>
202                                         <order-number></order-number>
203                                         <order-version></order-version>
204                                      </request-information>
205                                      <service-information>
206                                         <service-id>${serviceInstanceId}</service-id>
207                                         <subscription-service-type>${serviceType}</subscription-service-type>
208                                         <onap-model-information>
209                                              <model-invariant-uuid>${serviceModelInvariantUuid}</model-invariant-uuid>
210                                              <model-uuid>${serviceModelUuid}</model-uuid>
211                                              <model-version>${serviceModelVersion}</model-version>
212                                              <model-name>${serviceModelName}</model-name>
213                                         </onap-model-information>
214                                         <service-instance-id>${serviceInstanceId}</service-instance-id>
215                                         <global-customer-id>${globalCustomerId}</global-customer-id>
216                                      </service-information>
217                                      <${sdnc_apiType}-information>
218                                         <${sdnc_apiType}-id>${sdncResourceId}</${sdnc_apiType}-id>
219                                         <onap-model-information>
220                                              <model-invariant-uuid>${modelInvariantUuid}</model-invariant-uuid>
221                                              <model-customization-uuid>${modelCustomizationUuid}</model-customization-uuid>
222                                              <model-uuid>${modelUuid}</model-uuid>
223                                              <model-version>${modelVersion}</model-version>
224                                              <model-name>${modelName}</model-name>
225                                         </onap-model-information>
226                                      </${sdnc_apiType}-information>
227                                      <${sdnc_apiType}-request-input>
228                                        <${sdnc_apiType}-input-parameters>${netowrkInputParameters}</${sdnc_apiType}-input-parameters>
229                                      </${sdnc_apiType}-request-input>
230                                 </sdncadapterworkflow:SDNCRequestData>
231                              </aetgt:SDNCAdapterWorkflowRequest>""".trim()
232             
233             String sndcTopologyCreateRequesAsString = utils.formatXml(sndcTopologyCreateRequest)
234             utils.logAudit(sndcTopologyCreateRequesAsString)
235             execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyCreateRequesAsString)
236             utils.log("INFO","sdncAdapterWorkflowRequest :" + sndcTopologyCreateRequesAsString,  isDebugEnabled)
237             utils.log("DEBUG","sdncAdapterWorkflowRequest - " + "\n" +  sndcTopologyCreateRequesAsString, isDebugEnabled)
238
239         } catch (Exception ex) {
240             String exceptionMessage = " Bpmn error encountered in CreateSDNCCNetworkResource flow. prepareSDNCRequest() - " + ex.getMessage()
241             utils.log("DEBUG", exceptionMessage, isDebugEnabled)
242             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
243
244         }
245        utils.log("INFO"," ***** Exit prepareSDNCRequest *****",  isDebugEnabled)
246         }
247  
248     private void setProgressUpdateVariables(DelegateExecution execution, String body) {
249         def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint")
250         execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
251         execution.setVariable("CVFMI_updateResOperStatusRequest", body)
252     }
253
254     public void prepareUpdateBeforeCreateSDNCResource(DelegateExecution execution) {
255         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
256         utils.log("INFO"," ***** Started prepareUpdateBeforeCreateSDNCResource *****",  isDebugEnabled)
257
258         ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput")
259         String operType = resourceInputObj.getOperationType()
260         String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
261         String ServiceInstanceId = resourceInputObj.getServiceInstanceId()
262         String operationId = resourceInputObj.getOperationId()
263         String modelName = resourceInputObj.getResourceModelInfo().getModelName()
264         String progress = "20"
265         String status = "processing"
266         String statusDescription = "Create " + modelName
267
268         execution.getVariable("operationId")
269
270         String body = """
271                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
272                         xmlns:ns="http://org.openecomp.mso/requestsdb">
273                         <soapenv:Header/>
274                 <soapenv:Body>
275                     <ns:updateResourceOperationStatus>
276                                <operType>${operType}</operType>
277                                <operationId>${operationId}</operationId>
278                                <progress>${progress}</progress>
279                                <resourceTemplateUUID>${resourceCustomizationUuid}</resourceTemplateUUID>
280                                <serviceId>${ServiceInstanceId}</serviceId>
281                                <status>${status}</status>
282                                <statusDescription>${statusDescription}</statusDescription>
283                     </ns:updateResourceOperationStatus>
284                 </soapenv:Body>
285                 </soapenv:Envelope>""";
286
287         setProgressUpdateVariables(execution, body)
288         utils.log("INFO"," ***** End prepareUpdateBeforeCreateSDNCResource *****",  isDebugEnabled)
289     }
290     
291     public void postCreateSDNC(DelegateExecution execution) {
292         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
293         ServicePluginFactory.getInstance().test()
294         utils.log("INFO"," ***** Started postCreateSDNC *****",  isDebugEnabled)
295         String sdnc_apiType = execution.getVariable(Prefix + "apiType")
296         String sdncAdapterResponse = execution.getVariable("sdncAdapterResponse")       
297         utils.log("INFO","sdncAdapterResponse for create:" + sdncAdapterResponse ,  isDebugEnabled)
298         sdncAdapterResponse = sdncAdapterResponse.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
299         sdncAdapterResponse = sdncAdapterResponse.replaceAll('tag0:', '').replaceAll(':tag0', '')
300         utils.log("INFO","sdncAdapterResponse for create after replace:" + sdncAdapterResponse ,  isDebugEnabled)
301         //if it is vnf we need to query the vnf-id,if it is network , we need to query the network-id
302                 String sdncRespData = utils.getNodeText1(sdncAdapterResponse, "RequestData")
303                 utils.log("INFO","sdncRespData:" + sdncRespData ,  isDebugEnabled)
304                 String objectKey = "/" + sdnc_apiType + "/"
305                 String objectDataKey = "/" + sdnc_apiType + "-data/"
306                 String objectPath = utils.getNodeText1(sdncRespData, "object-path")
307                 
308                 String resourceObjId = objectPath.substring(objectPath.indexOf(objectKey) + objectKey.length(), objectPath.indexOf(objectDataKey))
309                 utils.log("INFO", "resourceObjId:" + resourceObjId,  isDebugEnabled)
310                 execution.setVariable(Prefix + "sdncResourceId", resourceObjId)
311
312         utils.log("INFO"," ***** End postCreateSDNC *****",  isDebugEnabled)
313                         
314     }
315     
316     public void postActivateSDNC(DelegateExecution execution) {
317         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
318         utils.log("INFO"," ***** Started postActivateSDNC *****",  isDebugEnabled)
319         String sdncAdapterResponse = execution.getVariable("sdncAdapterResponse")
320         utils.log("INFO","sdncAdapterResponse for activate:" + sdncAdapterResponse ,  isDebugEnabled)
321         utils.log("INFO"," ***** End postActivateSDNC *****",  isDebugEnabled)
322     }
323     
324     public void prepareUpdateAfterCreateSDNCResource(DelegateExecution execution) {
325         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
326         utils.log("INFO"," ***** Started prepareUpdateAfterCreateSDNCResource *****",  isDebugEnabled)
327         ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput")
328         String operType = resourceInputObj.getOperationType()
329         String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
330         String ServiceInstanceId = resourceInputObj.getServiceInstanceId()
331         String modelName = resourceInputObj.getResourceModelInfo().getModelName()
332         String operationId = resourceInputObj.getOperationId()
333         String progress = "50"
334         String status = "processing"
335         String statusDescription = "Instantiate " + modelName
336
337         execution.getVariable("operationId")
338
339         String body = """
340                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
341                         xmlns:ns="http://org.openecomp.mso/requestsdb">
342                         <soapenv:Header/>
343                 <soapenv:Body>
344                     <ns:updateResourceOperationStatus>
345                                <operType>${operType}</operType>
346                                <operationId>${operationId}</operationId>
347                                <progress>${progress}</progress>
348                                <resourceTemplateUUID>${resourceCustomizationUuid}</resourceTemplateUUID>
349                                <serviceId>${ServiceInstanceId}</serviceId>
350                                <status>${status}</status>
351                                <statusDescription>${statusDescription}</statusDescription>
352                     </ns:updateResourceOperationStatus>
353                 </soapenv:Body>
354                 </soapenv:Envelope>""";
355
356         setProgressUpdateVariables(execution, body)
357         utils.log("INFO"," ***** End prepareUpdateAfterCreateSDNCResource *****",  isDebugEnabled)
358     }
359
360     public void prepareUpdateAfterActivateSDNCResource(DelegateExecution execution) {
361         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
362         utils.log("INFO"," ***** Started prepareUpdateAfterActivateSDNCResource *****",  isDebugEnabled)
363         ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput")
364         String operType = resourceInputObj.getOperationType()
365         String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
366         String ServiceInstanceId = resourceInputObj.getServiceInstanceId()
367         String modelName = resourceInputObj.getResourceModelInfo().getModelName()
368         String operationId = resourceInputObj.getOperationId()
369         String progress = "100"
370         String status = "finished"
371         String statusDescription = "Instantiate " + modelName + " finished"
372
373         execution.getVariable("operationId")
374
375         String body = """
376                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
377                         xmlns:ns="http://org.openecomp.mso/requestsdb">
378                         <soapenv:Header/>
379                 <soapenv:Body>
380                     <ns:updateResourceOperationStatus>
381                                <operType>${operType}</operType>
382                                <operationId>${operationId}</operationId>
383                                <progress>${progress}</progress>
384                                <resourceTemplateUUID>${resourceCustomizationUuid}</resourceTemplateUUID>
385                                <serviceId>${ServiceInstanceId}</serviceId>
386                                <status>${status}</status>
387                                <statusDescription>${statusDescription}</statusDescription>
388                     </ns:updateResourceOperationStatus>
389                 </soapenv:Body>
390                 </soapenv:Envelope>""";
391
392         setProgressUpdateVariables(execution, body)
393         utils.log("INFO"," ***** End prepareUpdateAfterActivateSDNCResource *****",  isDebugEnabled)
394     }
395     
396     public void postCreateSDNCCall(DelegateExecution execution){
397         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
398         utils.log("INFO"," ***** Started prepareSDNCRequest *****",  isDebugEnabled)
399         String responseCode = execution.getVariable(Prefix + "sdncCreateReturnCode")
400         String responseObj = execution.getVariable(Prefix + "SuccessIndicator")
401         
402         utils.log("INFO","response from sdnc, response code :" + responseCode + "  response object :" + responseObj,  isDebugEnabled)
403         utils.log("INFO"," ***** Exit prepareSDNCRequest *****",  isDebugEnabled)
404     }
405     
406         public void sendSyncResponse (DelegateExecution execution) {
407                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
408                 utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
409
410                 try {
411                         String operationStatus = "finished"
412                         // RESTResponse for main flow
413                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
414                         utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled)
415                         sendWorkflowResponse(execution, 202, resourceOperationResp)
416                         execution.setVariable("sentSyncResponse", true)
417
418                 } catch (Exception ex) {
419                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
420                         utils.log("DEBUG", msg, isDebugEnabled)
421                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
422                 }
423                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
424         }
425 }