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