Containerization feature of SO
[so.git] / bpmn / so-bpmn-infrastructure-flows / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / CreateSDNCNetworkResource.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 static org.apache.commons.lang3.StringUtils.*;
24
25 import org.apache.commons.lang3.*
26 import org.camunda.bpm.engine.delegate.BpmnError 
27 import org.camunda.bpm.engine.delegate.DelegateExecution
28 import org.json.JSONObject
29 import org.json.XML;
30 import org.onap.so.bpmn.common.recipe.ResourceInput;
31 import org.onap.so.bpmn.common.resource.ResourceRequestBuilder 
32 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor 
33 import org.onap.so.bpmn.common.scripts.ExceptionUtil
34 import org.onap.so.bpmn.common.scripts.MsoUtils
35 import org.onap.so.bpmn.core.json.JsonUtils
36 import org.onap.so.logger.MsoLogger
37
38 import groovy.json.*
39
40 /**
41  * This groovy class supports the <class>CreateSDNCCNetworkResource.bpmn</class> process.
42  * flow for SDNC Network Resource Create
43  */
44 public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
45         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateSDNCNetworkResource.class);
46
47     String Prefix="CRESDNCRES_"
48             
49     ExceptionUtil exceptionUtil = new ExceptionUtil()
50
51     JsonUtils jsonUtil = new JsonUtils()
52     
53     public void preProcessRequest(DelegateExecution execution){
54         msoLogger.trace("Started preProcessRequest ")
55         try {           
56             
57             //get bpmn inputs from resource request.
58             String requestId = execution.getVariable("mso-request-id")
59             String requestAction = execution.getVariable("requestAction")
60             msoLogger.info("The requestAction is: " + requestAction)
61             String recipeParamsFromRequest = execution.getVariable("recipeParams")
62             msoLogger.info("The recipeParams is: " + recipeParamsFromRequest)
63             String resourceInput = execution.getVariable("resourceInput")
64             msoLogger.info("The resourceInput is: " + resourceInput)
65             //Get ResourceInput Object
66             ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class)
67             execution.setVariable(Prefix + "resourceInput", resourceInputObj)
68             
69             //Deal with recipeParams
70             String recipeParamsFromWf = execution.getVariable("recipeParamXsd")
71             String resourceName = resourceInputObj.getResourceInstanceName()            
72             //For sdnc requestAction default is "createNetworkInstance"
73             String operationType = "Network"    
74             if(!StringUtils.isBlank(recipeParamsFromRequest)){
75                 //the operationType from worflow(first node) is second priority.
76                 operationType = jsonUtil.getJsonValue(recipeParamsFromRequest, "operationType")
77             }
78             if(!StringUtils.isBlank(recipeParamsFromWf)){
79                 //the operationType from worflow(first node) is highest priority.
80                 operationType = jsonUtil.getJsonValue(recipeParamsFromWf, "operationType")
81             }
82             
83             
84             //For sdnc, generate svc_action and request_action
85             String sdnc_svcAction = "create"
86             if(StringUtils.containsIgnoreCase(resourceInputObj.getResourceInstanceName(), "overlay")){
87                 //This will be resolved in R3.
88                 sdnc_svcAction ="activate"
89                 operationType = "NCINetwork"        
90             }
91             if(StringUtils.containsIgnoreCase(resourceInputObj.getResourceInstanceName(), "underlay")){
92                 //This will be resolved in R3.
93                 operationType ="Network"
94             }        
95             String sdnc_requestAction = StringUtils.capitalize(sdnc_svcAction) + operationType +"Instance"                    
96             execution.setVariable(Prefix + "svcAction", sdnc_svcAction)        
97             execution.setVariable(Prefix + "requestAction", sdnc_requestAction)
98             execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId())
99             execution.setVariable("mso-request-id", requestId)
100             execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId())
101             //TODO Here build networkrequest
102             
103         } catch (BpmnError e) {
104             throw e;
105         } catch (Exception ex){
106             msg = "Exception in preProcessRequest " + ex.getMessage()
107             msoLogger.debug(msg)
108             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
109         }
110     }
111     
112     String customizeResourceParam(String netowrkInputParametersJson) {
113         List<Map<String, Object>> paramList = new ArrayList();
114         JSONObject jsonObject = new JSONObject(netowrkInputParametersJson);
115         Iterator iterator = jsonObject.keys();
116         while (iterator.hasNext()) {
117             String key = iterator.next();
118             HashMap<String, String> hashMap = new HashMap();
119             hashMap.put("name", key);
120             hashMap.put("value", jsonObject.get(key))
121             paramList.add(hashMap)
122         }
123         Map<String, List<Map<String, Object>>> paramMap = new HashMap();
124         paramMap.put("param", paramList);
125
126         return  new JSONObject(paramMap).toString();
127     }
128     
129     /**
130      * Pre Process the BPMN Flow Request
131      * Inclouds:
132      * generate the nsOperationKey
133      * generate the nsParameters
134      */
135     public void prepareSDNCRequest (DelegateExecution execution) {
136         msoLogger.trace("Started prepareSDNCRequest ")
137
138         try {
139             // get variables
140             String sdnc_svcAction = execution.getVariable(Prefix + "svcAction")        
141             String sdnc_requestAction = execution.getVariable(Prefix + "requestAction")
142             String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback")
143             String createNetworkInput = execution.getVariable(Prefix + "networkRequest")
144
145             String hdrRequestId = execution.getVariable("mso-request-id")
146             String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId")
147             String source = execution.getVariable("source")
148             String sdnc_service_id = execution.getVariable(Prefix + "sdncServiceId")
149             ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput")
150             String serviceType = resourceInputObj.getServiceType()
151             String serviceModelInvariantUuid = resourceInputObj.getServiceModelInfo().getModelInvariantUuid()
152             String serviceModelUuid = resourceInputObj.getServiceModelInfo().getModelUuid()
153             String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion()
154             String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName()
155             String globalCustomerId = resourceInputObj.getGlobalSubscriberId()
156             String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid();
157             String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
158             String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid()
159             String modelName = resourceInputObj.getResourceModelInfo().getModelName()
160             String modelVersion = resourceInputObj.getResourceModelInfo().getModelVersion()
161             String resourceInputPrameters = resourceInputObj.getResourceParameters()
162             String netowrkInputParametersJson = jsonUtil.getJsonValue(resourceInputPrameters, "requestInputs")
163             //here convert json string to xml string
164             String netowrkInputParameters = XML.toString(new JSONObject(customizeResourceParam(netowrkInputParametersJson)))
165             // 1. prepare assign topology via SDNC Adapter SUBFLOW call
166             String sndcTopologyCreateRequest =
167                     """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
168                                                               xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" 
169                                                               xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1">
170                                  <sdncadapter:RequestHeader>
171                                     <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId>
172                                     <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId>
173                                     <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction>
174                                     <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation>
175                                     <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl>
176                                     <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
177                                  </sdncadapter:RequestHeader>
178                                  <sdncadapterworkflow:SDNCRequestData>
179                                      <request-information>
180                                         <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id>
181                                         <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action>
182                                         <source>${MsoUtils.xmlEscape(source)}</source>
183                                         <notification-url></notification-url>
184                                         <order-number></order-number>
185                                         <order-version></order-version>
186                                      </request-information>
187                                      <service-information>
188                                         <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id>
189                                         <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type>
190                                         <onap-model-information>
191                                              <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid>
192                                              <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid>
193                                              <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version>
194                                              <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name>
195                                         </onap-model-information>
196                                         <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
197                                         <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id>
198                                      </service-information>
199                                      <network-information>
200                                         <onap-model-information>
201                                              <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid>
202                                              <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid>
203                                              <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid>
204                                              <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version>
205                                              <model-name>${MsoUtils.xmlEscape(modelName)}</model-name>
206                                         </onap-model-information>
207                                      </network-information>
208                                      <network-request-input>
209                                        <network-input-parameters>${MsoUtils.xmlEscape(netowrkInputParameters)}</network-input-parameters>
210                                      </network-request-input>
211                                 </sdncadapterworkflow:SDNCRequestData>
212                              </aetgt:SDNCAdapterWorkflowRequest>""".trim()
213             
214             String sndcTopologyCreateRequesAsString = utils.formatXml(sndcTopologyCreateRequest)
215             msoLogger.debug(sndcTopologyCreateRequesAsString)
216             execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyCreateRequesAsString)
217             msoLogger.debug("sdncAdapterWorkflowRequest - " + "\n" +  sndcTopologyCreateRequesAsString)
218
219         } catch (Exception ex) {
220             String exceptionMessage = " Bpmn error encountered in CreateSDNCCNetworkResource flow. prepareSDNCRequest() - " + ex.getMessage()
221             msoLogger.debug(exceptionMessage)
222             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
223
224         }
225        msoLogger.trace("Exit prepareSDNCRequest ")
226         }
227
228     private void setProgressUpdateVariables(DelegateExecution execution, String body) {
229         def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint")
230         execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
231         execution.setVariable("CVFMI_updateResOperStatusRequest", body)
232     }
233
234     public void prepareUpdateBeforeCreateSDNCResource(DelegateExecution execution) {
235         ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput")
236         String operType = resourceInputObj.getOperationType()
237         String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
238         String ServiceInstanceId = resourceInputObj.getServiceInstanceId()
239         String operationId = resourceInputObj.getOperationId()
240         String progress = "20"
241         String status = "processing"
242         String statusDescription = "SDCN resource creation invoked"
243
244         execution.getVariable("operationId")
245
246         String body = """
247                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
248                         xmlns:ns="http://org.onap.so/requestsdb">
249                         <soapenv:Header/>
250                 <soapenv:Body>
251                     <ns:updateResourceOperationStatus>
252                                <operType>${MsoUtils.xmlEscape(operType)}</operType>
253                                <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
254                                <progress>${MsoUtils.xmlEscape(progress)}</progress>
255                                <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID>
256                                <serviceId>${MsoUtils.xmlEscape(ServiceInstanceId)}</serviceId>
257                                <status>${MsoUtils.xmlEscape(status)}</status>
258                                <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription>
259                     </ns:updateResourceOperationStatus>
260                 </soapenv:Body>
261                 </soapenv:Envelope>""";
262
263         setProgressUpdateVariables(execution, body)
264
265     }
266
267     public void prepareUpdateAfterCreateSDNCResource(execution) {
268         ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput")
269         String operType = resourceInputObj.getOperationType()
270         String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
271         String ServiceInstanceId = resourceInputObj.getServiceInstanceId()
272         String operationId = resourceInputObj.getOperationId()
273         String progress = "100"
274         String status = "finished"
275         String statusDescription = "SDCN resource creation completed"
276
277         execution.getVariable("operationId")
278
279         String body = """
280                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
281                         xmlns:ns="http://org.onap.so/requestsdb">
282                         <soapenv:Header/>
283                 <soapenv:Body>
284                     <ns:updateResourceOperationStatus>
285                                <operType>${MsoUtils.xmlEscape(operType)}</operType>
286                                <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
287                                <progress>${MsoUtils.xmlEscape(progress)}</progress>
288                                <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID>
289                                <serviceId>${MsoUtils.xmlEscape(ServiceInstanceId)}</serviceId>
290                                <status>${MsoUtils.xmlEscape(status)}</status>
291                                <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription>
292                     </ns:updateResourceOperationStatus>
293                 </soapenv:Body>
294                 </soapenv:Envelope>""";
295
296         setProgressUpdateVariables(execution, body)
297     }
298
299     public void postCreateSDNCCall(DelegateExecution execution){
300         msoLogger.trace("Started prepareSDNCRequest ")
301         String responseCode = execution.getVariable(Prefix + "sdncCreateReturnCode")
302         String responseObj = execution.getVariable(Prefix + "SuccessIndicator")
303         
304         msoLogger.info("response from sdnc, response code :" + responseCode + "  response object :" + responseObj)
305         msoLogger.trace("Exit prepareSDNCRequest ")
306     }
307     
308         public void sendSyncResponse (DelegateExecution execution) {
309                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
310                 utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
311
312                 try {
313                         String operationStatus = "finished"
314                         // RESTResponse for main flow
315                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
316                         utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled)
317                         sendWorkflowResponse(execution, 202, resourceOperationResp)
318                         execution.setVariable("sentSyncResponse", true)
319
320                 } catch (Exception ex) {
321                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
322                         utils.log("DEBUG", msg, isDebugEnabled)
323                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
324                 }
325                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
326         }
327 }