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