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.sdnc.SdncActorServiceProvider;
47 import org.onap.policy.controlloop.actor.sdnr.SdnrActorServiceProvider;
48 import org.onap.policy.controlloop.actor.so.SoActorServiceProvider;
49 import org.onap.policy.controlloop.actor.vfc.VfcActorServiceProvider;
50 import org.onap.policy.controlloop.policy.Policy;
51 import org.onap.policy.controlloop.policy.PolicyResult;
52 import org.onap.policy.drools.system.PolicyEngine;
53 import org.onap.policy.guard.Util;
54 import org.onap.policy.sdnc.SdncResponse;
55 import org.onap.policy.sdnr.PciResponseWrapper;
56 import org.onap.policy.so.SOResponseWrapper;
57 import org.onap.policy.vfc.VFCResponse;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 public class ControlLoopOperationManager implements Serializable {
62 private static final long serialVersionUID = -3773199283624595410L;
63 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
65 private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
66 private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
67 private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
70 // These properties are not changeable, but accessible
71 // for Drools Rule statements.
73 public final ControlLoopEvent onset;
74 public final Policy policy;
77 // Properties used to track the Operation
79 private int attempts = 0;
80 private Operation currentOperation = null;
81 private LinkedList<Operation> operationHistory = new LinkedList<>();
82 private PolicyResult policyResult = null;
83 private ControlLoopEventManager eventManager = null;
84 private String targetEntity;
85 private String guardApprovalStatus = "NONE";// "NONE", "PERMIT", "DENY"
86 private transient Object operationRequest;
89 * Construct an instance.
91 * @param onset the onset event
92 * @param policy the policy
93 * @param em the event manager
94 * @throws ControlLoopException if an error occurs
95 * @throws AaiException if an error occurs retrieving information from A&AI
97 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em)
98 throws ControlLoopException, AaiException {
100 this.policy = policy;
101 this.guardApprovalStatus = "NONE";
102 this.eventManager = em;
103 this.targetEntity = getTarget(policy);
106 // Let's make a sanity check
108 switch (policy.getActor()) {
110 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
112 * The target vnf-id may not be the same as the source vnf-id specified in the
113 * yaml, the target vnf-id is retrieved by a named query to A&AI.
115 String targetVnf = AppcLcmActorServiceProvider.vnfNamedQuery(policy.getTarget().getResourceID(),
117 this.targetEntity = targetVnf;
129 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
133 public ControlLoopEventManager getEventManager() {
137 public void setEventManager(ControlLoopEventManager eventManager) {
138 this.eventManager = eventManager;
141 public String getTargetEntity() {
142 return this.targetEntity;
146 public String toString() {
147 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.getRequestId() : "null") + ", policy="
148 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts + ", policyResult="
149 + policyResult + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
154 // Internal class used for tracking
156 private class Operation implements Serializable {
157 private static final long serialVersionUID = 1L;
159 private ControlLoopOperation clOperation = new ControlLoopOperation();
160 private PolicyResult policyResult = null;
161 private int attempt = 0;
164 public String toString() {
165 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + clOperation
170 public Object getOperationRequest() {
171 return operationRequest;
174 public String getGuardApprovalStatus() {
175 return guardApprovalStatus;
178 public void setGuardApprovalStatus(String guardApprovalStatus) {
179 this.guardApprovalStatus = guardApprovalStatus;
183 * Get the target for a policy.
185 * @param policy the policy
187 * @throws ControlLoopException if an error occurs
188 * @throws AaiException if an error occurs retrieving information from A&AI
190 public String getTarget(Policy policy) throws ControlLoopException, AaiException {
191 if (policy.getTarget() == null) {
192 throw new ControlLoopException("The target is null");
195 if (policy.getTarget().getType() == null) {
196 throw new ControlLoopException("The target type is null");
199 switch (policy.getTarget().getType()) {
201 throw new ControlLoopException("PNF target is not supported");
204 VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset;
205 if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
206 return virtualOnset.getAai().get(VSERVER_VSERVER_NAME);
207 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
208 return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
209 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
211 * If the onset is enriched with the vnf-id, we don't need an A&AI response
213 if (virtualOnset.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
214 return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
218 * If the vnf-name was retrieved from the onset then the vnf-id must be obtained
219 * from the event manager's A&AI GET query
221 String vnfId = this.eventManager.getVnfResponse().getVnfId();
223 throw new AaiException("No vnf-id found");
227 throw new ControlLoopException("Target does not match target type");
229 throw new ControlLoopException("The target type is not supported");
234 * Start an operation.
236 * @param onset the onset event
237 * @return the operation request
238 * @throws ControlLoopException if an error occurs
240 public Object startOperation(/* VirtualControlLoopEvent */ControlLoopEvent onset) throws ControlLoopException {
241 verifyOperatonCanRun();
246 this.policyResult = null;
247 Operation operation = new Operation();
248 operation.attempt = ++this.attempts;
249 operation.clOperation.setActor(this.policy.getActor());
250 operation.clOperation.setOperation(this.policy.getRecipe());
251 operation.clOperation.setTarget(this.policy.getTarget().toString());
252 operation.clOperation.setSubRequestId(Integer.toString(operation.attempt));
254 // Now determine which actor we need to construct a request for
256 switch (policy.getActor()) {
259 * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an
260 * LCMRequest is constructed.
262 this.currentOperation = operation;
263 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
264 this.operationRequest = AppcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
265 operation.clOperation, this.policy, this.targetEntity);
267 this.operationRequest = AppcLcmActorServiceProvider.constructRequest(
268 (VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.targetEntity);
271 // Save the operation
274 return operationRequest;
276 SoActorServiceProvider soActorSp = new SoActorServiceProvider();
277 this.operationRequest = soActorSp.constructRequest((VirtualControlLoopEvent) onset,
278 operation.clOperation, this.policy, eventManager.getNqVserverFromAai());
280 // Save the operation
281 this.currentOperation = operation;
283 if (this.operationRequest == null) {
284 this.policyResult = PolicyResult.FAILURE;
287 return operationRequest;
289 this.operationRequest = VfcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
290 operation.clOperation, this.policy, this.eventManager.getVnfResponse());
291 this.currentOperation = operation;
292 if (this.operationRequest == null) {
293 this.policyResult = PolicyResult.FAILURE;
295 return operationRequest;
298 * If the recipe is ModifyConfig, a SDNR request is constructed.
300 this.currentOperation = operation;
301 this.operationRequest = SdnrActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
302 operation.clOperation, this.policy);
304 // Save the operation
306 if (this.operationRequest == null) {
307 this.policyResult = PolicyResult.FAILURE;
310 return operationRequest;
312 this.operationRequest = SdncActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
313 operation.clOperation, this.policy);
314 this.currentOperation = operation;
315 if (this.operationRequest == null) {
316 this.policyResult = PolicyResult.FAILURE;
318 return operationRequest;
320 throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy");
327 * @param response the response
328 * @return a PolicyResult
330 public PolicyResult onResponse(Object response) {
332 // Which response is it?
334 if (response instanceof Response) {
336 // Cast APPC response and handle it
338 return onResponse((Response) response);
339 } else if (response instanceof LcmResponseWrapper) {
341 // Cast LCM response and handle it
343 return onResponse((LcmResponseWrapper) response);
344 } else if (response instanceof PciResponseWrapper) {
346 // Cast SDNR response and handle it
348 return onResponse((PciResponseWrapper) response);
349 } else if (response instanceof SOResponseWrapper) {
351 // Cast SO response and handle it
353 return onResponse((SOResponseWrapper) response);
354 } else if (response instanceof VFCResponse) {
356 // Cast VFC response and handle it
358 return onResponse((VFCResponse) response);
365 * This method handles operation responses from APPC.
367 * @param appcResponse the APPC response
368 * @return The result of the response handling
370 private PolicyResult onResponse(Response appcResponse) {
372 // Determine which subrequestID (ie. attempt)
374 Integer operationAttempt = null;
376 operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestId());
377 } catch (NumberFormatException e) {
379 // We cannot tell what happened if this doesn't exist
381 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
382 PolicyResult.FAILURE_EXCEPTION);
383 return PolicyResult.FAILURE_EXCEPTION;
386 // Sanity check the response message
388 if (appcResponse.getStatus() == null) {
390 // We cannot tell what happened if this doesn't exist
392 this.completeOperation(operationAttempt,
393 "Policy was unable to parse APP-C response status field (it was null).",
394 PolicyResult.FAILURE_EXCEPTION);
395 return PolicyResult.FAILURE_EXCEPTION;
398 // Get the Response Code
400 ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode());
403 // We are unaware of this code
405 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.",
406 PolicyResult.FAILURE_EXCEPTION);
407 return PolicyResult.FAILURE_EXCEPTION;
410 // Ok, let's figure out what APP-C's response is
415 // This is good, they got our original message and
418 // Is there any need to track this?
424 // We'll consider these two codes as exceptions
426 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
427 PolicyResult.FAILURE_EXCEPTION);
428 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
431 return PolicyResult.FAILURE_EXCEPTION;
436 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
437 PolicyResult.SUCCESS);
438 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
441 return PolicyResult.SUCCESS;
446 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
447 PolicyResult.FAILURE);
448 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
451 return PolicyResult.FAILURE;
458 * This method handles operation responses from LCM.
460 * @param dmaapResponse the LCM response
461 * @return The result of the response handling
463 private PolicyResult onResponse(LcmResponseWrapper dmaapResponse) {
465 * Parse out the operation attempt using the subrequestid
467 Integer operationAttempt = AppcLcmActorServiceProvider
468 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
469 if (operationAttempt == null) {
470 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
471 PolicyResult.FAILURE_EXCEPTION);
475 * Process the APPCLCM response to see what PolicyResult should be returned
477 AbstractMap.SimpleEntry<PolicyResult, String> result =
478 AppcLcmActorServiceProvider.processResponse(dmaapResponse);
480 if (result.getKey() != null) {
481 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
482 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
485 return result.getKey();
491 * This method handles operation responses from SDNR.
493 * @param dmaapResponse the SDNR response
494 * @return the result of the response handling
496 private PolicyResult onResponse(PciResponseWrapper dmaapResponse) {
498 * Parse out the operation attempt using the subrequestid
500 Integer operationAttempt = SdnrActorServiceProvider
501 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
502 if (operationAttempt == null) {
503 this.completeOperation(operationAttempt, "Policy was unable to parse SDNR SubRequestID.",
504 PolicyResult.FAILURE_EXCEPTION);
508 * Process the SDNR response to see what PolicyResult should be returned
510 SdnrActorServiceProvider.Pair<PolicyResult, String> result =
511 SdnrActorServiceProvider.processResponse(dmaapResponse);
513 if (result.getResult() != null) {
514 this.completeOperation(operationAttempt, result.getMessage(), result.getResult());
515 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
518 return result.getResult();
524 * This method handles operation responses from SO.
526 * @param msoResponse the SO response
527 * @return The result of the response handling
529 private PolicyResult onResponse(SOResponseWrapper msoResponse) {
530 switch (msoResponse.getSoResponse().getHttpResponseCode()) {
534 // Consider it as success
536 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success",
537 PolicyResult.SUCCESS);
538 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
541 return PolicyResult.SUCCESS;
544 // Consider it as failure
546 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed",
547 PolicyResult.FAILURE);
548 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
551 return PolicyResult.FAILURE;
556 * This method handles operation responses from VFC.
558 * @param vfcResponse the VFC response
559 * @return The result of the response handling
561 private PolicyResult onResponse(VFCResponse vfcResponse) {
562 if ("finished".equalsIgnoreCase(vfcResponse.getResponseDescriptor().getStatus())) {
564 // Consider it as success
566 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
567 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
570 return PolicyResult.SUCCESS;
573 // Consider it as failure
575 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
576 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
579 // increment operation attempts for retries
581 return PolicyResult.FAILURE;
586 * Get the operation timeout.
588 * @return the timeout
590 public Integer getOperationTimeout() {
594 if (this.policy == null) {
595 logger.debug("getOperationTimeout returning 0");
598 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
599 return this.policy.getTimeout();
603 * Get the operation timeout as a String.
605 * @param defaultTimeout the default timeout
606 * @return the timeout as a String
608 public String getOperationTimeoutString(int defaultTimeout) {
609 Integer to = this.getOperationTimeout();
610 if (to == null || to == 0) {
611 return Integer.toString(defaultTimeout) + "s";
613 return to.toString() + "s";
616 public PolicyResult getOperationResult() {
617 return this.policyResult;
621 * Get the operation as a message.
623 * @return the operation as a message
625 public String getOperationMessage() {
626 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
627 return this.currentOperation.clOperation.toMessage();
630 if (!this.operationHistory.isEmpty()) {
631 return this.operationHistory.getLast().clOperation.toMessage();
637 * Get the operation as a message including the guard result.
639 * @param guardResult the guard result
640 * @return the operation as a message including the guard result
642 public String getOperationMessage(String guardResult) {
643 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
644 return this.currentOperation.clOperation.toMessage() + ", Guard result: " + guardResult;
647 if (!this.operationHistory.isEmpty()) {
648 return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " + guardResult;
654 * Get the operation history.
656 * @return the operation history
658 public String getOperationHistory() {
659 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
660 return this.currentOperation.clOperation.toHistory();
663 if (!this.operationHistory.isEmpty()) {
664 return this.operationHistory.getLast().clOperation.toHistory();
672 * @return the list of control loop operations
674 public List<ControlLoopOperation> getHistory() {
675 LinkedList<ControlLoopOperation> history = new LinkedList<>();
676 for (Operation op : this.operationHistory) {
677 history.add(new ControlLoopOperation(op.clOperation));
684 * Set the operation has timed out.
686 public void setOperationHasTimedOut() {
690 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
694 * Set the operation has been denied by guard.
696 public void setOperationHasGuardDeny() {
700 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
703 public void setOperationHasException(String message) {
704 this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
708 * Is the operation complete.
710 * @return <code>true</code> if the operation is complete, <code>false</code> otherwise
712 public boolean isOperationComplete() {
714 // Is there currently a result?
716 if (this.policyResult == null) {
718 // either we are in process or we
724 // We have some result, check if the operation failed
726 if (this.policyResult.equals(PolicyResult.FAILURE)) {
728 // Check if there were no retries specified
730 if (policy.getRetry() == null || policy.getRetry() == 0) {
732 // The result is the failure
739 if (this.isRetriesMaxedOut()) {
741 // No more attempts allowed, reset
742 // that our actual result is failure due to retries
744 this.policyResult = PolicyResult.FAILURE_RETRIES;
748 // There are more attempts available to try the
755 // Other results mean we are done
760 public boolean isOperationRunning() {
761 return (this.currentOperation != null);
765 * This method verifies that the operation manager may run an operation.
767 * @return True if the operation can run, false otherwise
768 * @throws ControlLoopException if the operation cannot run
770 private void verifyOperatonCanRun() throws ControlLoopException {
772 // They shouldn't call us if we currently running something
774 if (this.currentOperation != null) {
776 // what do we do if we are already running an operation?
778 throw new ControlLoopException("current operation is not null (an operation is already running)");
781 // Check if we have maxed out on retries
783 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
785 // No retries are allowed, so check have we even made
786 // one attempt to execute the operation?
788 if (this.attempts >= 1) {
790 // We have, let's ensure our PolicyResult is set
792 if (this.policyResult == null) {
793 this.policyResult = PolicyResult.FAILURE_RETRIES;
798 throw new ControlLoopException("current operation failed and retries are not allowed");
802 // Have we maxed out on retries?
804 if (this.attempts > this.policy.getRetry()) {
805 if (this.policyResult == null) {
806 this.policyResult = PolicyResult.FAILURE_RETRIES;
808 throw new ControlLoopException("current oepration has failed after " + this.attempts + " retries");
813 private boolean isRetriesMaxedOut() {
814 if (policy.getRetry() == null || policy.getRetry() == 0) {
816 // There were NO retries specified, so declare
817 // this as completed.
819 return (this.attempts > 0);
821 return (this.attempts > policy.getRetry());
824 private void storeOperationInDataBase() {
825 // Only store in DB if enabled
826 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
833 Properties props = new Properties();
834 if (PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null
835 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null
836 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null) {
837 props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
838 props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
839 props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
840 props.put(PersistenceUnitProperties.CLASSLOADER, ControlLoopOperationManager.class.getClassLoader());
844 String opsHistPu = System.getProperty("OperationsHistoryPU");
845 if (!"TestOperationsHistoryPU".equals(opsHistPu)) {
846 opsHistPu = "OperationsHistoryPU";
852 em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager();
853 } catch (Exception e) {
854 logger.error("storeOperationInDataBase threw: ", e);
858 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
860 newEntry.setClosedLoopName(this.onset.getClosedLoopControlName());
861 newEntry.setRequestId(this.onset.getRequestId().toString());
862 newEntry.setActor(this.currentOperation.clOperation.getActor());
863 newEntry.setOperation(this.currentOperation.clOperation.getOperation());
864 newEntry.setTarget(this.targetEntity);
865 newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart()));
866 newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId());
867 newEntry.setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli()));
868 newEntry.setMessage(this.currentOperation.clOperation.getMessage());
869 newEntry.setOutcome(this.currentOperation.clOperation.getOutcome());
871 em.getTransaction().begin();
872 em.persist(newEntry);
873 em.getTransaction().commit();
878 private void completeOperation(Integer attempt, String message, PolicyResult result) {
879 if (attempt == null) {
880 logger.debug("attempt cannot be null (i.e. subRequestID)");
883 if (this.currentOperation != null) {
884 if (this.currentOperation.attempt == attempt.intValue()) {
885 this.currentOperation.clOperation.setEnd(Instant.now());
886 this.currentOperation.clOperation.setMessage(message);
887 this.currentOperation.clOperation.setOutcome(result.toString());
888 this.currentOperation.policyResult = result;
890 // Save it in history
892 this.operationHistory.add(this.currentOperation);
893 this.storeOperationInDataBase();
895 // Set our last result
897 this.policyResult = result;
899 // Clear the current operation field
901 this.currentOperation = null;
904 logger.debug("not current");
906 for (Operation op : this.operationHistory) {
907 if (op.attempt == attempt.intValue()) {
908 op.clOperation.setEnd(Instant.now());
909 op.clOperation.setMessage(message);
910 op.clOperation.setOutcome(result.toString());
911 op.policyResult = result;
915 logger.debug("Could not find associated operation");
920 * Commit the abatement to the history database.
922 * @param message the abatement message
923 * @param outcome the abatement outcome
925 public void commitAbatement(String message, String outcome) {
926 logger.info("commitAbatement: {}. {}", message, outcome);
928 if (this.currentOperation == null) {
930 this.currentOperation = this.operationHistory.getLast();
931 } catch (NoSuchElementException e) {
932 logger.error("{}: commitAbatement threw an exception ", this, e);
936 this.currentOperation.clOperation.setEnd(Instant.now());
937 this.currentOperation.clOperation.setMessage(message);
938 this.currentOperation.clOperation.setOutcome(outcome);
940 // Store commit in DB
942 this.storeOperationInDataBase();
944 // Clear the current operation field
946 this.currentOperation = null;