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