39820dc2e1ccb5aa13933d470e8d5f76c7cafbb1
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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  *      http://www.apache.org/licenses/LICENSE-2.0
11  * 
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END=========================================================
18  */
19
20 package org.openecomp.mso.bpmn.infrastructure.scripts
21
22 import groovy.json.JsonOutput
23 import groovy.json.JsonSlurper
24 import groovy.util.Node
25 import groovy.util.XmlParser;
26 import groovy.xml.QName
27
28 import org.json.JSONArray
29 import org.json.JSONObject
30
31 import java.io.Serializable;
32 import java.util.List
33 import java.util.UUID;
34 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
35 import org.camunda.bpm.engine.delegate.BpmnError
36 import org.camunda.bpm.engine.impl.cmd.AbstractSetVariableCmd
37 import org.camunda.bpm.engine.delegate.DelegateExecution
38 import org.openecomp.mso.rest.APIResponse
39 import org.openecomp.mso.rest.RESTClient
40 import org.openecomp.mso.rest.RESTConfig
41 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor;
42 import org.openecomp.mso.bpmn.common.scripts.VidUtils;
43 import org.openecomp.mso.bpmn.core.RollbackData
44 import org.openecomp.mso.bpmn.core.WorkflowException
45 import org.openecomp.mso.bpmn.core.json.JsonUtils
46 import org.openecomp.mso.bpmn.core.domain.ModelInfo
47 import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition
48 import org.openecomp.mso.bpmn.core.domain.VnfResource
49 import org.openecomp.mso.client.aai.*
50
51 import org.openecomp.mso.client.appc.ApplicationControllerClient;
52 import org.openecomp.mso.client.appc.ApplicationControllerSupport;
53 import org.openecomp.mso.client.aai.entities.AAIResultWrapper
54 import org.openecomp.mso.client.aai.entities.Relationships
55 import org.openecomp.mso.client.aai.entities.uri.AAIResourceUri
56 import org.openecomp.mso.client.aai.entities.uri.AAIUri
57 import org.openecomp.mso.client.aai.entities.uri.AAIUriFactory
58 import org.onap.appc.client.lcm.model.Action;
59 import org.onap.appc.client.lcm.model.ActionIdentifiers;
60 import org.onap.appc.client.lcm.model.LockInput
61 import org.onap.appc.client.lcm.model.UnlockInput
62 import org.onap.appc.client.lcm.model.HealthCheckInput
63 import org.onap.appc.client.lcm.model.StartInput
64 import org.onap.appc.client.lcm.model.StopInput
65 import org.onap.appc.client.lcm.model.Flags
66 import org.onap.appc.client.lcm.model.Status
67
68
69
70 public abstract class VnfCmBase extends AbstractServiceTaskProcessor {
71
72         ExceptionUtil exceptionUtil = new ExceptionUtil()
73         JsonUtils jsonUtils = new JsonUtils()   
74         def prefix = "VnfIPU_"
75
76         /**
77          * Initialize the flow's variables.
78          *
79          * @param execution The flow's execution instance.
80          */
81         
82         /**
83          * Prepare and send the sychronous response for this flow.
84          *
85          * @param execution The flow's execution instance.
86          */
87         public void sendSynchResponse(DelegateExecution execution) {
88                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
89                         'execution=' + execution.getId() +
90                         ')'
91                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
92                 logDebug('Entered ' + method, isDebugLogEnabled)
93
94
95                 try {
96                         def requestInfo = execution.getVariable('requestInfo')
97                         def requestId = execution.getVariable('requestId')
98                         def source = execution.getVariable('source')
99                         def progress = getNodeTextForce(requestInfo, 'progress')
100                         if (progress.isEmpty()) {
101                                 progress = '0'
102                         }
103                         def startTime = getNodeTextForce(requestInfo, 'start-time')
104                         if (startTime.isEmpty()) {
105                                 startTime = System.currentTimeMillis()
106                         }
107
108                         // RESTResponse (for API Handler (APIH) Reply Task)
109                         def vnfId = execution.getVariable("vnfId")
110                         String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim()
111
112                         sendWorkflowResponse(execution, 200, synchResponse)
113
114                         logDebug('Exited ' + method, isDebugLogEnabled)
115                 } catch (BpmnError e) {
116                         throw e;
117                 } catch (Exception e) {
118                         logError('Caught exception in ' + method, e)
119                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
120                 }
121         }
122         
123         
124
125         /**
126          * Get VnfResource decomposition object for this VNF.
127          *      
128          *
129          * @param execution The flow's execution instance.
130          */
131         public void getVnfResourceDecomposition(DelegateExecution execution) {
132                 def method = getClass().getSimpleName() + '.getVnfResourceDecomposition(' +
133                         'execution=' + execution.getId() +
134                         ')'
135                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
136                 logDebug('Entered ' + method, isDebugLogEnabled)
137
138                 try {
139                         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
140                         String vnfModelInvariantUuid = execution.getVariable('vnfModelInvariantUuid')
141                         logDebug("vnfModelInvariantUuid: " + vnfModelInvariantUuid, isDebugLogEnabled)
142                         List<VnfResource> vnfResources = serviceDecomposition.getServiceVnfs()
143                         
144                         for (i in 0..vnfResources.size()-1) {
145                                 ModelInfo modelInfo = vnfResources[i].getModelInfo()
146                                 String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid()
147                                 logDebug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition, isDebugLogEnabled)
148                                 
149                                 if (vnfModelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) {
150                                         VnfResource vnfResourceDecomposition = vnfResources[i]
151                                         execution.setVariable('vnfResourceDecomposition', vnfResourceDecomposition)
152                                         def nfRole = vnfResourceDecomposition.getNfRole()                                       
153                                         execution.setVariable('nfRole', nfRole)
154                                         logDebug("vnfResourceDecomposition: " + vnfResourceDecomposition.toJsonString(), isDebugLogEnabled)                                     
155                                         break
156                                 }
157                                 else {
158                                         //exception!
159                                 }
160                                 
161                         }
162
163                         logDebug('Exited ' + method, isDebugLogEnabled)
164                 } catch (BpmnError e) {
165                         throw e;
166                 } catch (Exception e) {
167                         logError('Caught exception in ' + method, e)
168                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVnfResourceDecomposition(): ' + e.getMessage())
169                 }
170         }
171         
172         /**
173          * Check if this VNF is already in maintenance in A&AI.
174          *
175          *
176          * @param execution The flow's execution instance.
177          */
178         public void checkIfVnfInMaintInAAI(DelegateExecution execution) {
179                 def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' +
180                         'execution=' + execution.getId() +
181                         ')'
182                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
183                 execution.setVariable('errorCode', "0")
184                 execution.setVariable("workStep", "checkIfVnfInMaintInAAI")
185                 execution.setVariable("failedActivity", "AAI")
186                 logDebug('Entered ' + method, isDebugLogEnabled)
187
188                 try {
189                         def transactionLoggingUuid = UUID.randomUUID().toString()
190                         AAIRestClientImpl client = new AAIRestClientImpl()
191                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
192                         aaiValidator.setClient(client)
193                         def vnfId = execution.getVariable("vnfId")
194                         boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid)
195                         logDebug("isInMaint result: " + isInMaint, isDebugLogEnabled)
196                         execution.setVariable('isVnfInMaintenance', isInMaint)
197                         
198                         if (isInMaint) {
199                                 execution.setVariable("errorCode", "1003")
200                                 execution.setVariable("errorText", "VNF is in maintenance in A&AI")
201                         }
202
203
204                         logDebug('Exited ' + method, isDebugLogEnabled)
205                 } catch (BpmnError e) {
206                         throw e;
207                 } catch (Exception e) {
208                         logError('Caught exception in ' + method, e)                    
209                         execution.setVariable("errorCode", "1002")
210                         execution.setVariable("errorText", e.getMessage())
211                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
212                 }
213         }
214         
215         /**
216          * Get VNF info from A&AI.
217          *
218          *
219          * @param execution The flow's execution instance.
220          */
221         public void queryAAIForVnf(DelegateExecution execution) {
222                 def method = getClass().getSimpleName() + '.queryAAIForVnf(' +
223                         'execution=' + execution.getId() +
224                         ')'
225                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
226                 logDebug('Entered ' + method, isDebugLogEnabled)
227
228                 try {
229                         def transactionLoggingUuid = UUID.randomUUID().toString()
230                         def vnfId = execution.getVariable("vnfId")
231                         logDebug("vnfId is: " + vnfId, isDebugLogEnabled)
232                         def cloudRegionId = execution.getVariable("lcpCloudRegionId")
233                         logDebug("cloudRegionId is: " + cloudRegionId, isDebugLogEnabled)
234                         
235                         AAIResourcesClient client = new AAIResourcesClient()
236                         
237                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
238                         // Check if this VNF exists
239                         if (!client.exists(genericVnfUri)) {
240                                 logDebug("VNF with vnfId " + vnfId + " does not exist in A&AI", isDebugLogEnabled)
241                                 exceptionUtil.buildAndThrowWorkflowException(execution, 404, "VNF with vnfId " + vnfId + " does not exist in A&AI")
242                         }
243                         
244                         AAIResultWrapper aaiRW = client.get(genericVnfUri)
245                         
246                         Map<String, Object> result = aaiRW.asMap()
247                         
248                         String vnfName = result.get("vnf-name")
249                         logDebug("vnfName from A&AI is: " + vnfName, isDebugLogEnabled)
250                         execution.setVariable("vnfName", vnfName)
251                         String nfRole = result.get("nf-role")
252                         logDebug("nfRole from A&AI is: " + nfRole, isDebugLogEnabled)
253                         execution.setVariable("nfRole", nfRole)
254                         String vnfHostIpAddress = result.get("ipv4-oam-address")
255                         logDebug("vnfHostIpAddress from A&AI is: " + vnfHostIpAddress, isDebugLogEnabled)
256                         execution.setVariable("vnfHostIpAddress", vnfHostIpAddress)
257                         execution.setVariable("vmIdList", null)
258                         if (aaiRW.getRelationships() != null) {
259                                 Relationships relationships = aaiRW.getRelationships().get()
260                                 if (relationships != null) {
261                                                 
262                                         List<AAIResourceUri> vserverUris = relationships.getRelatedAAIUris(AAIObjectType.VSERVER)
263                                         JSONArray vserverIds = new JSONArray()
264                                 
265                                         for (AAIResourceUri j in vserverUris) {
266                                                 
267                                                 String vserverId = j.getURIKeys().get('vserver-id')
268                                                 vserverIds.put(vserverId)                                       
269                                         }
270                                 
271                                         JSONObject vmidsArray = new JSONObject()
272                                         vmidsArray.put("vmIds", vserverIds.toString())
273                                 
274                                         logDebug("vmidsArray is: " + vmidsArray.toString(), isDebugLogEnabled)                                                          
275                         
276                                         execution.setVariable("vmIdList", vmidsArray.toString())
277                                 }
278                         }
279                                                 
280                         if (cloudRegionId != null) {                    
281                                 AAIUri cloudRegionUri = AAIUriFactory.createResourceUri(AAIObjectType.DEFAULT_CLOUD_REGION, cloudRegionId)                              
282                                 // Check if this client region exists
283                                 if (!client.exists(cloudRegionUri)) {
284                                         logDebug("Cloud Region with cloudRegionId " + cloudRegionId + " does not exist in A&AI", isDebugLogEnabled)
285                                         exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Cloud Region with cloudRegionId " + cloudRegionId + " does not exist in A&AI")
286                                 }
287                         
288                                 AAIResultWrapper aaiRWCloud = client.get(cloudRegionUri)
289                         
290                                 Map<String, Object> resultCloud = aaiRWCloud.asMap()                    
291                         
292                                 String aicIdentity = resultCloud.get("identity-url")
293                                 logDebug("aicIdentity from A&AI is: " + aicIdentity, isDebugLogEnabled)
294                                 execution.setVariable("aicIdentity", aicIdentity)
295                         }
296
297                         logDebug('Exited ' + method, isDebugLogEnabled)
298                 } catch (BpmnError e) {
299                         throw e;
300                 } catch (Exception e) {
301                         logError('Caught exception in ' + method, e)
302                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIForVnf(): ' + e.getMessage())
303                 }
304         }
305
306         
307         
308         /**
309          * Check if this VNF's pservers are locked in A&AI.
310          *
311          *
312          * @param execution The flow's execution instance.
313          */
314         public void checkIfPserversInMaintInAAI(DelegateExecution execution) {
315                 def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' +
316                         'execution=' + execution.getId() +
317                         ')'
318                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
319                 execution.setVariable('errorCode', "0")
320                 logDebug('Entered ' + method, isDebugLogEnabled)
321                 execution.setVariable("workStep", "checkIfPserversInMaintInAAI")
322                 execution.setVariable("failedActivity", "AAI")
323
324                 try {
325                         def transactionLoggingUuid = UUID.randomUUID().toString()
326                         AAIRestClientImpl client = new AAIRestClientImpl()
327                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
328                         aaiValidator.setClient(client)
329                         def vnfId = execution.getVariable("vnfId")                      
330                         boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid)
331                         logDebug("areLocked result: " + areLocked, isDebugLogEnabled)
332                         execution.setVariable('arePserversLocked', areLocked)
333                         
334                         if (areLocked) {
335                                 execution.setVariable("errorCode", "1003")
336                                 execution.setVariable("errorText", "pServers are locked in A&AI")
337                         }                       
338
339                         logDebug('Exited ' + method, isDebugLogEnabled)
340                 } catch (BpmnError e) {
341                         throw e;
342                 } catch (Exception e) {
343                         logError('Caught exception in ' + method, e)
344                         execution.setVariable("errorCode", "1002")
345                         execution.setVariable("errorText", e.getMessage())
346                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage())
347                 }
348         }
349         
350         /**
351          * Set inMaint flag for this VNF to the specified value in A&AI.
352          *
353          *
354          * @param execution The flow's execution instance.
355          * @param inMaint The boolean value of the flag to set
356          */
357         public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) {
358                 def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' +
359                         'execution=' + execution.getId() +
360                         ')'
361                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
362                 execution.setVariable('errorCode', "0")
363                 logDebug('Entered ' + method, isDebugLogEnabled)
364                 if (inMaint) {
365                         execution.setVariable("workStep", "setVnfInMaintFlagInAAI")
366                 }
367                 else {
368                         execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI")
369                 }
370                 execution.setVariable("failedActivity", "AAI")
371
372                 try {
373                         def transactionLoggingUuid = UUID.randomUUID().toString()
374                         AAIRestClientImpl client = new AAIRestClientImpl()
375                         AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl()
376                         aaiUpdator.setClient(client)
377                         def vnfId = execution.getVariable("vnfId")
378                         if (inMaint) {
379                                 aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid)
380                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
381                         }
382                         else {
383                                 aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid)
384                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", false)
385                         }
386                                                         
387                         logDebug('Exited ' + method, isDebugLogEnabled)
388                 } catch (BpmnError e) {
389                         throw e;
390                 } catch (Exception e) {
391                         logError('Caught exception in ' + method, e)
392                         execution.setVariable("errorCode", "1002")
393                         execution.setVariable("errorText", e.getMessage())
394                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage())
395                 }
396         }
397         
398         /**
399          * Check if VF Closed Loop Disabled in A&AI.
400          *
401          *
402          * @param execution The flow's execution instance.
403          */
404         public void checkIfClosedLoopDisabledInAAI(DelegateExecution execution) {
405                 def method = getClass().getSimpleName() + '.checkIfClosedLoopDisabledInAAI(' +
406                         'execution=' + execution.getId() +
407                         ')'
408                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
409                 execution.setVariable('errorCode', "0")
410                 execution.setVariable("workStep", "checkClosedLoopDisabledFlagInAAI")
411                 execution.setVariable("failedActivity", "AAI")
412                 logDebug('Entered ' + method, isDebugLogEnabled)
413
414                 try {
415                         def transactionLoggingUuid = UUID.randomUUID().toString()                       
416                         def vnfId = execution.getVariable("vnfId")
417                         logDebug("vnfId is: " + vnfId, isDebugLogEnabled)
418                         AAIResourcesClient client = new AAIResourcesClient()                    
419                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
420                         AAIResultWrapper aaiRW = client.get(genericVnfUri)
421                         Map<String, Object> result = aaiRW.asMap()
422                         boolean isClosedLoopDisabled = result.getOrDefault("is-closed-loop-disabled", false)
423                 
424                         logDebug("isClosedLoopDisabled result: " + isClosedLoopDisabled, isDebugLogEnabled)
425                         execution.setVariable('isClosedLoopDisabled', isClosedLoopDisabled)
426                         
427                         if (isClosedLoopDisabled) {
428                                 execution.setVariable("errorCode", "1004")
429                                 execution.setVariable("errorText", "closedLoop is disabled in A&AI")
430                         }
431
432                         logDebug('Exited ' + method, isDebugLogEnabled)
433                 } catch (BpmnError e) {
434                         throw e;
435                 } catch (Exception e) {
436                         logError('Caught exception in ' + method, e)
437                         execution.setVariable("errorCode", "1002")
438                         execution.setVariable("errorText", e.getMessage())              
439                 }
440         }
441         
442         /**
443          * Set VF Closed Loop Disabled Flag in A&AI.
444          *
445          *
446          * @param execution The flow's execution instance.
447          */
448         public void setClosedLoopDisabledInAAI(DelegateExecution execution, boolean setDisabled) {
449                 def method = getClass().getSimpleName() + '.setClosedLoopDisabledInAAI(' +
450                         'execution=' + execution.getId() +
451                         ')'
452                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
453                 execution.setVariable('errorCode', "0")
454                 if (setDisabled) {
455                         execution.setVariable("workStep", "setClosedLoopDisabledFlagInAAI")
456                         execution.setVariable("rollbackSetClosedLoopDisabledFlag", true)
457                 }
458                 else {
459                         execution.setVariable("workStep", "unsetClosedLoopDisabledFlagInAAI")
460                         execution.setVariable("rollbackSetClosedLoopDisabledFlag", false)
461                 }
462                 
463                 execution.setVariable("failedActivity", "AAI")
464                 logDebug('Entered ' + method, isDebugLogEnabled)
465
466                 try {
467                         def transactionLoggingUuid = UUID.randomUUID().toString()
468                         def vnfId = execution.getVariable("vnfId")
469                         AAIResourcesClient client = new AAIResourcesClient()                    
470                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
471                         
472                         Map<String, Boolean> request = new HashMap<>()
473                         request.put("is-closed-loop-disabled", setDisabled)
474                         client.update(genericVnfUri, request)
475                         logDebug("set isClosedLoop to: " + setDisabled, isDebugLogEnabled)              
476
477                         logDebug('Exited ' + method, isDebugLogEnabled)
478                 } catch (BpmnError e) {
479                         throw e;
480                 } catch (Exception e) {
481                         logError('Caught exception in ' + method, e)
482                         execution.setVariable("errorCode", "1002")
483                         execution.setVariable("errorText", e.getMessage())                      
484                 }
485         }
486         
487         
488         
489         
490         /**
491          * Call APP-C client to execute specified APP-C command for this VNF.
492          *
493          *
494          * @param execution The flow's execution instance.
495          * @param action The action to take in APP-C.
496          */
497         public void runAppcCommand(DelegateExecution execution, Action action) {
498                 def method = getClass().getSimpleName() + '.runAppcCommand(' +
499                         'execution=' + execution.getId() +
500                         ')'
501                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
502                 execution.setVariable('errorCode', "0")
503                 logDebug('Entered ' + method, isDebugLogEnabled)
504                 
505                 ApplicationControllerClient appcClient = null
506                 
507                 try {
508                         logDebug("Running APP-C action: " + action.toString(), isDebugLogEnabled)
509                         String vnfId = execution.getVariable('vnfId')
510                         String msoRequestId = execution.getVariable('requestId')
511                         execution.setVariable('msoRequestId', msoRequestId)                     
512                         execution.setVariable("failedActivity", "APP-C")
513                         
514                         appcClient = new ApplicationControllerClient()                          
515                         ApplicationControllerSupport support = new ApplicationControllerSupport()                       
516                         appcClient.appCSupport=support                  
517                         org.springframework.test.util.ReflectionTestUtils.setField(support, "lcmModelPackage", "org.onap.appc.client.lcm.model");                       
518                         Flags flags = new Flags();                      
519                         ActionIdentifiers actionIdentifiers = new ActionIdentifiers();                  
520                         actionIdentifiers.setVnfId(vnfId);
521                         Status appcStatus
522                         switch(action) {
523                                 case Action.Lock:
524                                         execution.setVariable('workStep', "LockVNF")
525                                         appcStatus = appcClient.runCommand(Action.Lock,actionIdentifiers,null,msoRequestId)                                     
526                                         break
527                                 case Action.Unlock:
528                                         execution.setVariable('workStep', "UnlockVNF")
529                                         appcStatus = appcClient.runCommand(Action.Unlock,actionIdentifiers,null,msoRequestId)                                   
530                                         break
531                                 case Action.HealthCheck:
532                                         def healthCheckIndex = execution.getVariable('healthCheckIndex')
533                                         execution.setVariable('workStep', "HealthCheckVNF" + healthCheckIndex)
534                                         execution.setVariable('healthCheckIndex', healthCheckIndex + 1)
535                                         appcStatus = appcClient.runCommand(Action.HealthCheck,actionIdentifiers,null,msoRequestId)                                      
536                                         break
537                                 case Action.Start:
538                                         execution.setVariable('workStep', "StartVNF")
539                                         appcStatus = appcClient.runCommand(Action.Start,actionIdentifiers,null,msoRequestId)                                    
540                                         break
541                                 case Action.Stop:
542                                         execution.setVariable('workStep', "StopVNF")
543                                         appcStatus = appcClient.runCommand(Action.Stop,actionIdentifiers,null,msoRequestId)                                     
544                                         break
545                                 default:
546                                         break
547                         }
548                         logDebug("Completed AppC request", isDebugLogEnabled)                   
549                         int appcCode = appcStatus.getCode()
550                         logDebug("AppC status code is: " + appcCode, isDebugLogEnabled)
551                         logDebug("AppC status message is: " + appcStatus.getMessage(), isDebugLogEnabled)
552                         if (support.getCategoryOf(appcStatus) == ApplicationControllerSupport.StatusCategory.ERROR) {
553                                 execution.setVariable("errorCode", Integer.toString(appcCode))
554                                 execution.setVariable("errorText", appcStatus.getMessage())                             
555                         }
556                                 
557                         logDebug('Exited ' + method, isDebugLogEnabled)
558                 } catch (BpmnError e) {
559                         logError('Caught exception in ' + method, e)
560                         execution.setVariable("errorCode", "1002")
561                         execution.setVariable("errorText", e.getMessage())
562                         
563                 } catch (java.lang.NoSuchMethodError e) {
564                         logError('Caught exception in ' + method, e)
565                         execution.setVariable("errorCode", "1002")
566                         execution.setVariable("errorText", e.getMessage())              
567                         
568                 } catch (Exception e) {
569                         logError('Caught exception in ' + method, e)
570                         execution.setVariable("errorCode", "1002")
571                         execution.setVariable("errorText", e.getMessage())      
572                         
573                 }
574         }
575         
576         /**
577          * Placeholder for a call to APP-C client to execute specified APP-C command for this VNF.
578          *
579          *
580          * @param execution The flow's execution instance.
581          * @param action The action to take in APP-C.
582          */
583         public void runAppcCommandPlaceholder(DelegateExecution execution, String action) {
584                 def method = getClass().getSimpleName() + '.runAppcCommandPlaceholder(' +
585                         'execution=' + execution.getId() +
586                         ')'
587                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')              
588                 execution.setVariable('errorCode', "0")
589                 logDebug('Entered ' + method, isDebugLogEnabled)                
590                 execution.setVariable("failedActivity", "APP-C")
591                 execution.setVariable("workStep", action)               
592         }
593
594
595
596
597
598         
599
600         /**
601          * Builds a "CompletionHandler" request and stores it in the specified execution variable.
602          *
603          * @param execution the execution
604          * @param resultVar the execution variable in which the result will be stored
605          */
606         public void completionHandlerPrep(DelegateExecution execution, String resultVar) {
607                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
608                         'execution=' + execution.getId() +
609                         ', resultVar=' + resultVar +
610                         ')'
611                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
612                 logDebug('Entered ' + method, isDebugLogEnabled)                
613
614                 try {
615                         
616                         def requestInfo = execution.getVariable('requestInfo')
617
618                         String content = """
619                                 <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
620                                                 xmlns:reqtype="http://org.openecomp/mso/request/types/v1">
621                                         ${requestInfo}
622                                         <sdncadapterworkflow:status-message>Vnf has been updated successfully.</sdncadapterworkflow:status-message>
623                                         <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name>
624                                 </sdncadapterworkflow:MsoCompletionRequest>
625                         """
626
627                         content = utils.formatXml(content)
628                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
629                         execution.setVariable(resultVar, content)
630
631                         logDebug('Exited ' + method, isDebugLogEnabled)
632                 } catch (BpmnError e) {
633                         throw e;
634                 } catch (Exception e) {
635                         logError('Caught exception in ' + method, e)
636                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error')
637                 }
638         }
639         
640         /**
641         * Prepare DoUpdateVnfAndModules call.
642         *
643         *
644         * @param execution The flow's execution instance.
645         */
646    public void prepDoUpdateVnfAndModules(DelegateExecution execution) {
647            def method = getClass().getSimpleName() + '.prepDoUpdateVnfAndModules(' +
648                    'execution=' + execution.getId() +
649                    ')'
650            def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
651            execution.setVariable('errorCode', "0")
652            logDebug('Entered ' + method, isDebugLogEnabled)
653            execution.setVariable("workStep", "doUpdateVnfAndModules")
654            execution.setVariable("failedActivity", "MSO Update VNF")
655            logDebug('Exited ' + method, isDebugLogEnabled)
656            
657    }
658         
659         /**
660          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
661          *
662          * @param execution the execution
663          * @param resultVar the execution variable in which the result will be stored
664          */
665         public void falloutHandlerPrep(DelegateExecution execution, String resultVar) {
666                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
667                         'execution=' + execution.getId() +
668                         ', resultVar=' + resultVar +
669                         ')'
670                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
671                 logDebug('Entered ' + method, isDebugLogEnabled)
672
673                 try {
674                         def prefix = execution.getVariable('prefix')                    
675                         def requestInformation = execution.getVariable("requestInfo")           
676                         
677                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
678                         def errorResponseCode = workflowException.getErrorCode()
679                         def errorResponseMsg = workflowException.getErrorMessage()
680                         def encErrorResponseMsg = ""
681                         if (errorResponseMsg != null) {
682                                 encErrorResponseMsg = errorResponseMsg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
683                         }
684
685                         String content = """
686                                 <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
687                                                 xmlns:reqtype="http://org.openecomp/mso/request/types/v1"
688                                                 xmlns:msoservtypes="http://org.openecomp/mso/request/types/v1"
689                                                 xmlns:structuredtypes="http://org.openecomp/mso/structured/types/v1">
690                                         ${requestInformation}
691                                         <sdncadapterworkflow:WorkflowException>
692                                                 <sdncadapterworkflow:ErrorMessage>${encErrorResponseMsg}</sdncadapterworkflow:ErrorMessage>
693                                                 <sdncadapterworkflow:ErrorCode>${errorResponseCode}</sdncadapterworkflow:ErrorCode>
694                                         </sdncadapterworkflow:WorkflowException>
695                                 </sdncadapterworkflow:FalloutHandlerRequest>
696                         """
697                         content = utils.formatXml(content)
698                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
699                         execution.setVariable(resultVar, content)
700
701                         logDebug('Exited ' + method, isDebugLogEnabled)
702                 } catch (BpmnError e) {
703                         throw e;
704                 } catch (Exception e) {
705                         logError('Caught exception in ' + method, e)
706                         exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error')
707                 }
708         }
709         
710         /**
711          * Handle Abort disposition from RainyDayHandler
712          *
713          * @param execution The flow's execution instance.       
714          */
715         public void abortProcessing(DelegateExecution execution) {
716                 def method = getClass().getSimpleName() + '.abortProcessing(' +
717                         'execution=' + execution.getId() +
718                         ')'
719                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
720                 logDebug('Entered ' + method, isDebugLogEnabled)
721                 
722                 def errorText = execution.getVariable("errorText")
723                 def errorCode = execution.getVariable("errorCode")
724                 
725                 exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText)
726         }       
727         
728         /**
729          * Increment Retry Count for Current Work Step
730          *
731          * @param execution The flow's execution instance.
732          */
733         public void incrementRetryCount(DelegateExecution execution) {
734                 def method = getClass().getSimpleName() + '.incrementRetryCount(' +
735                         'execution=' + execution.getId() +
736                         ')'
737                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
738                 logDebug('Entered ' + method, isDebugLogEnabled)
739                 
740                 String retryCountVariableName = execution.getVariable("workStep") + "RetryCount"
741                 execution.setVariable("retryCountVariableName", retryCountVariableName)
742                 
743                 def retryCountVariable = execution.getVariable(retryCountVariableName)
744                 int retryCount = 0
745                 
746                 if (retryCountVariable != null) {
747                         retryCount = (int) retryCountVariable
748                 }
749                 
750                 retryCount += 1
751                 
752                 execution.setVariable(retryCountVariableName, retryCount)
753                 
754                 logDebug("value of " + retryCountVariableName + " is " + retryCount, isDebugLogEnabled)
755                 logDebug('Exited ' + method, isDebugLogEnabled)
756                         
757                 
758         }
759         
760         public void preProcessRollback (DelegateExecution execution) {
761                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
762                 utils.log("DEBUG"," ***** preProcessRollback ***** ", isDebugEnabled)
763                 try {
764                         
765                         Object workflowException = execution.getVariable("WorkflowException");
766  
767                         if (workflowException instanceof WorkflowException) {
768                                 utils.log("DEBUG", "Prev workflowException: " + workflowException.getErrorMessage(), isDebugEnabled)
769                                 execution.setVariable("prevWorkflowException", workflowException);
770                                 //execution.setVariable("WorkflowException", null);
771                         }
772                 } catch (BpmnError e) {
773                         utils.log("DEBUG", "BPMN Error during preProcessRollback", isDebugEnabled)
774                 } catch(Exception ex) {
775                         String msg = "Exception in preProcessRollback. " + ex.getMessage()
776                         utils.log("DEBUG", msg, isDebugEnabled)
777                 }
778                 utils.log("DEBUG"," *** Exit preProcessRollback *** ", isDebugEnabled)
779         }
780  
781         public void postProcessRollback (DelegateExecution execution) {
782                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
783                 utils.log("DEBUG"," ***** postProcessRollback ***** ", isDebugEnabled)
784                 String msg = ""
785                 try {
786                         Object workflowException = execution.getVariable("prevWorkflowException");
787                         if (workflowException instanceof WorkflowException) {
788                                 utils.log("DEBUG", "Setting prevException to WorkflowException: ", isDebugEnabled)
789                                 execution.setVariable("WorkflowException", workflowException);
790                         }
791                         
792                 } catch (BpmnError b) {
793                         utils.log("DEBUG", "BPMN Error during postProcessRollback", isDebugEnabled)
794                         throw b;
795                 } catch(Exception ex) {
796                         msg = "Exception in postProcessRollback. " + ex.getMessage()
797                         utils.log("DEBUG", msg, isDebugEnabled)
798                 }
799                 utils.log("DEBUG"," *** Exit postProcessRollback *** ", isDebugEnabled)
800         }
801  
802
803         
804 }