2  * ============LICENSE_START=======================================================
 
   3  * controlloop operation manager
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
 
   6  * Modifications Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved.
 
   7  * Modifications Copyright (C) 2019 Tech Mahindra
 
   8  * ================================================================================
 
   9  * Licensed under the Apache License, Version 2.0 (the "License");
 
  10  * you may not use this file except in compliance with the License.
 
  11  * You may obtain a copy of the License at
 
  13  *      http://www.apache.org/licenses/LICENSE-2.0
 
  15  * Unless required by applicable law or agreed to in writing, software
 
  16  * distributed under the License is distributed on an "AS IS" BASIS,
 
  17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  18  * See the License for the specific language governing permissions and
 
  19  * limitations under the License.
 
  20  * ============LICENSE_END=========================================================
 
  23 package org.onap.policy.controlloop.eventmanager;
 
  25 import java.io.Serializable;
 
  26 import java.sql.Timestamp;
 
  27 import java.time.Instant;
 
  28 import java.util.AbstractMap;
 
  29 import java.util.LinkedList;
 
  30 import java.util.List;
 
  31 import java.util.NoSuchElementException;
 
  32 import java.util.Properties;
 
  33 import javax.persistence.EntityManager;
 
  34 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.ControlLoopResponse;
 
  44 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 
  45 import org.onap.policy.controlloop.actor.appc.AppcActorServiceProvider;
 
  46 import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
 
  47 import org.onap.policy.controlloop.actor.sdnc.SdncActorServiceProvider;
 
  48 import org.onap.policy.controlloop.actor.sdnr.SdnrActorServiceProvider;
 
  49 import org.onap.policy.controlloop.actor.so.SoActorServiceProvider;
 
  50 import org.onap.policy.controlloop.actor.vfc.VfcActorServiceProvider;
 
  51 import org.onap.policy.controlloop.policy.Policy;
 
  52 import org.onap.policy.controlloop.policy.PolicyResult;
 
  53 import org.onap.policy.drools.system.PolicyEngine;
 
  54 import org.onap.policy.guard.Util;
 
  55 import org.onap.policy.sdnc.SdncResponse;
 
  56 import org.onap.policy.sdnr.PciResponseWrapper;
 
  57 import org.onap.policy.so.SoResponseWrapper;
 
  58 import org.onap.policy.vfc.VfcResponse;
 
  59 import org.slf4j.Logger;
 
  60 import org.slf4j.LoggerFactory;
 
  62 public class ControlLoopOperationManager implements Serializable {
 
  63     private static final long serialVersionUID = -3773199283624595410L;
 
  64     private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
 
  66     private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
 
  67     private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
 
  68     private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
 
  71     // These properties are not changeable, but accessible
 
  72     // for Drools Rule statements.
 
  74     public final ControlLoopEvent onset;
 
  75     public final Policy policy;
 
  78     // Properties used to track the Operation
 
  80     private int attempts = 0;
 
  81     private Operation currentOperation = null;
 
  82     private LinkedList<Operation> operationHistory = new LinkedList<>();
 
  83     private PolicyResult policyResult = null;
 
  84     private ControlLoopEventManager eventManager = null;
 
  85     private String targetEntity;
 
  86     private String guardApprovalStatus = "NONE";// "NONE", "PERMIT", "DENY"
 
  87     private transient Object operationRequest;
 
  90      * Construct an instance.
 
  92      * @param onset the onset event
 
  93      * @param policy the policy
 
  94      * @param em the event manager
 
  95      * @throws ControlLoopException if an error occurs
 
  96      * @throws AaiException if an error occurs retrieving information from A&AI
 
  98     public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em)
 
  99             throws ControlLoopException, AaiException {
 
 101         this.policy = policy;
 
 102         this.guardApprovalStatus = "NONE";
 
 103         this.eventManager = em;
 
 104         this.targetEntity = getTarget(policy);
 
 107         // Let's make a sanity check
 
 109         switch (policy.getActor()) {
 
 111                 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
 
 113                      * The target vnf-id may not be the same as the source vnf-id specified in the
 
 114                      * yaml, the target vnf-id is retrieved by a named query to A&AI.
 
 116                     String targetVnf = AppcLcmActorServiceProvider.vnfNamedQuery(policy.getTarget().getResourceID(),
 
 117                             this.targetEntity, PolicyEngine.manager.getEnvironmentProperty("aai.url"),
 
 118                             PolicyEngine.manager.getEnvironmentProperty("aai.username"),
 
 119                             PolicyEngine.manager.getEnvironmentProperty("aai.password"));
 
 120                     this.targetEntity = targetVnf;
 
 132                 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
 
 136     public ControlLoopEventManager getEventManager() {
 
 140     public void setEventManager(ControlLoopEventManager eventManager) {
 
 141         this.eventManager = eventManager;
 
 144     public String getTargetEntity() {
 
 145         return this.targetEntity;
 
 149     public String toString() {
 
 150         return "ControlLoopOperationManager [onset=" + (onset != null ? onset.getRequestId() : "null") + ", policy="
 
 151                 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts + ", policyResult="
 
 152                 + policyResult + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
 
 157     // Internal class used for tracking
 
 159     private class Operation implements Serializable {
 
 160         private static final long serialVersionUID = 1L;
 
 162         private ControlLoopOperation clOperation = new ControlLoopOperation();
 
 163         private PolicyResult policyResult = null;
 
 164         private int attempt = 0;
 
 167         public String toString() {
 
 168             return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + clOperation
 
 173     public Object getOperationRequest() {
 
 174         return operationRequest;
 
 177     public String getGuardApprovalStatus() {
 
 178         return guardApprovalStatus;
 
 181     public void setGuardApprovalStatus(String guardApprovalStatus) {
 
 182         this.guardApprovalStatus = guardApprovalStatus;
 
 186      * Get the target for a policy.
 
 188      * @param policy the policy
 
 190      * @throws ControlLoopException if an error occurs
 
 191      * @throws AaiException if an error occurs retrieving information from A&AI
 
 193     public String getTarget(Policy policy) throws ControlLoopException, AaiException {
 
 194         if (policy.getTarget() == null) {
 
 195             throw new ControlLoopException("The target is null");
 
 198         if (policy.getTarget().getType() == null) {
 
 199             throw new ControlLoopException("The target type is null");
 
 202         switch (policy.getTarget().getType()) {
 
 204                 throw new ControlLoopException("PNF target is not supported");
 
 207                 VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset;
 
 208                 if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
 
 209                     return virtualOnset.getAai().get(VSERVER_VSERVER_NAME);
 
 210                 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
 
 211                     return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
 
 212                 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
 
 214                      * If the onset is enriched with the vnf-id, we don't need an A&AI response
 
 216                     if (virtualOnset.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
 
 217                         return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
 
 221                      * If the vnf-name was retrieved from the onset then the vnf-id must be obtained
 
 222                      * from the event manager's A&AI GET query
 
 224                     String vnfId = this.eventManager.getVnfResponse().getVnfId();
 
 226                         throw new AaiException("No vnf-id found");
 
 230                 throw new ControlLoopException("Target does not match target type");
 
 232                 VirtualControlLoopEvent virtualOnsetEvent = (VirtualControlLoopEvent) this.onset;
 
 233                 if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
 
 234                     return virtualOnsetEvent.getAai().get(VSERVER_VSERVER_NAME);
 
 235                 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
 
 236                     return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID);
 
 237                 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
 
 239                      * If the onset is enriched with the vnf-id, we don't need an A&AI response
 
 241                     if (virtualOnsetEvent.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
 
 242                         return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID);
 
 246                      * If the vnf-name was retrieved from the onset then the vnf-id must be obtained
 
 247                      * from the event manager's A&AI GET query
 
 249                     String vnfId = this.eventManager.getVnfResponse().getVnfId();
 
 251                         throw new AaiException("No vnf-id found");
 
 255                 throw new ControlLoopException("Target does not match target type");
 
 257                 throw new ControlLoopException("The target type is not supported");
 
 262      * Start an operation.
 
 264      * @param onset the onset event
 
 265      * @return the operation request
 
 266      * @throws ControlLoopException if an error occurs
 
 268     public Object startOperation(/* VirtualControlLoopEvent */ControlLoopEvent onset) throws ControlLoopException {
 
 269         verifyOperatonCanRun();
 
 274         this.policyResult = null;
 
 275         Operation operation = new Operation();
 
 276         operation.attempt = ++this.attempts;
 
 277         operation.clOperation.setActor(this.policy.getActor());
 
 278         operation.clOperation.setOperation(this.policy.getRecipe());
 
 279         operation.clOperation.setTarget(this.policy.getTarget().toString());
 
 280         operation.clOperation.setSubRequestId(Integer.toString(operation.attempt));
 
 282         // Now determine which actor we need to construct a request for
 
 284         switch (policy.getActor()) {
 
 287                  * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an
 
 288                  * LCMRequest is constructed.
 
 290                 this.currentOperation = operation;
 
 291                 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
 
 292                     this.operationRequest = AppcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
 
 293                             operation.clOperation, this.policy, this.targetEntity);
 
 295                     this.operationRequest = AppcLcmActorServiceProvider.constructRequest(
 
 296                             (VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.targetEntity);
 
 299                 // Save the operation
 
 302                 return operationRequest;
 
 304                 SoActorServiceProvider soActorSp = new SoActorServiceProvider();
 
 305                 this.operationRequest = soActorSp.constructRequest((VirtualControlLoopEvent) onset,
 
 306                                 operation.clOperation, this.policy, eventManager.getNqVserverFromAai());
 
 308                 // Save the operation
 
 309                 this.currentOperation = operation;
 
 311                 if (this.operationRequest == null) {
 
 312                     this.policyResult = PolicyResult.FAILURE;
 
 315                 return operationRequest;
 
 317                 this.operationRequest = VfcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
 
 318                         operation.clOperation, this.policy, this.eventManager.getVnfResponse(),
 
 319                         PolicyEngine.manager.getEnvironmentProperty("vfc.url"),
 
 320                         PolicyEngine.manager.getEnvironmentProperty("vfc.username"),
 
 321                         PolicyEngine.manager.getEnvironmentProperty("vfc.password"));
 
 322                 this.currentOperation = operation;
 
 323                 if (this.operationRequest == null) {
 
 324                     this.policyResult = PolicyResult.FAILURE;
 
 326                 return operationRequest;
 
 329                  * If the recipe is ModifyConfig or ModifyConfigANR, a SDNR request is constructed.
 
 331                 this.currentOperation = operation;
 
 332                 this.operationRequest = SdnrActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
 
 333                             operation.clOperation, this.policy);
 
 335                 // Save the operation
 
 337                 if (this.operationRequest == null) {
 
 338                     this.policyResult = PolicyResult.FAILURE;
 
 341                 return operationRequest;
 
 343                 SdncActorServiceProvider provider = new SdncActorServiceProvider();
 
 344                 this.operationRequest = provider.constructRequest((VirtualControlLoopEvent) onset,
 
 345                         operation.clOperation, this.policy);
 
 346                 this.currentOperation = operation;
 
 347                 if (this.operationRequest == null) {
 
 348                     this.policyResult = PolicyResult.FAILURE;
 
 350                 return operationRequest;
 
 352                 throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy");
 
 359      * @param response the response
 
 360      * @return a PolicyResult
 
 362     public PolicyResult onResponse(Object response) {
 
 364         // Which response is it?
 
 366         if (response instanceof Response) {
 
 368             // Cast APPC response and handle it
 
 370             return onResponse((Response) response);
 
 371         } else if (response instanceof LcmResponseWrapper) {
 
 373             // Cast LCM response and handle it
 
 375             return onResponse((LcmResponseWrapper) response);
 
 376         } else if (response instanceof PciResponseWrapper) {
 
 378             // Cast SDNR response and handle it
 
 380             return onResponse((PciResponseWrapper) response);
 
 381         } else if (response instanceof SoResponseWrapper) {
 
 383             // Cast SO response and handle it
 
 385             return onResponse((SoResponseWrapper) response);
 
 386         } else if (response instanceof VfcResponse) {
 
 388             // Cast VFC response and handle it
 
 390             return onResponse((VfcResponse) response);
 
 391         } else if (response instanceof SdncResponse) {
 
 393             // Cast SDNC response and handle it
 
 395             return onResponse((SdncResponse) response);
 
 402      * This method handles operation responses from APPC.
 
 404      * @param appcResponse the APPC response
 
 405      * @return The result of the response handling
 
 407     private PolicyResult onResponse(Response appcResponse) {
 
 409         // Determine which subrequestID (ie. attempt)
 
 411         Integer operationAttempt = null;
 
 413             operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestId());
 
 414         } catch (NumberFormatException e) {
 
 416             // We cannot tell what happened if this doesn't exist
 
 418             this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
 
 419                     PolicyResult.FAILURE_EXCEPTION);
 
 420             return PolicyResult.FAILURE_EXCEPTION;
 
 423         // Sanity check the response message
 
 425         if (appcResponse.getStatus() == null) {
 
 427             // We cannot tell what happened if this doesn't exist
 
 429             this.completeOperation(operationAttempt,
 
 430                     "Policy was unable to parse APP-C response status field (it was null).",
 
 431                     PolicyResult.FAILURE_EXCEPTION);
 
 432             return PolicyResult.FAILURE_EXCEPTION;
 
 435         // Get the Response Code
 
 437         ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode());
 
 440             // We are unaware of this code
 
 442             this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.",
 
 443                     PolicyResult.FAILURE_EXCEPTION);
 
 444             return PolicyResult.FAILURE_EXCEPTION;
 
 447         // Ok, let's figure out what APP-C's response is
 
 452                 // This is good, they got our original message and
 
 455                 // Is there any need to track this?
 
 461                 // We'll consider these two codes as exceptions
 
 463                 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
 
 464                         PolicyResult.FAILURE_EXCEPTION);
 
 465                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 468                 return PolicyResult.FAILURE_EXCEPTION;
 
 473                 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
 
 474                         PolicyResult.SUCCESS);
 
 475                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 478                 return PolicyResult.SUCCESS;
 
 483                 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
 
 484                         PolicyResult.FAILURE);
 
 485                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 488                 return PolicyResult.FAILURE;
 
 495      * This method handles operation responses from LCM.
 
 497      * @param dmaapResponse the LCM response
 
 498      * @return The result of the response handling
 
 500     private PolicyResult onResponse(LcmResponseWrapper dmaapResponse) {
 
 502          * Parse out the operation attempt using the subrequestid
 
 504         Integer operationAttempt = AppcLcmActorServiceProvider
 
 505                 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
 
 506         if (operationAttempt == null) {
 
 507             this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
 
 508                     PolicyResult.FAILURE_EXCEPTION);
 
 512          * Process the APPCLCM response to see what PolicyResult should be returned
 
 514         AbstractMap.SimpleEntry<PolicyResult, String> result =
 
 515                 AppcLcmActorServiceProvider.processResponse(dmaapResponse);
 
 517         if (result.getKey() != null) {
 
 518             this.completeOperation(operationAttempt, result.getValue(), result.getKey());
 
 519             if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
 
 522             return result.getKey();
 
 528      * This method handles operation responses from SDNR.
 
 530      * @param dmaapResponse the SDNR response
 
 531      * @return the result of the response handling
 
 533     private PolicyResult onResponse(PciResponseWrapper dmaapResponse) {
 
 535          * Parse out the operation attempt using the subrequestid
 
 537         Integer operationAttempt = SdnrActorServiceProvider
 
 538                 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
 
 539         if (operationAttempt == null) {
 
 540             this.completeOperation(operationAttempt, "Policy was unable to parse SDNR SubRequestID.",
 
 541                     PolicyResult.FAILURE_EXCEPTION);
 
 545          * Process the SDNR response to see what PolicyResult should be returned
 
 547         SdnrActorServiceProvider.Pair<PolicyResult, String> result =
 
 548                 SdnrActorServiceProvider.processResponse(dmaapResponse);
 
 550         if (result.getResult() != null) {
 
 551             this.completeOperation(operationAttempt, result.getMessage(), result.getResult());
 
 552             if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
 
 555             return result.getResult();
 
 561      * This method handles operation responses from SO.
 
 563      * @param msoResponse the SO response
 
 564      * @return The result of the response handling
 
 566     private PolicyResult onResponse(SoResponseWrapper msoResponse) {
 
 567         switch (msoResponse.getSoResponse().getHttpResponseCode()) {
 
 571                 // Consider it as success
 
 573                 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success",
 
 574                         PolicyResult.SUCCESS);
 
 575                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 578                 return PolicyResult.SUCCESS;
 
 581                 // Consider it as failure
 
 583                 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed",
 
 584                         PolicyResult.FAILURE);
 
 585                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 588                 return PolicyResult.FAILURE;
 
 593      * This method handles operation responses from VFC.
 
 595      * @param vfcResponse the VFC response
 
 596      * @return The result of the response handling
 
 598     private PolicyResult onResponse(VfcResponse vfcResponse) {
 
 599         if ("finished".equalsIgnoreCase(vfcResponse.getResponseDescriptor().getStatus())) {
 
 601             // Consider it as success
 
 603             this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
 
 604             if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 607             return PolicyResult.SUCCESS;
 
 610             // Consider it as failure
 
 612             this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
 
 613             if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 616             // increment operation attempts for retries
 
 618             return PolicyResult.FAILURE;
 
 623      * This method handles operation responses from SDNC.
 
 625      * @param sdncResponse the VFC response
 
 626      * @return The result of the response handling
 
 628     private PolicyResult onResponse(SdncResponse sdncResponse) {
 
 629         if ("200".equals(sdncResponse.getResponseOutput().getResponseCode())) {
 
 631             // Consider it as success
 
 633             this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
 
 634             if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 637             return PolicyResult.SUCCESS;
 
 640             // Consider it as failure
 
 642             this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
 
 643             if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
 
 646             // increment operation attempts for retries
 
 648             return PolicyResult.FAILURE;
 
 653      * Get the operation timeout.
 
 655      * @return the timeout
 
 657     public Integer getOperationTimeout() {
 
 661         if (this.policy == null) {
 
 662             logger.debug("getOperationTimeout returning 0");
 
 665         logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
 
 666         return this.policy.getTimeout();
 
 670      * Get the operation timeout as a String.
 
 672      * @param defaultTimeout the default timeout
 
 673      * @return the timeout as a String
 
 675     public String getOperationTimeoutString(int defaultTimeout) {
 
 676         Integer to = this.getOperationTimeout();
 
 677         if (to == null || to == 0) {
 
 678             return Integer.toString(defaultTimeout) + "s";
 
 680         return to.toString() + "s";
 
 683     public PolicyResult getOperationResult() {
 
 684         return this.policyResult;
 
 688      * Get the operation as a message.
 
 690      * @return the operation as a message
 
 692     public String getOperationMessage() {
 
 693         if (this.currentOperation != null && this.currentOperation.clOperation != null) {
 
 694             return this.currentOperation.clOperation.toMessage();
 
 697         if (!this.operationHistory.isEmpty()) {
 
 698             return this.operationHistory.getLast().clOperation.toMessage();
 
 704      * Get the operation as a message including the guard result.
 
 706      * @param guardResult the guard result
 
 707      * @return the operation as a message including the guard result
 
 709     public String getOperationMessage(String guardResult) {
 
 710         if (this.currentOperation != null && this.currentOperation.clOperation != null) {
 
 711             return this.currentOperation.clOperation.toMessage() + ", Guard result: " + guardResult;
 
 714         if (!this.operationHistory.isEmpty()) {
 
 715             return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " + guardResult;
 
 721      * Get the operation history.
 
 723      * @return the operation history
 
 725     public String getOperationHistory() {
 
 726         if (this.currentOperation != null && this.currentOperation.clOperation != null) {
 
 727             return this.currentOperation.clOperation.toHistory();
 
 730         if (!this.operationHistory.isEmpty()) {
 
 731             return this.operationHistory.getLast().clOperation.toHistory();
 
 739      * @return the list of control loop operations
 
 741     public List<ControlLoopOperation> getHistory() {
 
 742         LinkedList<ControlLoopOperation> history = new LinkedList<>();
 
 743         for (Operation op : this.operationHistory) {
 
 744             history.add(new ControlLoopOperation(op.clOperation));
 
 751      * Set the operation has timed out.
 
 753     public void setOperationHasTimedOut() {
 
 757         this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
 
 761      * Set the operation has been denied by guard.
 
 763     public void setOperationHasGuardDeny() {
 
 767         this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
 
 770     public void setOperationHasException(String message) {
 
 771         this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
 
 775      * Is the operation complete.
 
 777      * @return <code>true</code> if the operation is complete, <code>false</code> otherwise
 
 779     public boolean isOperationComplete() {
 
 781         // Is there currently a result?
 
 783         if (this.policyResult == null) {
 
 785             // either we are in process or we
 
 791         // We have some result, check if the operation failed
 
 793         if (this.policyResult.equals(PolicyResult.FAILURE)) {
 
 795             // Check if there were no retries specified
 
 797             if (policy.getRetry() == null || policy.getRetry() == 0) {
 
 799                 // The result is the failure
 
 806             if (this.isRetriesMaxedOut()) {
 
 808                 // No more attempts allowed, reset
 
 809                 // that our actual result is failure due to retries
 
 811                 this.policyResult = PolicyResult.FAILURE_RETRIES;
 
 815                 // There are more attempts available to try the
 
 822         // Other results mean we are done
 
 827     public boolean isOperationRunning() {
 
 828         return (this.currentOperation != null);
 
 832      * This method verifies that the operation manager may run an operation.
 
 834      * @return True if the operation can run, false otherwise
 
 835      * @throws ControlLoopException if the operation cannot run
 
 837     private void verifyOperatonCanRun() throws ControlLoopException {
 
 839         // They shouldn't call us if we currently running something
 
 841         if (this.currentOperation != null) {
 
 843             // what do we do if we are already running an operation?
 
 845             throw new ControlLoopException("current operation is not null (an operation is already running)");
 
 848         // Check if we have maxed out on retries
 
 850         if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
 
 852             // No retries are allowed, so check have we even made
 
 853             // one attempt to execute the operation?
 
 855             if (this.attempts >= 1) {
 
 857                 // We have, let's ensure our PolicyResult is set
 
 859                 if (this.policyResult == null) {
 
 860                     this.policyResult = PolicyResult.FAILURE_RETRIES;
 
 865                 throw new ControlLoopException("current operation failed and retries are not allowed");
 
 869             // Have we maxed out on retries?
 
 871             if (this.attempts > this.policy.getRetry()) {
 
 872                 if (this.policyResult == null) {
 
 873                     this.policyResult = PolicyResult.FAILURE_RETRIES;
 
 875                 throw new ControlLoopException("current oepration has failed after " + this.attempts + " retries");
 
 880     private boolean isRetriesMaxedOut() {
 
 881         if (policy.getRetry() == null || policy.getRetry() == 0) {
 
 883             // There were NO retries specified, so declare
 
 884             // this as completed.
 
 886             return (this.attempts > 0);
 
 888         return (this.attempts > policy.getRetry());
 
 891     private void storeOperationInDataBase() {
 
 892         // Only store in DB if enabled
 
 893         boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
 
 900         Properties props = new Properties();
 
 901         if (PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null
 
 902                 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null
 
 903                 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null) {
 
 904             props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
 
 905             props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
 
 906             props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
 
 907             props.put(PersistenceUnitProperties.CLASSLOADER, ControlLoopOperationManager.class.getClassLoader());
 
 911         String opsHistPu = System.getProperty("OperationsHistoryPU");
 
 912         if (!"TestOperationsHistoryPU".equals(opsHistPu)) {
 
 913             opsHistPu = "OperationsHistoryPU";
 
 919             em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager();
 
 920         } catch (Exception e) {
 
 921             logger.error("storeOperationInDataBase threw: ", e);
 
 925         OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
 
 927         newEntry.setClosedLoopName(this.onset.getClosedLoopControlName());
 
 928         newEntry.setRequestId(this.onset.getRequestId().toString());
 
 929         newEntry.setActor(this.currentOperation.clOperation.getActor());
 
 930         newEntry.setOperation(this.currentOperation.clOperation.getOperation());
 
 931         newEntry.setTarget(this.targetEntity);
 
 932         newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart()));
 
 933         newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId());
 
 934         newEntry.setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli()));
 
 935         newEntry.setMessage(this.currentOperation.clOperation.getMessage());
 
 936         newEntry.setOutcome(this.currentOperation.clOperation.getOutcome());
 
 938         em.getTransaction().begin();
 
 939         em.persist(newEntry);
 
 940         em.getTransaction().commit();
 
 945     private void completeOperation(Integer attempt, String message, PolicyResult result) {
 
 946         if (attempt == null) {
 
 947             logger.debug("attempt cannot be null (i.e. subRequestID)");
 
 950         if (this.currentOperation != null) {
 
 951             if (this.currentOperation.attempt == attempt.intValue()) {
 
 952                 this.currentOperation.clOperation.setEnd(Instant.now());
 
 953                 this.currentOperation.clOperation.setMessage(message);
 
 954                 this.currentOperation.clOperation.setOutcome(result.toString());
 
 955                 this.currentOperation.policyResult = result;
 
 957                 // Save it in history
 
 959                 this.operationHistory.add(this.currentOperation);
 
 960                 this.storeOperationInDataBase();
 
 962                 // Set our last result
 
 964                 this.policyResult = result;
 
 966                 // Clear the current operation field
 
 968                 this.currentOperation = null;
 
 971             logger.debug("not current");
 
 973         for (Operation op : this.operationHistory) {
 
 974             if (op.attempt == attempt.intValue()) {
 
 975                 op.clOperation.setEnd(Instant.now());
 
 976                 op.clOperation.setMessage(message);
 
 977                 op.clOperation.setOutcome(result.toString());
 
 978                 op.policyResult = result;
 
 982         logger.debug("Could not find associated operation");
 
 987      * Commit the abatement to the history database.
 
 989      * @param message the abatement message
 
 990      * @param outcome the abatement outcome
 
 992     public void commitAbatement(String message, String outcome) {
 
 993         logger.info("commitAbatement: {}. {}", message, outcome);
 
 995         if (this.currentOperation == null) {
 
 997                 this.currentOperation = this.operationHistory.getLast();
 
 998             } catch (NoSuchElementException e) {
 
 999                 logger.error("{}: commitAbatement threw an exception ", this, e);
 
1003         this.currentOperation.clOperation.setEnd(Instant.now());
 
1004         this.currentOperation.clOperation.setMessage(message);
 
1005         this.currentOperation.clOperation.setOutcome(outcome);
 
1007         // Store commit in DB
 
1009         this.storeOperationInDataBase();
 
1011         // Clear the current operation field
 
1013         this.currentOperation = null;
 
1017      * Construct a ControlLoopResponse object from actor response and input event.
 
1019      * @param response the response from actor
 
1020      * @param event the input event
 
1022      * @return a ControlLoopResponse
 
1024     public ControlLoopResponse getControlLoopResponse(Object response, VirtualControlLoopEvent event) {
 
1025         if (response instanceof PciResponseWrapper) {
 
1027             // Cast SDNR response and handle it
 
1029             return SdnrActorServiceProvider.getControlLoopResponse((PciResponseWrapper) response, event);