2  * ============LICENSE_START=======================================================
 
   3  * controlloop operation manager
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017-2018 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
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  13  * Unless required by applicable law or agreed to in writing, software
 
  14  * distributed under the License is distributed on an "AS IS" BASIS,
 
  15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  16  * See the License for the specific language governing permissions and
 
  17  * limitations under the License.
 
  18  * ============LICENSE_END=========================================================
 
  21 package org.onap.policy.controlloop.eventmanager;
 
  23 import java.io.Serializable;
 
  24 import java.sql.Timestamp;
 
  25 import java.time.Instant;
 
  26 import java.util.AbstractMap;
 
  27 import java.util.LinkedList;
 
  28 import java.util.List;
 
  29 import java.util.NoSuchElementException;
 
  30 import java.util.Properties;
 
  32 import javax.persistence.EntityManager;
 
  33 import javax.persistence.Persistence;
 
  35 import org.eclipse.persistence.config.PersistenceUnitProperties;
 
  36 import org.onap.policy.aai.util.AaiException;
 
  37 import org.onap.policy.appc.Response;
 
  38 import org.onap.policy.appc.ResponseCode;
 
  39 import org.onap.policy.appclcm.LcmResponseWrapper;
 
  40 import org.onap.policy.controlloop.ControlLoopEvent;
 
  41 import org.onap.policy.controlloop.ControlLoopException;
 
  42 import org.onap.policy.controlloop.ControlLoopOperation;
 
  43 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 
  44 import org.onap.policy.controlloop.actor.appc.APPCActorServiceProvider;
 
  45 import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
 
  46 import org.onap.policy.controlloop.actor.sdnr.SdnrActorServiceProvider;
 
  47 import org.onap.policy.controlloop.actor.so.SOActorServiceProvider;
 
  48 import org.onap.policy.controlloop.actor.vfc.VFCActorServiceProvider;
 
  49 import org.onap.policy.controlloop.policy.Policy;
 
  50 import org.onap.policy.controlloop.policy.PolicyResult;
 
  51 import org.onap.policy.drools.system.PolicyEngine;
 
  52 import org.onap.policy.guard.Util;
 
  53 import org.onap.policy.sdnr.PciResponseWrapper;
 
  54 import org.onap.policy.so.SOResponseWrapper;
 
  55 import org.onap.policy.vfc.VFCResponse;
 
  56 import org.slf4j.Logger;
 
  57 import org.slf4j.LoggerFactory;
 
  59 public class ControlLoopOperationManager implements Serializable {
 
  60     private static final long serialVersionUID = -3773199283624595410L;
 
  61     private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
 
  63     private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
 
  64     private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
 
  65     private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
 
  68     public String toString() {
 
  69         return "ControlLoopOperationManager [onset=" + (onset != null ? onset.getRequestId() : "null") + ", policy="
 
  70                 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts + ", policyResult="
 
  71                 + policyResult + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
 
  76     // These properties are not changeable, but accessible
 
  77     // for Drools Rule statements.
 
  79     public final ControlLoopEvent onset;
 
  80     public final Policy policy;
 
  83     // Properties used to track the Operation
 
  85     private int attempts = 0;
 
  86     private Operation currentOperation = null;
 
  87     private LinkedList<Operation> operationHistory = new LinkedList<>();
 
  88     private PolicyResult policyResult = null;
 
  89     private ControlLoopEventManager eventManager = null;
 
  90     private String targetEntity;
 
  92     public ControlLoopEventManager getEventManager() {
 
  96     public void setEventManager(ControlLoopEventManager eventManager) {
 
  97         this.eventManager = eventManager;
 
 100     public String getTargetEntity() {
 
 101         return this.targetEntity;
 
 105     // Internal class used for tracking
 
 107     private class Operation implements Serializable {
 
 108         private static final long serialVersionUID = 1L;
 
 110         private ControlLoopOperation clOperation = new ControlLoopOperation();
 
 111         private PolicyResult policyResult = null;
 
 112         private int attempt = 0;
 
 115         public String toString() {
 
 116             return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + clOperation
 
 121     private String guardApprovalStatus = "NONE";// "NONE", "PERMIT", "DENY"
 
 122     private transient Object operationRequest;
 
 124     public Object getOperationRequest() {
 
 125         return operationRequest;
 
 128     public String getGuardApprovalStatus() {
 
 129         return guardApprovalStatus;
 
 132     public void setGuardApprovalStatus(String guardApprovalStatus) {
 
 133         this.guardApprovalStatus = guardApprovalStatus;
 
 137      * Get the target for a policy.
 
 139      * @param policy the policy
 
 141      * @throws ControlLoopException if an error occurs
 
 142      * @throws AaiException if an error occurs retrieving information from A&AI
 
 144     public String getTarget(Policy policy) throws ControlLoopException, AaiException {
 
 145         if (policy.getTarget() == null) {
 
 146             throw new ControlLoopException("The target is null");
 
 149         if (policy.getTarget().getType() == null) {
 
 150             throw new ControlLoopException("The target type is null");
 
 153         switch (policy.getTarget().getType()) {
 
 155                 throw new ControlLoopException("PNF target is not supported");
 
 158                 VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset;
 
 159                 if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
 
 160                     return virtualOnset.getAai().get(VSERVER_VSERVER_NAME);
 
 161                 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
 
 162                     return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
 
 163                 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
 
 165                      * If the onset is enriched with the vnf-id, we don't need an A&AI response
 
 167                     if (virtualOnset.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
 
 168                         return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
 
 172                      * If the vnf-name was retrieved from the onset then the vnf-id must be obtained
 
 173                      * from the event manager's A&AI GET query
 
 175                     String vnfId = this.eventManager.getVnfResponse().getVnfId();
 
 177                         throw new AaiException("No vnf-id found");
 
 181                 throw new ControlLoopException("Target does not match target type");
 
 183                 throw new ControlLoopException("The target type is not supported");
 
 188      * Construct an instance.
 
 190      * @param onset the onset event
 
 191      * @param policy the policy
 
 192      * @param em the event manager
 
 193      * @throws ControlLoopException if an error occurs
 
 194      * @throws AaiException if an error occurs retrieving information from A&AI
 
 196     public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em)
 
 197             throws ControlLoopException, AaiException {
 
 199         this.policy = policy;
 
 200         this.guardApprovalStatus = "NONE";
 
 201         this.eventManager = em;
 
 202         this.targetEntity = getTarget(policy);
 
 205         // Let's make a sanity check
 
 207         switch (policy.getActor()) {
 
 209                 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
 
 211                      * The target vnf-id may not be the same as the source vnf-id specified in the
 
 212                      * yaml, the target vnf-id is retrieved by a named query to A&AI.
 
 214                     String targetVnf = AppcLcmActorServiceProvider.vnfNamedQuery(policy.getTarget().getResourceID(),
 
 216                     this.targetEntity = targetVnf;
 
 226                 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
 
 231      * Start an operation.
 
 233      * @param onset the onset event
 
 234      * @return the operation request
 
 235      * @throws ControlLoopException if an error occurs
 
 237     public Object startOperation(/* VirtualControlLoopEvent */ControlLoopEvent onset) throws ControlLoopException {
 
 238         verifyOperatonCanRun();
 
 243         this.policyResult = null;
 
 244         Operation operation = new Operation();
 
 245         operation.attempt = ++this.attempts;
 
 246         operation.clOperation.setActor(this.policy.getActor());
 
 247         operation.clOperation.setOperation(this.policy.getRecipe());
 
 248         operation.clOperation.setTarget(this.policy.getTarget().toString());
 
 249         operation.clOperation.setSubRequestId(Integer.toString(operation.attempt));
 
 251         // Now determine which actor we need to construct a request for
 
 253         switch (policy.getActor()) {
 
 256                  * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an
 
 257                  * LCMRequest is constructed.
 
 259                 this.currentOperation = operation;
 
 260                 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
 
 261                     this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
 
 262                             operation.clOperation, this.policy, this.targetEntity);
 
 264                     this.operationRequest = AppcLcmActorServiceProvider.constructRequest(
 
 265                             (VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.targetEntity);
 
 268                 // Save the operation
 
 271                 return operationRequest;
 
 273                 SOActorServiceProvider soActorSp = new SOActorServiceProvider();
 
 274                 this.operationRequest = soActorSp.constructRequest((VirtualControlLoopEvent) onset,
 
 275                                 operation.clOperation, this.policy, eventManager.getNqVserverFromAai());
 
 277                 // Save the operation
 
 278                 this.currentOperation = operation;
 
 280                 if (this.operationRequest == null) {
 
 281                     this.policyResult = PolicyResult.FAILURE;
 
 284                 return operationRequest;
 
 286                 this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
 
 287                         operation.clOperation, this.policy, this.eventManager.getVnfResponse());
 
 288                 this.currentOperation = operation;
 
 289                 if (this.operationRequest == null) {
 
 290                     this.policyResult = PolicyResult.FAILURE;
 
 292                 return operationRequest;
 
 295                  * If the recipe is ModifyConfig, a SDNR request is constructed.
 
 297                 this.currentOperation = operation;
 
 298                 this.operationRequest = SdnrActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
 
 299                             operation.clOperation, this.policy);
 
 301                 // Save the operation
 
 303                 if (this.operationRequest == null) {
 
 304                     this.policyResult = PolicyResult.FAILURE;
 
 307                 return operationRequest;
 
 309                 throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy");
 
 316      * @param response the response
 
 317      * @return a PolicyResult
 
 319     public PolicyResult onResponse(Object response) {
 
 321         // Which response is it?
 
 323         if (response instanceof Response) {
 
 325             // Cast APPC response and handle it
 
 327             return onResponse((Response) response);
 
 328         } else if (response instanceof LcmResponseWrapper) {
 
 330             // Cast LCM response and handle it
 
 332             return onResponse((LcmResponseWrapper) response);
 
 333         } else if (response instanceof PciResponseWrapper) {
 
 335             // Cast SDNR response and handle it
 
 337             return onResponse((PciResponseWrapper) response);
 
 338         } else if (response instanceof SOResponseWrapper) {
 
 340             // Cast SO response and handle it
 
 342             return onResponse((SOResponseWrapper) response);
 
 343         } else if (response instanceof VFCResponse) {
 
 345             // Cast VFC response and handle it
 
 347             return onResponse((VFCResponse) response);
 
 354      * This method handles operation responses from APPC.
 
 356      * @param appcResponse the APPC response
 
 357      * @return The result of the response handling
 
 359     private PolicyResult onResponse(Response appcResponse) {
 
 361         // Determine which subrequestID (ie. attempt)
 
 363         Integer operationAttempt = null;
 
 365             operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestId());
 
 366         } catch (NumberFormatException e) {
 
 368             // We cannot tell what happened if this doesn't exist
 
 370             this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
 
 371                     PolicyResult.FAILURE_EXCEPTION);
 
 372             return PolicyResult.FAILURE_EXCEPTION;
 
 375         // Sanity check the response message
 
 377         if (appcResponse.getStatus() == null) {
 
 379             // We cannot tell what happened if this doesn't exist
 
 381             this.completeOperation(operationAttempt,
 
 382                     "Policy was unable to parse APP-C response status field (it was null).",
 
 383                     PolicyResult.FAILURE_EXCEPTION);
 
 384             return PolicyResult.FAILURE_EXCEPTION;
 
 387         // Get the Response Code
 
 389         ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode());
 
 392             // We are unaware of this code
 
 394             this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.",
 
 395                     PolicyResult.FAILURE_EXCEPTION);
 
 396             return PolicyResult.FAILURE_EXCEPTION;
 
 399         // Ok, let's figure out what APP-C's response is
 
 404                 // This is good, they got our original message and
 
 407                 // Is there any need to track this?
 
 413                 // We'll consider these two codes as exceptions
 
 415                 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
 
 416                         PolicyResult.FAILURE_EXCEPTION);
 
 417                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 420                 return PolicyResult.FAILURE_EXCEPTION;
 
 425                 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
 
 426                         PolicyResult.SUCCESS);
 
 427                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 430                 return PolicyResult.SUCCESS;
 
 435                 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
 
 436                         PolicyResult.FAILURE);
 
 437                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 440                 return PolicyResult.FAILURE;
 
 447      * This method handles operation responses from LCM.
 
 449      * @param dmaapResponse the LCM response
 
 450      * @return The result of the response handling
 
 452     private PolicyResult onResponse(LcmResponseWrapper dmaapResponse) {
 
 454          * Parse out the operation attempt using the subrequestid
 
 456         Integer operationAttempt = AppcLcmActorServiceProvider
 
 457                 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
 
 458         if (operationAttempt == null) {
 
 459             this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
 
 460                     PolicyResult.FAILURE_EXCEPTION);
 
 464          * Process the APPCLCM response to see what PolicyResult should be returned
 
 466         AbstractMap.SimpleEntry<PolicyResult, String> result =
 
 467                 AppcLcmActorServiceProvider.processResponse(dmaapResponse);
 
 469         if (result.getKey() != null) {
 
 470             this.completeOperation(operationAttempt, result.getValue(), result.getKey());
 
 471             if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
 
 474             return result.getKey();
 
 480      * This method handles operation responses from SDNR.
 
 482      * @param dmaapResponse the SDNR response
 
 483      * @return the result of the response handling
 
 485     private PolicyResult onResponse(PciResponseWrapper dmaapResponse) {
 
 487          * Parse out the operation attempt using the subrequestid
 
 489         Integer operationAttempt = SdnrActorServiceProvider
 
 490                 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
 
 491         if (operationAttempt == null) {
 
 492             this.completeOperation(operationAttempt, "Policy was unable to parse SDNR SubRequestID.",
 
 493                     PolicyResult.FAILURE_EXCEPTION);
 
 497          * Process the SDNR response to see what PolicyResult should be returned
 
 499         SdnrActorServiceProvider.Pair<PolicyResult, String> result =
 
 500                 SdnrActorServiceProvider.processResponse(dmaapResponse);
 
 502         if (result.getResult() != null) {
 
 503             this.completeOperation(operationAttempt, result.getMessage(), result.getResult());
 
 504             if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
 
 507             return result.getResult();
 
 513      * This method handles operation responses from SO.
 
 515      * @param msoResponse the SO response
 
 516      * @return The result of the response handling
 
 518     private PolicyResult onResponse(SOResponseWrapper msoResponse) {
 
 519         switch (msoResponse.getSoResponse().getHttpResponseCode()) {
 
 523                 // Consider it as success
 
 525                 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success",
 
 526                         PolicyResult.SUCCESS);
 
 527                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 530                 return PolicyResult.SUCCESS;
 
 533                 // Consider it as failure
 
 535                 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed",
 
 536                         PolicyResult.FAILURE);
 
 537                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 540                 return PolicyResult.FAILURE;
 
 545      * This method handles operation responses from VFC.
 
 547      * @param vfcResponse the VFC response
 
 548      * @return The result of the response handling
 
 550     private PolicyResult onResponse(VFCResponse vfcResponse) {
 
 551         if (vfcResponse.getResponseDescriptor().getStatus().equalsIgnoreCase("finished")) {
 
 553             // Consider it as success
 
 555             this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
 
 556             if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 559             return PolicyResult.SUCCESS;
 
 562             // Consider it as failure
 
 564             this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
 
 565             if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 568             // increment operation attempts for retries
 
 570             return PolicyResult.FAILURE;
 
 575      * Get the operation timeout.
 
 577      * @return the timeout
 
 579     public Integer getOperationTimeout() {
 
 583         if (this.policy == null) {
 
 584             logger.debug("getOperationTimeout returning 0");
 
 587         logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
 
 588         return this.policy.getTimeout();
 
 592      * Get the operation timeout as a String.
 
 594      * @param defaultTimeout the default timeout
 
 595      * @return the timeout as a String
 
 597     public String getOperationTimeoutString(int defaultTimeout) {
 
 598         Integer to = this.getOperationTimeout();
 
 599         if (to == null || to == 0) {
 
 600             return Integer.toString(defaultTimeout) + "s";
 
 602         return to.toString() + "s";
 
 605     public PolicyResult getOperationResult() {
 
 606         return this.policyResult;
 
 610      * Get the operation as a message.
 
 612      * @return the operation as a message
 
 614     public String getOperationMessage() {
 
 615         if (this.currentOperation != null && this.currentOperation.clOperation != null) {
 
 616             return this.currentOperation.clOperation.toMessage();
 
 619         if (!this.operationHistory.isEmpty()) {
 
 620             return this.operationHistory.getLast().clOperation.toMessage();
 
 626      * Get the operation as a message including the guard result.
 
 628      * @param guardResult the guard result
 
 629      * @return the operation as a message including the guard result
 
 631     public String getOperationMessage(String guardResult) {
 
 632         if (this.currentOperation != null && this.currentOperation.clOperation != null) {
 
 633             return this.currentOperation.clOperation.toMessage() + ", Guard result: " + guardResult;
 
 636         if (!this.operationHistory.isEmpty()) {
 
 637             return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " + guardResult;
 
 643      * Get the operation history.
 
 645      * @return the operation history
 
 647     public String getOperationHistory() {
 
 648         if (this.currentOperation != null && this.currentOperation.clOperation != null) {
 
 649             return this.currentOperation.clOperation.toHistory();
 
 652         if (!this.operationHistory.isEmpty()) {
 
 653             return this.operationHistory.getLast().clOperation.toHistory();
 
 661      * @return the list of control loop operations
 
 663     public List<ControlLoopOperation> getHistory() {
 
 664         LinkedList<ControlLoopOperation> history = new LinkedList<>();
 
 665         for (Operation op : this.operationHistory) {
 
 666             history.add(new ControlLoopOperation(op.clOperation));
 
 673      * Set the operation has timed out.
 
 675     public void setOperationHasTimedOut() {
 
 679         this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
 
 683      * Set the operation has been denied by guard.
 
 685     public void setOperationHasGuardDeny() {
 
 689         this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
 
 692     public void setOperationHasException(String message) {
 
 693         this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
 
 697      * Is the operation complete.
 
 699      * @return <code>true</code> if the operation is complete, <code>false</code> otherwise
 
 701     public boolean isOperationComplete() {
 
 703         // Is there currently a result?
 
 705         if (this.policyResult == null) {
 
 707             // either we are in process or we
 
 713         // We have some result, check if the operation failed
 
 715         if (this.policyResult.equals(PolicyResult.FAILURE)) {
 
 717             // Check if there were no retries specified
 
 719             if (policy.getRetry() == null || policy.getRetry() == 0) {
 
 721                 // The result is the failure
 
 728             if (this.isRetriesMaxedOut()) {
 
 730                 // No more attempts allowed, reset
 
 731                 // that our actual result is failure due to retries
 
 733                 this.policyResult = PolicyResult.FAILURE_RETRIES;
 
 737                 // There are more attempts available to try the
 
 744         // Other results mean we are done
 
 749     public boolean isOperationRunning() {
 
 750         return (this.currentOperation != null);
 
 754      * This method verifies that the operation manager may run an operation.
 
 756      * @return True if the operation can run, false otherwise
 
 757      * @throws ControlLoopException if the operation cannot run
 
 759     private void verifyOperatonCanRun() throws ControlLoopException {
 
 761         // They shouldn't call us if we currently running something
 
 763         if (this.currentOperation != null) {
 
 765             // what do we do if we are already running an operation?
 
 767             throw new ControlLoopException("current operation is not null (an operation is already running)");
 
 770         // Check if we have maxed out on retries
 
 772         if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
 
 774             // No retries are allowed, so check have we even made
 
 775             // one attempt to execute the operation?
 
 777             if (this.attempts >= 1) {
 
 779                 // We have, let's ensure our PolicyResult is set
 
 781                 if (this.policyResult == null) {
 
 782                     this.policyResult = PolicyResult.FAILURE_RETRIES;
 
 787                 throw new ControlLoopException("current operation failed and retries are not allowed");
 
 791             // Have we maxed out on retries?
 
 793             if (this.attempts > this.policy.getRetry()) {
 
 794                 if (this.policyResult == null) {
 
 795                     this.policyResult = PolicyResult.FAILURE_RETRIES;
 
 797                 throw new ControlLoopException("current oepration has failed after " + this.attempts + " retries");
 
 804     private boolean isRetriesMaxedOut() {
 
 805         if (policy.getRetry() == null || policy.getRetry() == 0) {
 
 807             // There were NO retries specified, so declare
 
 808             // this as completed.
 
 810             return (this.attempts > 0);
 
 812         return (this.attempts > policy.getRetry());
 
 815     private void storeOperationInDataBase() {
 
 816         // Only store in DB if enabled
 
 817         boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
 
 824         Properties props = new Properties();
 
 825         if (PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null
 
 826                 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null
 
 827                 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null) {
 
 828             props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
 
 829             props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
 
 830             props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
 
 831             props.put(PersistenceUnitProperties.CLASSLOADER, ControlLoopOperationManager.class.getClassLoader());
 
 835         String opsHistPu = System.getProperty("OperationsHistoryPU");
 
 836         if (opsHistPu == null || !opsHistPu.equals("TestOperationsHistoryPU")) {
 
 837             opsHistPu = "OperationsHistoryPU";
 
 843             em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager();
 
 844         } catch (Exception e) {
 
 845             logger.error("storeOperationInDataBase threw: ", e);
 
 849         OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
 
 851         newEntry.setClosedLoopName(this.onset.getClosedLoopControlName());
 
 852         newEntry.setRequestId(this.onset.getRequestId().toString());
 
 853         newEntry.setActor(this.currentOperation.clOperation.getActor());
 
 854         newEntry.setOperation(this.currentOperation.clOperation.getOperation());
 
 855         newEntry.setTarget(this.targetEntity);
 
 856         newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart()));
 
 857         newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId());
 
 858         newEntry.setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli()));
 
 859         newEntry.setMessage(this.currentOperation.clOperation.getMessage());
 
 860         newEntry.setOutcome(this.currentOperation.clOperation.getOutcome());
 
 862         em.getTransaction().begin();
 
 863         em.persist(newEntry);
 
 864         em.getTransaction().commit();
 
 869     private void completeOperation(Integer attempt, String message, PolicyResult result) {
 
 870         if (attempt == null) {
 
 871             logger.debug("attempt cannot be null (i.e. subRequestID)");
 
 874         if (this.currentOperation != null) {
 
 875             if (this.currentOperation.attempt == attempt.intValue()) {
 
 876                 this.currentOperation.clOperation.setEnd(Instant.now());
 
 877                 this.currentOperation.clOperation.setMessage(message);
 
 878                 this.currentOperation.clOperation.setOutcome(result.toString());
 
 879                 this.currentOperation.policyResult = result;
 
 881                 // Save it in history
 
 883                 this.operationHistory.add(this.currentOperation);
 
 884                 this.storeOperationInDataBase();
 
 886                 // Set our last result
 
 888                 this.policyResult = result;
 
 890                 // Clear the current operation field
 
 892                 this.currentOperation = null;
 
 895             logger.debug("not current");
 
 897         for (Operation op : this.operationHistory) {
 
 898             if (op.attempt == attempt.intValue()) {
 
 899                 op.clOperation.setEnd(Instant.now());
 
 900                 op.clOperation.setMessage(message);
 
 901                 op.clOperation.setOutcome(result.toString());
 
 902                 op.policyResult = result;
 
 906         logger.debug("Could not find associated operation");
 
 911      * Commit the abatement to the history database.
 
 913      * @param message the abatement message
 
 914      * @param outcome the abatement outcome
 
 916     public void commitAbatement(String message, String outcome) {
 
 917         logger.info("commitAbatement: " + message + ", " + outcome);
 
 919         if (this.currentOperation == null) {
 
 921                 this.currentOperation = this.operationHistory.getLast();
 
 922             } catch (NoSuchElementException e) {
 
 923                 logger.error("{}: commitAbatement threw an exception ", this, e);
 
 927         this.currentOperation.clOperation.setEnd(Instant.now());
 
 928         this.currentOperation.clOperation.setMessage(message);
 
 929         this.currentOperation.clOperation.setOutcome(outcome);
 
 931         // Store commit in DB
 
 933         this.storeOperationInDataBase();
 
 935         // Clear the current operation field
 
 937         this.currentOperation = null;