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