Fix SDNC Resource creation workflow
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateVfModuleRollback.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts
24 import org.camunda.bpm.engine.delegate.BpmnError
25 import org.camunda.bpm.engine.delegate.DelegateExecution
26 import org.onap.aai.domain.yang.NetworkPolicies
27 import org.onap.aai.domain.yang.NetworkPolicy
28 import org.onap.so.bpmn.common.scripts.AaiUtil
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.scripts.MsoUtils
32 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
33 import org.onap.so.bpmn.core.UrnPropertiesReader
34 import org.onap.so.bpmn.core.WorkflowException
35 import org.onap.so.client.aai.AAIObjectPlurals
36 import org.onap.so.client.aai.AAIObjectType
37 import org.onap.so.client.aai.entities.uri.AAIResourceUri
38 import org.onap.so.client.aai.entities.uri.AAIUriFactory
39 import org.onap.so.logger.ErrorCode
40 import org.onap.so.logger.MessageEnum
41 import org.slf4j.Logger
42 import org.slf4j.LoggerFactory
43
44 import javax.ws.rs.NotFoundException
45
46
47 public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{
48     private static final Logger logger = LoggerFactory.getLogger( DoCreateVfModuleRollback.class);
49
50         def Prefix="DCVFMR_"
51         ExceptionUtil exceptionUtil = new ExceptionUtil()
52
53         public void initProcessVariables(DelegateExecution execution) {
54                 execution.setVariable("prefix",Prefix)
55         }
56
57         // parse the incoming DELETE_VF_MODULE request for the Generic Vnf and Vf Module Ids
58         // and formulate the outgoing request for PrepareUpdateAAIVfModuleRequest
59         public void preProcessRequest(DelegateExecution execution) {
60
61
62                 initProcessVariables(execution)
63
64                 try {
65
66                         execution.setVariable("rolledBack", null)
67                         execution.setVariable("rollbackError", null)
68
69                         def rollbackData = execution.getVariable("rollbackData")
70                         logger.debug("RollbackData:" + rollbackData)
71
72                         if (rollbackData != null) {
73                         String vnfId = rollbackData.get("VFMODULE", "vnfid")
74                         execution.setVariable("DCVFMR_vnfId", vnfId)
75                         String vfModuleId = rollbackData.get("VFMODULE", "vfmoduleid")
76                         execution.setVariable("DCVFMR_vfModuleId", vfModuleId)
77                         String source = rollbackData.get("VFMODULE", "source")
78                         execution.setVariable("DCVFMR_source", source)
79                         String serviceInstanceId = rollbackData.get("VFMODULE", "serviceInstanceId")
80                         execution.setVariable("DCVFMR_serviceInstanceId", serviceInstanceId)
81                         String serviceId = rollbackData.get("VFMODULE", "service-id")
82                         execution.setVariable("DCVFMR_serviceId", serviceId)
83                         String vnfType = rollbackData.get("VFMODULE", "vnftype")
84                         execution.setVariable("DCVFMR_vnfType", vnfType)
85                         String vnfName = rollbackData.get("VFMODULE", "vnfname")
86                         execution.setVariable("DCVFMR_vnfName", vnfName)
87                         String tenantId = rollbackData.get("VFMODULE", "tenantid")
88                         execution.setVariable("DCVFMR_tenantId", tenantId)
89                         String vfModuleName = rollbackData.get("VFMODULE", "vfmodulename")
90                         execution.setVariable("DCVFMR_vfModuleName", vfModuleName)
91                         String vfModuleModelName = rollbackData.get("VFMODULE", "vfmodulemodelname")
92                         execution.setVariable("DCVFMR_vfModuleModelName", vfModuleModelName)
93                         String cloudSiteId = rollbackData.get("VFMODULE", "aiccloudregion")
94                         execution.setVariable("DCVFMR_cloudSiteId", cloudSiteId)
95                         String cloudOwner = rollbackData.get("VFMODULE", "cloudowner")
96                         execution.setVariable("DCVFMR_cloudOwner", cloudOwner)
97                         String heatStackId = rollbackData.get("VFMODULE", "heatstackid")
98                         execution.setVariable("DCVFMR_heatStackId", heatStackId)
99                         String requestId = rollbackData.get("VFMODULE", "msorequestid")
100                         execution.setVariable("DCVFMR_requestId", requestId)
101                         // Set mso-request-id to request-id for VNF Adapter interface
102                         execution.setVariable("mso-request-id", requestId)
103                         List createdNetworkPolicyFqdnList = []
104                         int i = 0
105                         while (i < 100) {
106                                 String fqdn = rollbackData.get("VFMODULE", "contrailNetworkPolicyFqdn" + i)
107                                 if (fqdn == null) {
108                                         break
109                                 }
110                                 createdNetworkPolicyFqdnList.add(fqdn)
111                                 logger.debug("got fqdn # " + i + ": " + fqdn)
112                                 i = i + 1
113
114                         }
115
116                         execution.setVariable("DCVFMR_createdNetworkPolicyFqdnList", createdNetworkPolicyFqdnList)
117                         String oamManagementV4Address = rollbackData.get("VFMODULE", "oamManagementV4Address")
118                         execution.setVariable("DCVFMR_oamManagementV4Address", oamManagementV4Address)
119                         String oamManagementV6Address = rollbackData.get("VFMODULE", "oamManagementV6Address")
120                         execution.setVariable("DCVFMR_oamManagementV6Address", oamManagementV6Address)
121                         //String serviceInstanceId = rollbackData.get("VFMODULE", "msoserviceinstanceid")
122                         //execution.setVariable("DCVFMR_serviceInstanceId", serviceInstanceId)
123                         execution.setVariable("DCVFMR_rollbackPrepareUpdateVfModule", rollbackData.get("VFMODULE", "rollbackPrepareUpdateVfModule"))
124                         execution.setVariable("DCVFMR_rollbackUpdateAAIVfModule", rollbackData.get("VFMODULE", "rollbackUpdateAAIVfModule"))
125                         execution.setVariable("DCVFMR_rollbackVnfAdapterCreate", rollbackData.get("VFMODULE", "rollbackVnfAdapterCreate"))
126                         execution.setVariable("DCVFMR_rollbackSDNCRequestAssign", rollbackData.get("VFMODULE", "rollbackSDNCRequestAssign"))
127                         execution.setVariable("DCVFMR_rollbackSDNCRequestActivate", rollbackData.get("VFMODULE", "rollbackSDNCRequestActivate"))
128                         execution.setVariable("DCVFMR_rollbackCreateAAIVfModule", rollbackData.get("VFMODULE", "rollbackCreateAAIVfModule"))
129                         execution.setVariable("DCVFMR_rollbackCreateNetworkPoliciesAAI", rollbackData.get("VFMODULE", "rollbackCreateNetworkPoliciesAAI"))
130                         execution.setVariable("DCVFMR_rollbackUpdateVnfAAI", rollbackData.get("VFMODULE", "rollbackUpdateVnfAAI"))
131
132                         // formulate the request for PrepareUpdateAAIVfModule
133                         String request = """<PrepareUpdateAAIVfModuleRequest>
134                                                                         <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
135                                                                         <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
136                                                                         <orchestration-status>pending-delete</orchestration-status>
137                                                                 </PrepareUpdateAAIVfModuleRequest>""" as String
138                         logger.debug("PrepareUpdateAAIVfModuleRequest :" + request)
139                         execution.setVariable("PrepareUpdateAAIVfModuleRequest", request)
140                 } else {
141                         execution.setVariable("skipRollback", true)
142                 }
143
144                 if (execution.getVariable("disableRollback").equals("true" )) {
145                         execution.setVariable("skipRollback", true)
146                 }
147
148                 } catch (BpmnError e) {
149                         throw e;
150                 } catch (Exception ex){
151                         def msg = "Exception in DoCreateVfModuleRollback preProcessRequest " + ex.getMessage()
152                         logger.debug(msg)
153                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
154                 }
155         }
156
157         // build a SDNC vnf-topology-operation request for the specified action
158         // (note: the action passed is expected to be 'changedelete' or 'delete')
159         public void prepSDNCAdapterRequest(DelegateExecution execution) {
160
161                 String srvInstId = execution.getVariable("DCVFMR_serviceInstanceId")
162
163                 String uuid = execution.getVariable('testReqId') // for junits
164                 if(uuid==null){
165                         uuid = execution.getVariable("DCVFMR_requestId") + "-" +        System.currentTimeMillis()
166                 }
167
168                 def callbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution)
169
170                 String source = execution.getVariable("DCVFMR_source")
171                 String serviceId = execution.getVariable("DCVFMR_serviceId")
172                 String vnfId = execution.getVariable("DCVFMR_vnfId")
173                 String vnfType = execution.getVariable("DCVFMR_vnfType")
174                 String vnfName = execution.getVariable("DCVFMR_vnfName")
175                 String tenantId = execution.getVariable("DCVFMR_tenantId")
176                 String vfModuleId = execution.getVariable("DCVFMR_vfModuleId")
177                 String vfModuleName = execution.getVariable("DCVFMR_vfModuleName")
178                 String vfModuleModelName = execution.getVariable("DCVFMR_vfModuleModelName")
179                 String cloudSiteId = execution.getVariable("DCVFMR_cloudSiteId")
180                 String requestId = execution.getVariable("DCVFMR_requestId")
181
182                 String serviceInstanceIdToSdnc = ""
183                 if (srvInstId != null && !srvInstId.isEmpty()) {
184                         serviceInstanceIdToSdnc = srvInstId
185                 } else {
186                     serviceInstanceIdToSdnc = vfModuleId
187                 }
188
189                 def doSDNCActivateRollback = execution.getVariable("DCVFMR_rollbackSDNCRequestActivate")
190                 def doSDNCAssignRollback = execution.getVariable("DCVFMR_rollbackSDNCRequestAssign")
191
192                 def action = ""
193                 def requestAction = ""
194
195                 if (doSDNCActivateRollback.equals("true")) {
196                         action = "delete"
197                         requestAction = "DisconnectVNFRequest"
198                 }
199                 else if (doSDNCAssignRollback.equals("true")) {
200                         action = "rollback"
201                         requestAction = "VNFActivateRequest"
202                 }
203                 else
204                         return
205
206
207                 String request = """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
208                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
209                                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
210                                                       <sdncadapter:RequestHeader>
211                                                          <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
212                                                          <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(vfModuleId)}</sdncadapter:SvcInstanceId>
213                                                          <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
214                                                          <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
215                                                          <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl>
216                                                       </sdncadapter:RequestHeader>
217                                                       <sdncadapterworkflow:SDNCRequestData>
218                                                          <request-information>
219                                                             <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
220                                                             <request-action>${MsoUtils.xmlEscape(requestAction)}</request-action>
221                                                             <source>${MsoUtils.xmlEscape(source)}</source>
222                                                             <notification-url/>
223                                                             <order-number/>
224                                                             <order-version/>
225                                                          </request-information>
226                                                          <service-information>
227                                                             <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
228                                                                         <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type>
229                                                             <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceIdToSdnc)}</service-instance-id>
230                                                             <subscriber-name>notsurewecare</subscriber-name>
231                                                          </service-information>
232                                                          <vnf-request-information>
233                                                                 <vnf-id>${MsoUtils.xmlEscape(vfModuleId)}</vnf-id>
234                                                                         <vnf-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vnf-type>
235                                     <vnf-name>${MsoUtils.xmlEscape(vfModuleName)}</vnf-name>
236                                                                         <generic-vnf-id>${MsoUtils.xmlEscape(vnfId)}</generic-vnf-id>
237                                     <generic-vnf-name>${MsoUtils.xmlEscape(vnfName)}</generic-vnf-name>
238                                                                         <generic-vnf-type>${MsoUtils.xmlEscape(vnfType)}</generic-vnf-type>
239                                                                         <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>
240                                                                         <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
241                                                          </vnf-request-information>
242                                                       </sdncadapterworkflow:SDNCRequestData>
243                                                    </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
244
245                 logger.debug("sdncAdapterWorkflowRequest: " + request)
246                 execution.setVariable("sdncAdapterWorkflowRequest", request)
247         }
248
249         public void preProcessSDNCDeactivateRequest(DelegateExecution execution){
250
251                 execution.setVariable("prefix", Prefix)
252                 logger.trace("STARTED preProcessSDNCDeactivateRequest")
253
254                 def serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId")
255
256                 try{
257                         //Build SDNC Request
258
259                         String deactivateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "deactivate")
260
261                         deactivateSDNCRequest = utils.formatXml(deactivateSDNCRequest)
262                         execution.setVariable("DCVFMR_deactivateSDNCRequest", deactivateSDNCRequest)
263                         logger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest)
264
265                 }catch(Exception e){
266                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
267                                         "Exception Occured Processing preProcessSDNCDeactivateRequest.", "BPMN",
268                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
269                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage())
270                 }
271                 logger.trace("COMPLETED preProcessSDNCDeactivateRequest")
272         }
273
274         public void preProcessSDNCUnassignRequest(DelegateExecution execution) {
275                 def method = getClass().getSimpleName() + '.preProcessSDNCUnassignRequest(' +
276                         'execution=' + execution.getId() +
277                         ')'
278                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
279                 logger.trace('Entered ' + method)
280                 execution.setVariable("prefix", Prefix)
281                 logger.trace("STARTED preProcessSDNCUnassignRequest Process")
282                 try{
283                         String serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId")
284
285                         String unassignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "unassign")
286
287                         execution.setVariable("DCVFMR_unassignSDNCRequest", unassignSDNCRequest)
288                         logger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest)
289
290                 }catch(Exception e){
291                         logger.debug("Exception Occured Processing preProcessSDNCUnassignRequest. Exception is:\n" + e)
292                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during  preProcessSDNCUnassignRequest Method:\n" + e.getMessage())
293                 }
294                 logger.trace("COMPLETED  preProcessSDNCUnassignRequest Process")
295         }
296
297         public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){
298
299                         String uuid = execution.getVariable('testReqId') // for junits
300                         if(uuid==null){
301                                 uuid = execution.getVariable("DCVFMR_requestId") + "-" +        System.currentTimeMillis()
302                         }
303                         def callbackURL = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution)
304                         def requestId = execution.getVariable("DCVFMR_requestId")
305                         def serviceId = execution.getVariable("DCVFMR_serviceId")
306                         def serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId")
307                         def vfModuleId = execution.getVariable("DCVFMR_vfModuleId")
308                         def source = execution.getVariable("DCVFMR_source")
309                         def vnfId = execution.getVariable("DCVFMR_vnfId")
310
311                         def sdncVersion = execution.getVariable("sdncVersion")
312
313                         String sdncRequest =
314                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
315                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
316                                                                                                         xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1">
317            <sdncadapter:RequestHeader>
318                                 <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
319                                 <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
320                                 <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
321                                 <sdncadapter:SvcOperation>vf-module-topology-operation</sdncadapter:SvcOperation>
322                                 <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
323                                 <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
324                 </sdncadapter:RequestHeader>
325         <sdncadapterworkflow:SDNCRequestData>
326                 <request-information>
327                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
328                         <request-action>DeleteVfModuleInstance</request-action>
329                         <source>${MsoUtils.xmlEscape(source)}</source>
330                         <notification-url/>
331                         <order-number/>
332                         <order-version/>
333                 </request-information>
334                 <service-information>
335                         <service-id/>
336                         <subscription-service-type/>
337                         <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
338                         <global-customer-id/>
339                 </service-information>
340                 <vnf-information>
341                         <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
342                         <vnf-type/>
343                 </vnf-information>
344                 <vf-module-information>
345                         <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
346                 </vf-module-information>
347                 <vf-module-request-input/>
348         </sdncadapterworkflow:SDNCRequestData>
349         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
350
351                 logger.debug("sdncRequest:  " + sdncRequest)
352                 return sdncRequest
353         }
354
355         // parse the incoming DELETE_VF_MODULE request
356         // and formulate the outgoing VnfAdapterDeleteV1 request
357         public void prepVNFAdapterRequest(DelegateExecution execution) {
358
359                 String requestId = UUID.randomUUID().toString()
360                 String origRequestId = execution.getVariable("DCVFMR_requestId")
361                 String srvInstId = execution.getVariable("DCVFMR_serviceInstanceId")
362                 String aicCloudRegion = execution.getVariable("DCVFMR_cloudSiteId")
363                 String cloudOwner = execution.getVariable("DCVFMR_cloudOwner")
364                 String vnfId = execution.getVariable("DCVFMR_vnfId")
365                 String vfModuleId = execution.getVariable("DCVFMR_vfModuleId")
366                 String vfModuleStackId = execution.getVariable("DCVFMR_heatStackId")
367                 String tenantId = execution.getVariable("DCVFMR_tenantId")
368                 def messageId = execution.getVariable('mso-request-id') + '-' +
369                         System.currentTimeMillis()
370                 def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId)
371                 def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution)
372                 if ('true'.equals(useQualifiedHostName)) {
373                         notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
374                 }
375
376                 String request = """
377                         <deleteVfModuleRequest>
378                             <cloudSiteId>${MsoUtils.xmlEscape(aicCloudRegion)}</cloudSiteId>
379                             <cloudOwner>${MsoUtils.xmlEscape(cloudOwner)}</cloudOwner>
380                             <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
381                             <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId>
382                             <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId>
383                             <vfModuleStackId>${MsoUtils.xmlEscape(vfModuleStackId)}</vfModuleStackId>
384                             <skipAAI>true</skipAAI>
385                             <msoRequest>
386                                 <requestId>${MsoUtils.xmlEscape(origRequestId)}</requestId>
387                                 <serviceInstanceId>${MsoUtils.xmlEscape(srvInstId)}</serviceInstanceId>
388                             </msoRequest>
389                             <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
390                             <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl>
391                         </deleteVfModuleRequest>
392                         """ as String
393
394                 logger.debug("vnfAdapterRestV1Request: " + request)
395                 execution.setVariable("vnfAdapterRestV1Request", request)
396         }
397
398         // parse the incoming DELETE_VF_MODULE request
399         // and formulate the outgoing UpdateAAIVfModuleRequest request
400         public void prepUpdateAAIVfModule(DelegateExecution execution) {
401
402                 String vnfId = execution.getVariable("DCVFMR_vnfId")
403                 String vfModuleId = execution.getVariable("DCVFMR_vfModuleId")
404                 // formulate the request for UpdateAAIVfModule
405                 String request = """<UpdateAAIVfModuleRequest>
406                                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
407                                                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
408                                                                 <heat-stack-id>DELETE</heat-stack-id>
409                                                                 <orchestration-status>deleted</orchestration-status>
410                                                         </UpdateAAIVfModuleRequest>""" as String
411                 logger.debug("UpdateAAIVfModuleRequest :" + request)
412                 execution.setVariable("UpdateAAIVfModuleRequest", request)
413         }
414
415         // parse the incoming DELETE_VF_MODULE request
416         // and formulate the outgoing UpdateAAIVfModuleRequest request
417         public void prepUpdateAAIVfModuleToAssigned(DelegateExecution execution) {
418
419                 String vnfId = execution.getVariable("DCVFMR_vnfId")
420                 String vfModuleId = execution.getVariable("DCVFMR_vfModuleId")
421                 // formulate the request for UpdateAAIVfModule
422                 String request = """<UpdateAAIVfModuleRequest>
423                                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
424                                                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
425                                                                 <heat-stack-id></heat-stack-id>
426                                                                 <orchestration-status>Assigned</orchestration-status>
427                                                         </UpdateAAIVfModuleRequest>""" as String
428                 logger.debug("UpdateAAIVfModuleRequest :" + request)
429                 execution.setVariable("UpdateAAIVfModuleRequest", request)
430         }
431
432         // parse the incoming DELETE_VF_MODULE request
433         // and formulate the outgoing DeleteAAIVfModuleRequest request
434         public void prepDeleteAAIVfModule(DelegateExecution execution) {
435
436                 String vnfId = execution.getVariable("DCVFMR_vnfId")
437                 String vfModuleId = execution.getVariable("DCVFMR_vfModuleId")
438                 // formulate the request for UpdateAAIVfModule
439                 String request = """<DeleteAAIVfModuleRequest>
440                                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
441                                                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
442                                                         </DeleteAAIVfModuleRequest>""" as String
443                 logger.debug("DeleteAAIVfModuleRequest :" + request)
444                 execution.setVariable("DeleteAAIVfModuleRequest", request)
445         }
446
447         // generates a WorkflowException if
448         //              -
449         public void handleDoDeleteVfModuleFailure(DelegateExecution execution) {
450
451                 logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
452                                 "AAI error occurred deleting the Generic Vnf" + execution.getVariable("DoDVfMod_deleteGenericVnfResponse"),
453                                 "BPMN", ErrorCode.UnknownError.getValue());
454                 String processKey = getProcessKey(execution);
455                 exceptionUtil.buildWorkflowException(execution, 5000, "Failure in DoDeleteVfModule")
456
457         }
458
459         public void sdncValidateResponse(DelegateExecution execution, String response){
460
461                 execution.setVariable("prefix",Prefix)
462
463                 WorkflowException workflowException = execution.getVariable("WorkflowException")
464                 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
465
466                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
467                 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
468
469                 if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
470                         logger.debug("Successfully Validated SDNC Response")
471                 }else{
472                         throw new BpmnError("MSOWorkflowException")
473                 }
474         }
475
476         public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) {
477                 def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' +
478                 'execution=' + execution.getId() +
479                 ')'
480                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
481                 logger.trace('Entered ' + method)
482                 execution.setVariable("prefix", Prefix)
483                 logger.trace("STARTED deleteNetworkPoliciesFromAAI")
484
485                 try {
486                         // get variables
487                         List fqdnList = execution.getVariable(Prefix + "createdNetworkPolicyFqdnList")
488                         if (fqdnList == null) {
489                                 logger.debug("No network policies to delete")
490                                 return
491                         }
492                         int fqdnCount = fqdnList.size()
493
494                         execution.setVariable(Prefix + "networkPolicyFqdnCount", fqdnCount)
495                         logger.debug("networkPolicyFqdnCount - " + fqdnCount)
496
497                         AaiUtil aaiUriUtil = new AaiUtil(this)
498
499                         if (fqdnCount > 0) {
500                                 // AII loop call over contrail network policy fqdn list
501                                 for (i in 0..fqdnCount-1) {
502
503                                         int counting = i+1
504                                         String fqdn = fqdnList[i]
505
506                     try {
507                         // Query AAI for this network policy FQDN
508                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY)
509                         uri.queryParam("network-policy-fqdn", fqdn)
510                         Optional<NetworkPolicies> networkPolicies = getAAIClient().get(NetworkPolicies.class, uri)
511
512                         if (networkPolicies.isPresent() && !networkPolicies.get().getNetworkPolicy().isEmpty()) {
513                             execution.setVariable(Prefix + "aaiQueryNetworkPolicyByFqdnReturnCode", 200)
514                             NetworkPolicy networkPolicy = networkPolicies.get().getNetworkPolicy().get(0)
515
516                             try{
517                             AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicy.getNetworkPolicyId())
518                             getAAIClient().delete(delUri)
519                             execution.setVariable(Prefix + "aaiDeleteNetworkPolicyReturnCode", 200)
520                             logger.debug("AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + 200)
521                                 logger.debug("The return code from deleting network policy is: " + 200)
522                                 // This network policy was deleted from AAI successfully
523                                 logger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ")
524                             }catch(NotFoundException ne){
525                                 // This network policy FQDN is not in AAI. No need to delete.
526                                 execution.setVariable(Prefix + "aaiDeleteNetworkPolicyReturnCode", 404)
527                                 logger.debug("The return code is: " + 404)
528                                 logger.debug("This network policy FQDN is not in AAI: " + fqdn)
529                             }catch(Exception e){
530                                 // aai all errors
531                                 String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + e.getMessage()
532                                 logger.debug(delErrorMessage)
533                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage)
534                             }
535                         } else {
536                             // This network policy FQDN is not in AAI. No need to delete.
537                             logger.debug("This network policy FQDN is not in AAI: " + fqdn)
538                         }
539                     }catch (BpmnError e){
540                         throw e
541                     }
542                     catch (Exception e) {
543                         // aai all errors
544                         String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + e.getMessage()
545                         logger.debug(dataErrorMessage)
546                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
547                     }
548                                 } // end loop
549
550
551                         } else {
552                                    logger.debug("No contrail network policies to query/create")
553
554                         }
555
556                 } catch (BpmnError e) {
557                         throw e;
558
559                 } catch (Exception ex) {
560                         String exceptionMessage = "Bpmn error encountered in DoCreateVfModuleRollback flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage()
561                         logger.debug(exceptionMessage)
562                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
563                 }
564
565         }
566
567
568         /**
569          * Prepare a Request for invoking the UpdateAAIGenericVnf subflow.
570          *
571          * @param execution The flow's execution instance.
572          */
573         public void preProcessUpdateAAIGenericVnf(DelegateExecution execution) {
574                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIGenericVnf((' +
575                         'execution=' + execution.getId() +
576                         ')'
577                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
578                 logger.trace('Entered ' + method)
579
580                 try {
581                         def vnfId = execution.getVariable('DCVFMR_vnfId')
582                         def oamManagementV4Address = execution.getVariable(Prefix + 'oamManagementV4Address')
583                         def oamManagementV6Address = execution.getVariable(Prefix + 'oamManagementV6Address')
584                         def ipv4OamAddressElement = ''
585                         def managementV6AddressElement = ''
586
587                         if (oamManagementV4Address != null) {
588                                 ipv4OamAddressElement = '<ipv4-oam-address>' + 'DELETE' + '</ipv4-oam-address>'
589                         }
590
591                         if (oamManagementV6Address != null) {
592                                 managementV6AddressElement = '<management-v6-address>' + 'DELETE' + '</management-v6-address>'
593                         }
594
595
596                         String updateAAIGenericVnfRequest = """
597                                         <UpdateAAIGenericVnfRequest>
598                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
599                                                 ${ipv4OamAddressElement}
600                                                 ${managementV6AddressElement}
601                                         </UpdateAAIGenericVnfRequest>
602                                 """
603                                 updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest)
604                                 execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest)
605                                 logger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest)
606
607
608                         logger.trace('Exited ' + method)
609                 } catch (BpmnError e) {
610                         throw e;
611                 } catch (Exception e) {
612                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
613                                         'Caught exception in ' + method, "BPMN",
614                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
615                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessUpdateAAIGenericVnf((): ' + e.getMessage())
616                 }
617         }
618
619         public void setSuccessfulRollbackStatus (DelegateExecution execution){
620
621                 execution.setVariable("prefix", Prefix)
622                 logger.trace("STARTED setSuccessfulRollbackStatus")
623
624                 try{
625                         // Set rolledBack to true, rollbackError to null
626                         execution.setVariable("rolledBack", true)
627                         execution.setVariable("rollbackError", null)
628
629                 }catch(Exception e){
630                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
631                                         "Exception Occured Processing setSuccessfulRollbackStatus.", "BPMN",
632                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
633                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setSuccessfulRollbackStatus Method:\n" + e.getMessage())
634                 }
635                 logger.trace("COMPLETED setSuccessfulRollbackStatus")
636         }
637
638         public void setFailedRollbackStatus (DelegateExecution execution){
639
640                 execution.setVariable("prefix", Prefix)
641                 logger.trace("STARTED setFailedRollbackStatus")
642
643                 try{
644                         // Set rolledBack to false, rollbackError to actual value, rollbackData to null
645                         execution.setVariable("rolledBack", false)
646                         execution.setVariable("rollbackError", 'Caught exception in DoCreateVfModuleRollback')
647                         execution.setVariable("rollbackData", null)
648
649                 }catch(Exception e){
650                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
651                                         "Exception Occured Processing setFailedRollbackStatus.", "BPMN",
652                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
653                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setFailedRollbackStatus Method:\n" + e.getMessage())
654                 }
655                 logger.trace("COMPLETED setFailedRollbackStatus")
656         }
657 }