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