Merge "Reorder modifiers"
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / VnfCmBase.groovy
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                                 String cloudOwnerId = "att-aic"; 
282                                 try {
283                                     cloudOwnerId = execution.getVariable("URN_mso_default_cloud_owner_id");
284                                     if (cloudOwnerId == null) cloudOwnerId = "att-aic";
285                                 } catch (RuntimeException e) {
286                                         cloudOwnerId = "att-aic"; 
287                                 }
288                                 
289                                 AAIUri cloudRegionUri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudOwnerId, cloudRegionId)                                
290                                 // Check if this client region exists
291                                 if (!client.exists(cloudRegionUri)) {
292                                         logDebug("Cloud Region with cloudOwner ID " + cloudOwnerId + " and cloudRegionId " + cloudRegionId + " does not exist in A&AI", isDebugLogEnabled)
293                                         exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Cloud Region with cloudRegionId " + cloudRegionId + " does not exist in A&AI")
294                                 }
295                         
296                                 AAIResultWrapper aaiRWCloud = client.get(cloudRegionUri)
297                         
298                                 Map<String, Object> resultCloud = aaiRWCloud.asMap()                    
299                         
300                                 String aicIdentity = resultCloud.get("identity-url")
301                                 logDebug("aicIdentity from A&AI is: " + aicIdentity, isDebugLogEnabled)
302                                 execution.setVariable("aicIdentity", aicIdentity)
303                         }
304
305                         logDebug('Exited ' + method, isDebugLogEnabled)
306                 } catch (BpmnError e) {
307                         throw e;
308                 } catch (Exception e) {
309                         logError('Caught exception in ' + method, e)
310                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIForVnf(): ' + e.getMessage())
311                 }
312         }
313
314         
315         
316         /**
317          * Check if this VNF's pservers are locked in A&AI.
318          *
319          *
320          * @param execution The flow's execution instance.
321          */
322         public void checkIfPserversInMaintInAAI(DelegateExecution execution) {
323                 def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' +
324                         'execution=' + execution.getId() +
325                         ')'
326                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
327                 execution.setVariable('errorCode', "0")
328                 logDebug('Entered ' + method, isDebugLogEnabled)
329                 execution.setVariable("workStep", "checkIfPserversInMaintInAAI")
330                 execution.setVariable("failedActivity", "AAI")
331
332                 try {
333                         def transactionLoggingUuid = UUID.randomUUID().toString()
334                         AAIRestClientImpl client = new AAIRestClientImpl()
335                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
336                         aaiValidator.setClient(client)
337                         def vnfId = execution.getVariable("vnfId")                      
338                         boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid)
339                         logDebug("areLocked result: " + areLocked, isDebugLogEnabled)
340                         execution.setVariable('arePserversLocked', areLocked)
341                         
342                         if (areLocked) {
343                                 execution.setVariable("errorCode", "1003")
344                                 execution.setVariable("errorText", "pServers are locked in A&AI")
345                         }                       
346
347                         logDebug('Exited ' + method, isDebugLogEnabled)
348                 } catch (BpmnError e) {
349                         throw e;
350                 } catch (Exception e) {
351                         logError('Caught exception in ' + method, e)
352                         execution.setVariable("errorCode", "1002")
353                         execution.setVariable("errorText", e.getMessage())
354                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage())
355                 }
356         }
357         
358         /**
359          * Set inMaint flag for this VNF to the specified value in A&AI.
360          *
361          *
362          * @param execution The flow's execution instance.
363          * @param inMaint The boolean value of the flag to set
364          */
365         public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) {
366                 def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' +
367                         'execution=' + execution.getId() +
368                         ')'
369                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
370                 execution.setVariable('errorCode', "0")
371                 logDebug('Entered ' + method, isDebugLogEnabled)
372                 if (inMaint) {
373                         execution.setVariable("workStep", "setVnfInMaintFlagInAAI")
374                 }
375                 else {
376                         execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI")
377                 }
378                 execution.setVariable("failedActivity", "AAI")
379
380                 try {
381                         def transactionLoggingUuid = UUID.randomUUID().toString()
382                         AAIRestClientImpl client = new AAIRestClientImpl()
383                         AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl()
384                         aaiUpdator.setClient(client)
385                         def vnfId = execution.getVariable("vnfId")
386                         if (inMaint) {
387                                 aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid)
388                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
389                         }
390                         else {
391                                 aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid)
392                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", false)
393                         }
394                                                         
395                         logDebug('Exited ' + method, isDebugLogEnabled)
396                 } catch (BpmnError e) {
397                         throw e;
398                 } catch (Exception e) {
399                         logError('Caught exception in ' + method, e)
400                         execution.setVariable("errorCode", "1002")
401                         execution.setVariable("errorText", e.getMessage())
402                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage())
403                 }
404         }
405         
406         /**
407          * Check if VF Closed Loop Disabled in A&AI.
408          *
409          *
410          * @param execution The flow's execution instance.
411          */
412         public void checkIfClosedLoopDisabledInAAI(DelegateExecution execution) {
413                 def method = getClass().getSimpleName() + '.checkIfClosedLoopDisabledInAAI(' +
414                         'execution=' + execution.getId() +
415                         ')'
416                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
417                 execution.setVariable('errorCode', "0")
418                 execution.setVariable("workStep", "checkClosedLoopDisabledFlagInAAI")
419                 execution.setVariable("failedActivity", "AAI")
420                 logDebug('Entered ' + method, isDebugLogEnabled)
421
422                 try {
423                         def transactionLoggingUuid = UUID.randomUUID().toString()                       
424                         def vnfId = execution.getVariable("vnfId")
425                         logDebug("vnfId is: " + vnfId, isDebugLogEnabled)
426                         AAIResourcesClient client = new AAIResourcesClient()                    
427                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
428                         AAIResultWrapper aaiRW = client.get(genericVnfUri)
429                         Map<String, Object> result = aaiRW.asMap()
430                         boolean isClosedLoopDisabled = result.getOrDefault("is-closed-loop-disabled", false)
431                 
432                         logDebug("isClosedLoopDisabled result: " + isClosedLoopDisabled, isDebugLogEnabled)
433                         execution.setVariable('isClosedLoopDisabled', isClosedLoopDisabled)
434                         
435                         if (isClosedLoopDisabled) {
436                                 execution.setVariable("errorCode", "1004")
437                                 execution.setVariable("errorText", "closedLoop is disabled in A&AI")
438                         }
439
440                         logDebug('Exited ' + method, isDebugLogEnabled)
441                 } catch (BpmnError e) {
442                         throw e;
443                 } catch (Exception e) {
444                         logError('Caught exception in ' + method, e)
445                         execution.setVariable("errorCode", "1002")
446                         execution.setVariable("errorText", e.getMessage())              
447                 }
448         }
449         
450         /**
451          * Set VF Closed Loop Disabled Flag in A&AI.
452          *
453          *
454          * @param execution The flow's execution instance.
455          */
456         public void setClosedLoopDisabledInAAI(DelegateExecution execution, boolean setDisabled) {
457                 def method = getClass().getSimpleName() + '.setClosedLoopDisabledInAAI(' +
458                         'execution=' + execution.getId() +
459                         ')'
460                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
461                 execution.setVariable('errorCode', "0")
462                 if (setDisabled) {
463                         execution.setVariable("workStep", "setClosedLoopDisabledFlagInAAI")
464                         execution.setVariable("rollbackSetClosedLoopDisabledFlag", true)
465                 }
466                 else {
467                         execution.setVariable("workStep", "unsetClosedLoopDisabledFlagInAAI")
468                         execution.setVariable("rollbackSetClosedLoopDisabledFlag", false)
469                 }
470                 
471                 execution.setVariable("failedActivity", "AAI")
472                 logDebug('Entered ' + method, isDebugLogEnabled)
473
474                 try {
475                         def transactionLoggingUuid = UUID.randomUUID().toString()
476                         def vnfId = execution.getVariable("vnfId")
477                         AAIResourcesClient client = new AAIResourcesClient()                    
478                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
479                         
480                         Map<String, Boolean> request = new HashMap<>()
481                         request.put("is-closed-loop-disabled", setDisabled)
482                         client.update(genericVnfUri, request)
483                         logDebug("set isClosedLoop to: " + setDisabled, isDebugLogEnabled)              
484
485                         logDebug('Exited ' + method, isDebugLogEnabled)
486                 } catch (BpmnError e) {
487                         throw e;
488                 } catch (Exception e) {
489                         logError('Caught exception in ' + method, e)
490                         execution.setVariable("errorCode", "1002")
491                         execution.setVariable("errorText", e.getMessage())                      
492                 }
493         }
494         
495         
496         
497         
498         /**
499          * Call APP-C client to execute specified APP-C command for this VNF.
500          *
501          *
502          * @param execution The flow's execution instance.
503          * @param action The action to take in APP-C.
504          */
505         public void runAppcCommand(DelegateExecution execution, Action action) {
506                 def method = getClass().getSimpleName() + '.runAppcCommand(' +
507                         'execution=' + execution.getId() +
508                         ')'
509                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
510                 execution.setVariable('errorCode', "0")
511                 logDebug('Entered ' + method, isDebugLogEnabled)
512                 
513                 ApplicationControllerClient appcClient = null
514                 
515                 try {
516                         logDebug("Running APP-C action: " + action.toString(), isDebugLogEnabled)
517                         String vnfId = execution.getVariable('vnfId')
518                         String msoRequestId = execution.getVariable('requestId')
519                         execution.setVariable('msoRequestId', msoRequestId)                     
520                         execution.setVariable("failedActivity", "APP-C")
521                         
522                         appcClient = new ApplicationControllerClient()                          
523                         ApplicationControllerSupport support = new ApplicationControllerSupport()                       
524                         appcClient.appCSupport=support                  
525                         org.springframework.test.util.ReflectionTestUtils.setField(support, "lcmModelPackage", "org.onap.appc.client.lcm.model");                       
526                         Flags flags = new Flags();                      
527                         ActionIdentifiers actionIdentifiers = new ActionIdentifiers();                  
528                         actionIdentifiers.setVnfId(vnfId);
529                         Status appcStatus
530                         switch(action) {
531                                 case Action.Lock:
532                                         execution.setVariable('workStep', "LockVNF")
533                                         appcStatus = appcClient.runCommand(Action.Lock,actionIdentifiers,null,msoRequestId)                                     
534                                         break
535                                 case Action.Unlock:
536                                         execution.setVariable('workStep', "UnlockVNF")
537                                         appcStatus = appcClient.runCommand(Action.Unlock,actionIdentifiers,null,msoRequestId)                                   
538                                         break
539                                 case Action.HealthCheck:
540                                         def healthCheckIndex = execution.getVariable('healthCheckIndex')
541                                         execution.setVariable('workStep', "HealthCheckVNF" + healthCheckIndex)
542                                         execution.setVariable('healthCheckIndex', healthCheckIndex + 1)
543                                         appcStatus = appcClient.runCommand(Action.HealthCheck,actionIdentifiers,null,msoRequestId)                                      
544                                         break
545                                 case Action.Start:
546                                         execution.setVariable('workStep', "StartVNF")
547                                         appcStatus = appcClient.runCommand(Action.Start,actionIdentifiers,null,msoRequestId)                                    
548                                         break
549                                 case Action.Stop:
550                                         execution.setVariable('workStep', "StopVNF")
551                                         appcStatus = appcClient.runCommand(Action.Stop,actionIdentifiers,null,msoRequestId)                                     
552                                         break
553                                 default:
554                                         break
555                         }
556                         logDebug("Completed AppC request", isDebugLogEnabled)                   
557                         int appcCode = appcStatus.getCode()
558                         logDebug("AppC status code is: " + appcCode, isDebugLogEnabled)
559                         logDebug("AppC status message is: " + appcStatus.getMessage(), isDebugLogEnabled)
560                         if (support.getCategoryOf(appcStatus) == ApplicationControllerSupport.StatusCategory.ERROR) {
561                                 execution.setVariable("errorCode", Integer.toString(appcCode))
562                                 execution.setVariable("errorText", appcStatus.getMessage())                             
563                         }
564                                 
565                         logDebug('Exited ' + method, isDebugLogEnabled)
566                 } catch (BpmnError e) {
567                         logError('Caught exception in ' + method, e)
568                         execution.setVariable("errorCode", "1002")
569                         execution.setVariable("errorText", e.getMessage())
570                         
571                 } catch (java.lang.NoSuchMethodError e) {
572                         logError('Caught exception in ' + method, e)
573                         execution.setVariable("errorCode", "1002")
574                         execution.setVariable("errorText", e.getMessage())              
575                         
576                 } catch (Exception e) {
577                         logError('Caught exception in ' + method, e)
578                         execution.setVariable("errorCode", "1002")
579                         execution.setVariable("errorText", e.getMessage())      
580                         
581                 }
582         }
583         
584         /**
585          * Placeholder for a call to APP-C client to execute specified APP-C command for this VNF.
586          *
587          *
588          * @param execution The flow's execution instance.
589          * @param action The action to take in APP-C.
590          */
591         public void runAppcCommandPlaceholder(DelegateExecution execution, String action) {
592                 def method = getClass().getSimpleName() + '.runAppcCommandPlaceholder(' +
593                         'execution=' + execution.getId() +
594                         ')'
595                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')              
596                 execution.setVariable('errorCode', "0")
597                 logDebug('Entered ' + method, isDebugLogEnabled)                
598                 execution.setVariable("failedActivity", "APP-C")
599                 execution.setVariable("workStep", action)               
600         }
601
602
603
604
605
606         
607
608         /**
609          * Builds a "CompletionHandler" request and stores it in the specified execution variable.
610          *
611          * @param execution the execution
612          * @param resultVar the execution variable in which the result will be stored
613          */
614         public void completionHandlerPrep(DelegateExecution execution, String resultVar) {
615                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
616                         'execution=' + execution.getId() +
617                         ', resultVar=' + resultVar +
618                         ')'
619                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
620                 logDebug('Entered ' + method, isDebugLogEnabled)                
621
622                 try {
623                         
624                         def requestInfo = execution.getVariable('requestInfo')
625
626                         String content = """
627                                 <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
628                                                 xmlns:reqtype="http://org.openecomp/mso/request/types/v1">
629                                         ${requestInfo}
630                                         <sdncadapterworkflow:status-message>Vnf has been updated successfully.</sdncadapterworkflow:status-message>
631                                         <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name>
632                                 </sdncadapterworkflow:MsoCompletionRequest>
633                         """
634
635                         content = utils.formatXml(content)
636                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
637                         execution.setVariable(resultVar, content)
638
639                         logDebug('Exited ' + method, isDebugLogEnabled)
640                 } catch (BpmnError e) {
641                         throw e;
642                 } catch (Exception e) {
643                         logError('Caught exception in ' + method, e)
644                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error')
645                 }
646         }
647         
648         /**
649         * Prepare DoUpdateVnfAndModules call.
650         *
651         *
652         * @param execution The flow's execution instance.
653         */
654    public void prepDoUpdateVnfAndModules(DelegateExecution execution) {
655            def method = getClass().getSimpleName() + '.prepDoUpdateVnfAndModules(' +
656                    'execution=' + execution.getId() +
657                    ')'
658            def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
659            execution.setVariable('errorCode', "0")
660            logDebug('Entered ' + method, isDebugLogEnabled)
661            execution.setVariable("workStep", "doUpdateVnfAndModules")
662            execution.setVariable("failedActivity", "MSO Update VNF")
663            logDebug('Exited ' + method, isDebugLogEnabled)
664            
665    }
666         
667         /**
668          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
669          *
670          * @param execution the execution
671          * @param resultVar the execution variable in which the result will be stored
672          */
673         public void falloutHandlerPrep(DelegateExecution execution, String resultVar) {
674                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
675                         'execution=' + execution.getId() +
676                         ', resultVar=' + resultVar +
677                         ')'
678                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
679                 logDebug('Entered ' + method, isDebugLogEnabled)
680
681                 try {
682                         def prefix = execution.getVariable('prefix')                    
683                         def requestInformation = execution.getVariable("requestInfo")           
684                         
685                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
686                         def errorResponseCode = workflowException.getErrorCode()
687                         def errorResponseMsg = workflowException.getErrorMessage()
688                         def encErrorResponseMsg = ""
689                         if (errorResponseMsg != null) {
690                                 encErrorResponseMsg = errorResponseMsg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
691                         }
692
693                         String content = """
694                                 <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
695                                                 xmlns:reqtype="http://org.openecomp/mso/request/types/v1"
696                                                 xmlns:msoservtypes="http://org.openecomp/mso/request/types/v1"
697                                                 xmlns:structuredtypes="http://org.openecomp/mso/structured/types/v1">
698                                         ${requestInformation}
699                                         <sdncadapterworkflow:WorkflowException>
700                                                 <sdncadapterworkflow:ErrorMessage>${encErrorResponseMsg}</sdncadapterworkflow:ErrorMessage>
701                                                 <sdncadapterworkflow:ErrorCode>${errorResponseCode}</sdncadapterworkflow:ErrorCode>
702                                         </sdncadapterworkflow:WorkflowException>
703                                 </sdncadapterworkflow:FalloutHandlerRequest>
704                         """
705                         content = utils.formatXml(content)
706                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
707                         execution.setVariable(resultVar, content)
708
709                         logDebug('Exited ' + method, isDebugLogEnabled)
710                 } catch (BpmnError e) {
711                         throw e;
712                 } catch (Exception e) {
713                         logError('Caught exception in ' + method, e)
714                         exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error')
715                 }
716         }
717         
718         /**
719          * Handle Abort disposition from RainyDayHandler
720          *
721          * @param execution The flow's execution instance.       
722          */
723         public void abortProcessing(DelegateExecution execution) {
724                 def method = getClass().getSimpleName() + '.abortProcessing(' +
725                         'execution=' + execution.getId() +
726                         ')'
727                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
728                 logDebug('Entered ' + method, isDebugLogEnabled)
729                 
730                 def errorText = execution.getVariable("errorText")
731                 def errorCode = execution.getVariable("errorCode")
732                 
733                 exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText)
734         }       
735         
736         /**
737          * Increment Retry Count for Current Work Step
738          *
739          * @param execution The flow's execution instance.
740          */
741         public void incrementRetryCount(DelegateExecution execution) {
742                 def method = getClass().getSimpleName() + '.incrementRetryCount(' +
743                         'execution=' + execution.getId() +
744                         ')'
745                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
746                 logDebug('Entered ' + method, isDebugLogEnabled)
747                 
748                 String retryCountVariableName = execution.getVariable("workStep") + "RetryCount"
749                 execution.setVariable("retryCountVariableName", retryCountVariableName)
750                 
751                 def retryCountVariable = execution.getVariable(retryCountVariableName)
752                 int retryCount = 0
753                 
754                 if (retryCountVariable != null) {
755                         retryCount = (int) retryCountVariable
756                 }
757                 
758                 retryCount += 1
759                 
760                 execution.setVariable(retryCountVariableName, retryCount)
761                 
762                 logDebug("value of " + retryCountVariableName + " is " + retryCount, isDebugLogEnabled)
763                 logDebug('Exited ' + method, isDebugLogEnabled)
764                         
765                 
766         }
767         
768         public void preProcessRollback (DelegateExecution execution) {
769                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
770                 utils.log("DEBUG"," ***** preProcessRollback ***** ", isDebugEnabled)
771                 try {
772                         
773                         Object workflowException = execution.getVariable("WorkflowException");
774  
775                         if (workflowException instanceof WorkflowException) {
776                                 utils.log("DEBUG", "Prev workflowException: " + workflowException.getErrorMessage(), isDebugEnabled)
777                                 execution.setVariable("prevWorkflowException", workflowException);
778                                 //execution.setVariable("WorkflowException", null);
779                         }
780                 } catch (BpmnError e) {
781                         utils.log("DEBUG", "BPMN Error during preProcessRollback", isDebugEnabled)
782                 } catch(Exception ex) {
783                         String msg = "Exception in preProcessRollback. " + ex.getMessage()
784                         utils.log("DEBUG", msg, isDebugEnabled)
785                 }
786                 utils.log("DEBUG"," *** Exit preProcessRollback *** ", isDebugEnabled)
787         }
788  
789         public void postProcessRollback (DelegateExecution execution) {
790                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
791                 utils.log("DEBUG"," ***** postProcessRollback ***** ", isDebugEnabled)
792                 String msg = ""
793                 try {
794                         Object workflowException = execution.getVariable("prevWorkflowException");
795                         if (workflowException instanceof WorkflowException) {
796                                 utils.log("DEBUG", "Setting prevException to WorkflowException: ", isDebugEnabled)
797                                 execution.setVariable("WorkflowException", workflowException);
798                         }
799                         
800                 } catch (BpmnError b) {
801                         utils.log("DEBUG", "BPMN Error during postProcessRollback", isDebugEnabled)
802                         throw b;
803                 } catch(Exception ex) {
804                         msg = "Exception in postProcessRollback. " + ex.getMessage()
805                         utils.log("DEBUG", msg, isDebugEnabled)
806                 }
807                 utils.log("DEBUG"," *** Exit postProcessRollback *** ", isDebugEnabled)
808         }
809  
810
811         
812 }