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.aai.domain.yang.GenericVnf;
37 import org.onap.policy.aai.util.AaiException;
38 import org.onap.policy.appc.Response;
39 import org.onap.policy.appc.ResponseCode;
40 import org.onap.policy.appclcm.LcmResponseWrapper;
41 import org.onap.policy.controlloop.ControlLoopEvent;
42 import org.onap.policy.controlloop.ControlLoopException;
43 import org.onap.policy.controlloop.ControlLoopOperation;
44 import org.onap.policy.controlloop.ControlLoopResponse;
45 import org.onap.policy.controlloop.VirtualControlLoopEvent;
46 import org.onap.policy.controlloop.actor.appc.AppcActorServiceProvider;
47 import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
48 import org.onap.policy.controlloop.actor.sdnc.SdncActorServiceProvider;
49 import org.onap.policy.controlloop.actor.sdnr.SdnrActorServiceProvider;
50 import org.onap.policy.controlloop.actor.so.SoActorServiceProvider;
51 import org.onap.policy.controlloop.actor.vfc.VfcActorServiceProvider;
52 import org.onap.policy.controlloop.policy.Policy;
53 import org.onap.policy.controlloop.policy.PolicyResult;
54 import org.onap.policy.database.operationshistory.Dbao;
55 import org.onap.policy.drools.system.PolicyEngine;
56 import org.onap.policy.guard.Util;
57 import org.onap.policy.sdnc.SdncResponse;
58 import org.onap.policy.sdnr.PciResponseWrapper;
59 import org.onap.policy.so.SoResponseWrapper;
60 import org.onap.policy.vfc.VfcResponse;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 public class ControlLoopOperationManager implements Serializable {
65 private static final long serialVersionUID = -3773199283624595410L;
66 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
68 private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
69 private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
70 private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
73 // These properties are not changeable, but accessible
74 // for Drools Rule statements.
76 public final ControlLoopEvent onset;
77 public final Policy policy;
80 // Properties used to track the Operation
82 private int attempts = 0;
83 private Operation currentOperation = null;
84 private LinkedList<Operation> operationHistory = new LinkedList<>();
85 private PolicyResult policyResult = null;
86 private ControlLoopEventManager eventManager = null;
87 private String targetEntity;
88 private String guardApprovalStatus = "NONE";// "NONE", "PERMIT", "DENY"
89 private transient Object operationRequest;
92 * Construct an instance.
94 * @param onset the onset event
95 * @param policy the policy
96 * @param em the event manager
97 * @throws ControlLoopException if an error occurs
98 * @throws AaiException if an error occurs retrieving information from A&AI
100 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em)
101 throws ControlLoopException, AaiException {
103 this.policy = policy;
104 this.guardApprovalStatus = "NONE";
105 this.eventManager = em;
106 this.targetEntity = getTarget(policy);
109 // Let's make a sanity check
111 switch (policy.getActor()) {
113 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
115 * The target vnf-id may not be the same as the source vnf-id specified in the yaml, the target
116 * vnf-id is retrieved by a named query to A&AI.
118 if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
119 GenericVnf genvnf = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset)
120 .getGenericVnfByModelInvariantId(policy.getTarget().getResourceID());
121 if (genvnf == null) {
122 logger.info("Target entity could not be found");
123 throw new AaiException("Target vnf-id could not be found");
125 this.targetEntity = genvnf.getVnfId();
129 AppcLcmActorServiceProvider.vnfNamedQuery(policy.getTarget().getResourceID(),
130 this.targetEntity, PolicyEngine.manager.getEnvironmentProperty("aai.url"),
131 PolicyEngine.manager.getEnvironmentProperty("aai.username"),
132 PolicyEngine.manager.getEnvironmentProperty("aai.password"));
145 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
150 public ControlLoopEventManager getEventManager() {
154 public void setEventManager(ControlLoopEventManager eventManager) {
155 this.eventManager = eventManager;
158 public String getTargetEntity() {
159 return this.targetEntity;
163 public String toString() {
164 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.getRequestId() : "null") + ", policy="
165 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts + ", policyResult="
166 + policyResult + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
171 // Internal class used for tracking
173 private class Operation implements Serializable {
174 private static final long serialVersionUID = 1L;
176 private ControlLoopOperation clOperation = new ControlLoopOperation();
177 private PolicyResult policyResult = null;
178 private int attempt = 0;
181 public String toString() {
182 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + clOperation
187 public Object getOperationRequest() {
188 return operationRequest;
191 public String getGuardApprovalStatus() {
192 return guardApprovalStatus;
195 public void setGuardApprovalStatus(String guardApprovalStatus) {
196 this.guardApprovalStatus = guardApprovalStatus;
200 * Get the target for a policy.
202 * @param policy the policy
204 * @throws ControlLoopException if an error occurs
205 * @throws AaiException if an error occurs retrieving information from A&AI
207 public String getTarget(Policy policy) throws ControlLoopException, AaiException {
208 if (policy.getTarget() == null) {
209 throw new ControlLoopException("The target is null");
212 if (policy.getTarget().getType() == null) {
213 throw new ControlLoopException("The target type is null");
216 switch (policy.getTarget().getType()) {
218 throw new ControlLoopException("PNF target is not supported");
221 VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset;
222 if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
223 return virtualOnset.getAai().get(VSERVER_VSERVER_NAME);
224 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
225 return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
226 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
228 * If the onset is enriched with the vnf-id, we don't need an A&AI response
230 if (virtualOnset.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
231 return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
235 * If the vnf-name was retrieved from the onset then the vnf-id must be obtained from the event
236 * manager's A&AI GET query
239 if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
240 vnfId = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset).getDefaultGenericVnf()
243 vnfId = this.eventManager.getVnfResponse().getVnfId();
246 throw new AaiException("No vnf-id found");
250 throw new ControlLoopException("Target does not match target type");
252 VirtualControlLoopEvent virtualOnsetEvent = (VirtualControlLoopEvent) this.onset;
253 if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
254 return virtualOnsetEvent.getAai().get(VSERVER_VSERVER_NAME);
255 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
256 return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID);
257 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
259 * If the onset is enriched with the vnf-id, we don't need an A&AI response
261 if (virtualOnsetEvent.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
262 return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID);
266 * If the vnf-name was retrieved from the onset then the vnf-id must be obtained from the event
267 * manager's A&AI GET query
270 if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
271 vnfId = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset).getDefaultGenericVnf()
274 vnfId = this.eventManager.getVnfResponse().getVnfId();
277 throw new AaiException("No vnf-id found");
281 throw new ControlLoopException("Target does not match target type");
283 throw new ControlLoopException("The target type is not supported");
288 * Start an operation.
290 * @param onset the onset event
291 * @return the operation request
292 * @throws ControlLoopException if an error occurs
293 * @throws AaiException if error occurs
295 public Object startOperation(/* VirtualControlLoopEvent */ControlLoopEvent onset)
296 throws ControlLoopException, AaiException {
297 verifyOperatonCanRun();
302 this.policyResult = null;
303 Operation operation = new Operation();
304 operation.attempt = ++this.attempts;
305 operation.clOperation.setActor(this.policy.getActor());
306 operation.clOperation.setOperation(this.policy.getRecipe());
307 operation.clOperation.setTarget(this.policy.getTarget().toString());
308 operation.clOperation.setSubRequestId(Integer.toString(operation.attempt));
310 // Now determine which actor we need to construct a request for
312 switch (policy.getActor()) {
315 * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an LCMRequest is
318 this.currentOperation = operation;
319 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
320 this.operationRequest = AppcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
321 operation.clOperation, this.policy, this.targetEntity);
323 this.operationRequest = AppcLcmActorServiceProvider.constructRequest(
324 (VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.targetEntity);
327 // Save the operation
330 return operationRequest;
332 SoActorServiceProvider soActorSp = new SoActorServiceProvider();
333 if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
334 this.operationRequest =
335 soActorSp.constructRequestCq((VirtualControlLoopEvent) onset, operation.clOperation,
336 this.policy, eventManager.getCqResponse((VirtualControlLoopEvent) onset));
338 this.operationRequest = soActorSp.constructRequest((VirtualControlLoopEvent) onset,
339 operation.clOperation, this.policy, eventManager.getNqVserverFromAai());
342 // Save the operation
343 this.currentOperation = operation;
345 if (this.operationRequest == null) {
346 this.policyResult = PolicyResult.FAILURE;
349 return operationRequest;
351 if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
352 this.operationRequest = VfcActorServiceProvider.constructRequestCq((VirtualControlLoopEvent) onset,
353 operation.clOperation, this.policy,
354 eventManager.getCqResponse((VirtualControlLoopEvent) onset));
356 this.operationRequest = VfcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
357 operation.clOperation, this.policy, this.eventManager.getVnfResponse(),
358 PolicyEngine.manager.getEnvironmentProperty("vfc.url"),
359 PolicyEngine.manager.getEnvironmentProperty("vfc.username"),
360 PolicyEngine.manager.getEnvironmentProperty("vfc.password"));
362 this.currentOperation = operation;
363 if (this.operationRequest == null) {
364 this.policyResult = PolicyResult.FAILURE;
366 return operationRequest;
369 * If the recipe is ModifyConfig or ModifyConfigANR, a SDNR request is constructed.
371 this.currentOperation = operation;
372 this.operationRequest = SdnrActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
373 operation.clOperation, this.policy);
375 // Save the operation
377 if (this.operationRequest == null) {
378 this.policyResult = PolicyResult.FAILURE;
381 return operationRequest;
383 SdncActorServiceProvider provider = new SdncActorServiceProvider();
384 this.operationRequest =
385 provider.constructRequest((VirtualControlLoopEvent) onset, operation.clOperation, this.policy);
386 this.currentOperation = operation;
387 if (this.operationRequest == null) {
388 this.policyResult = PolicyResult.FAILURE;
390 return operationRequest;
392 throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy");
399 * @param response the response
400 * @return a PolicyResult
402 public PolicyResult onResponse(Object response) {
404 // Which response is it?
406 if (response instanceof Response) {
408 // Cast APPC response and handle it
410 return onResponse((Response) response);
411 } else if (response instanceof LcmResponseWrapper) {
413 // Cast LCM response and handle it
415 return onResponse((LcmResponseWrapper) response);
416 } else if (response instanceof PciResponseWrapper) {
418 // Cast SDNR response and handle it
420 return onResponse((PciResponseWrapper) response);
421 } else if (response instanceof SoResponseWrapper) {
423 // Cast SO response and handle it
425 return onResponse((SoResponseWrapper) response);
426 } else if (response instanceof VfcResponse) {
428 // Cast VFC response and handle it
430 return onResponse((VfcResponse) response);
431 } else if (response instanceof SdncResponse) {
433 // Cast SDNC response and handle it
435 return onResponse((SdncResponse) response);
442 * This method handles operation responses from APPC.
444 * @param appcResponse the APPC response
445 * @return The result of the response handling
447 private PolicyResult onResponse(Response appcResponse) {
449 // Determine which subrequestID (ie. attempt)
451 Integer operationAttempt = null;
453 operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestId());
454 } catch (NumberFormatException e) {
456 // We cannot tell what happened if this doesn't exist
458 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
459 PolicyResult.FAILURE_EXCEPTION);
460 return PolicyResult.FAILURE_EXCEPTION;
463 // Sanity check the response message
465 if (appcResponse.getStatus() == null) {
467 // We cannot tell what happened if this doesn't exist
469 this.completeOperation(operationAttempt,
470 "Policy was unable to parse APP-C response status field (it was null).",
471 PolicyResult.FAILURE_EXCEPTION);
472 return PolicyResult.FAILURE_EXCEPTION;
475 // Get the Response Code
477 ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode());
480 // We are unaware of this code
482 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.",
483 PolicyResult.FAILURE_EXCEPTION);
484 return PolicyResult.FAILURE_EXCEPTION;
487 // Ok, let's figure out what APP-C's response is
492 // This is good, they got our original message and
495 // Is there any need to track this?
501 // We'll consider these two codes as exceptions
503 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
504 PolicyResult.FAILURE_EXCEPTION);
505 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
508 return PolicyResult.FAILURE_EXCEPTION;
513 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
514 PolicyResult.SUCCESS);
515 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
518 return PolicyResult.SUCCESS;
523 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
524 PolicyResult.FAILURE);
525 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
528 return PolicyResult.FAILURE;
535 * This method handles operation responses from LCM.
537 * @param dmaapResponse the LCM response
538 * @return The result of the response handling
540 private PolicyResult onResponse(LcmResponseWrapper dmaapResponse) {
542 * Parse out the operation attempt using the subrequestid
544 Integer operationAttempt = AppcLcmActorServiceProvider
545 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
546 if (operationAttempt == null) {
547 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
548 PolicyResult.FAILURE_EXCEPTION);
552 * Process the APPCLCM response to see what PolicyResult should be returned
554 AbstractMap.SimpleEntry<PolicyResult, String> result =
555 AppcLcmActorServiceProvider.processResponse(dmaapResponse);
557 if (result.getKey() != null) {
558 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
559 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
562 return result.getKey();
568 * This method handles operation responses from SDNR.
570 * @param dmaapResponse the SDNR response
571 * @return the result of the response handling
573 private PolicyResult onResponse(PciResponseWrapper dmaapResponse) {
575 * Parse out the operation attempt using the subrequestid
577 Integer operationAttempt = SdnrActorServiceProvider
578 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
579 if (operationAttempt == null) {
580 this.completeOperation(operationAttempt, "Policy was unable to parse SDNR SubRequestID.",
581 PolicyResult.FAILURE_EXCEPTION);
585 * Process the SDNR response to see what PolicyResult should be returned
587 SdnrActorServiceProvider.Pair<PolicyResult, String> result =
588 SdnrActorServiceProvider.processResponse(dmaapResponse);
590 if (result.getResult() != null) {
591 this.completeOperation(operationAttempt, result.getMessage(), result.getResult());
592 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
595 return result.getResult();
601 * This method handles operation responses from SO.
603 * @param msoResponse the SO response
604 * @return The result of the response handling
606 private PolicyResult onResponse(SoResponseWrapper msoResponse) {
607 switch (msoResponse.getSoResponse().getHttpResponseCode()) {
611 // Consider it as success
613 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success",
614 PolicyResult.SUCCESS);
615 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
618 return PolicyResult.SUCCESS;
621 // Consider it as failure
623 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed",
624 PolicyResult.FAILURE);
625 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
628 return PolicyResult.FAILURE;
633 * This method handles operation responses from VFC.
635 * @param vfcResponse the VFC response
636 * @return The result of the response handling
638 private PolicyResult onResponse(VfcResponse vfcResponse) {
639 if ("finished".equalsIgnoreCase(vfcResponse.getResponseDescriptor().getStatus())) {
641 // Consider it as success
643 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
644 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
647 return PolicyResult.SUCCESS;
650 // Consider it as failure
652 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
653 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
656 // increment operation attempts for retries
658 return PolicyResult.FAILURE;
663 * This method handles operation responses from SDNC.
665 * @param sdncResponse the VFC response
666 * @return The result of the response handling
668 private PolicyResult onResponse(SdncResponse sdncResponse) {
669 if ("200".equals(sdncResponse.getResponseOutput().getResponseCode())) {
671 // Consider it as success
673 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
674 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
677 return PolicyResult.SUCCESS;
680 // Consider it as failure
682 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
683 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
686 // increment operation attempts for retries
688 return PolicyResult.FAILURE;
693 * Get the operation timeout.
695 * @return the timeout
697 public Integer getOperationTimeout() {
701 if (this.policy == null) {
702 logger.debug("getOperationTimeout returning 0");
705 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
706 return this.policy.getTimeout();
710 * Get the operation timeout as a String.
712 * @param defaultTimeout the default timeout
713 * @return the timeout as a String
715 public String getOperationTimeoutString(int defaultTimeout) {
716 Integer to = this.getOperationTimeout();
717 if (to == null || to == 0) {
718 return Integer.toString(defaultTimeout) + "s";
720 return to.toString() + "s";
723 public PolicyResult getOperationResult() {
724 return this.policyResult;
728 * Get the operation as a message.
730 * @return the operation as a message
732 public String getOperationMessage() {
733 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
734 return this.currentOperation.clOperation.toMessage();
737 if (!this.operationHistory.isEmpty()) {
738 return this.operationHistory.getLast().clOperation.toMessage();
744 * Get the operation as a message including the guard result.
746 * @param guardResult the guard result
747 * @return the operation as a message including the guard result
749 public String getOperationMessage(String guardResult) {
750 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
751 return this.currentOperation.clOperation.toMessage() + ", Guard result: " + guardResult;
754 if (!this.operationHistory.isEmpty()) {
755 return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " + guardResult;
761 * Get the operation history.
763 * @return the operation history
765 public String getOperationHistory() {
766 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
767 return this.currentOperation.clOperation.toHistory();
770 if (!this.operationHistory.isEmpty()) {
771 return this.operationHistory.getLast().clOperation.toHistory();
779 * @return the list of control loop operations
781 public List<ControlLoopOperation> getHistory() {
782 LinkedList<ControlLoopOperation> history = new LinkedList<>();
783 for (Operation op : this.operationHistory) {
784 history.add(new ControlLoopOperation(op.clOperation));
791 * Set the operation has timed out.
793 public void setOperationHasTimedOut() {
797 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
801 * Set the operation has been denied by guard.
803 public void setOperationHasGuardDeny() {
807 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
810 public void setOperationHasException(String message) {
811 this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
815 * Is the operation complete.
817 * @return <code>true</code> if the operation is complete, <code>false</code> otherwise
819 public boolean isOperationComplete() {
821 // Is there currently a result?
823 if (this.policyResult == null) {
825 // either we are in process or we
831 // We have some result, check if the operation failed
833 if (this.policyResult.equals(PolicyResult.FAILURE)) {
835 // Check if there were no retries specified
837 if (policy.getRetry() == null || policy.getRetry() == 0) {
839 // The result is the failure
846 if (this.isRetriesMaxedOut()) {
848 // No more attempts allowed, reset
849 // that our actual result is failure due to retries
851 this.policyResult = PolicyResult.FAILURE_RETRIES;
855 // There are more attempts available to try the
862 // Other results mean we are done
867 public boolean isOperationRunning() {
868 return (this.currentOperation != null);
872 * This method verifies that the operation manager may run an operation.
874 * @return True if the operation can run, false otherwise
875 * @throws ControlLoopException if the operation cannot run
877 private void verifyOperatonCanRun() throws ControlLoopException {
879 // They shouldn't call us if we currently running something
881 if (this.currentOperation != null) {
883 // what do we do if we are already running an operation?
885 throw new ControlLoopException("current operation is not null (an operation is already running)");
888 // Check if we have maxed out on retries
890 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
892 // No retries are allowed, so check have we even made
893 // one attempt to execute the operation?
895 if (this.attempts >= 1) {
897 // We have, let's ensure our PolicyResult is set
899 if (this.policyResult == null) {
900 this.policyResult = PolicyResult.FAILURE_RETRIES;
905 throw new ControlLoopException("current operation failed and retries are not allowed");
909 // Have we maxed out on retries?
911 if (this.attempts > this.policy.getRetry()) {
912 if (this.policyResult == null) {
913 this.policyResult = PolicyResult.FAILURE_RETRIES;
915 throw new ControlLoopException("current oepration has failed after " + this.attempts + " retries");
920 private boolean isRetriesMaxedOut() {
921 if (policy.getRetry() == null || policy.getRetry() == 0) {
923 // There were NO retries specified, so declare
924 // this as completed.
926 return (this.attempts > 0);
928 return (this.attempts > policy.getRetry());
931 private void storeOperationInDataBase() {
932 // Only store in DB if enabled
933 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
940 Properties props = new Properties();
941 if (PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null
942 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null
943 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null) {
944 props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
945 props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
946 props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
947 props.put(PersistenceUnitProperties.CLASSLOADER, ControlLoopOperationManager.class.getClassLoader());
951 String opsHistPu = System.getProperty("OperationsHistoryPU");
952 if (!"OperationsHistoryPUTest".equals(opsHistPu)) {
953 opsHistPu = "OperationsHistoryPU";
959 em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager();
960 } catch (Exception e) {
961 logger.error("storeOperationInDataBase threw: ", e);
965 Dbao newEntry = new Dbao();
967 newEntry.setClosedLoopName(this.onset.getClosedLoopControlName());
968 newEntry.setRequestId(this.onset.getRequestId().toString());
969 newEntry.setActor(this.currentOperation.clOperation.getActor());
970 newEntry.setOperation(this.currentOperation.clOperation.getOperation());
971 newEntry.setTarget(this.targetEntity);
972 newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart()));
973 newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId());
974 newEntry.setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli()));
975 newEntry.setMessage(this.currentOperation.clOperation.getMessage());
976 newEntry.setOutcome(this.currentOperation.clOperation.getOutcome());
978 em.getTransaction().begin();
979 em.persist(newEntry);
980 em.getTransaction().commit();
985 private void completeOperation(Integer attempt, String message, PolicyResult result) {
986 if (attempt == null) {
987 logger.debug("attempt cannot be null (i.e. subRequestID)");
990 if (this.currentOperation != null) {
991 if (this.currentOperation.attempt == attempt.intValue()) {
992 this.currentOperation.clOperation.setEnd(Instant.now());
993 this.currentOperation.clOperation.setMessage(message);
994 this.currentOperation.clOperation.setOutcome(result.toString());
995 this.currentOperation.policyResult = result;
997 // Save it in history
999 this.operationHistory.add(this.currentOperation);
1000 this.storeOperationInDataBase();
1002 // Set our last result
1004 this.policyResult = result;
1006 // Clear the current operation field
1008 this.currentOperation = null;
1011 logger.debug("not current");
1013 for (Operation op : this.operationHistory) {
1014 if (op.attempt == attempt.intValue()) {
1015 op.clOperation.setEnd(Instant.now());
1016 op.clOperation.setMessage(message);
1017 op.clOperation.setOutcome(result.toString());
1018 op.policyResult = result;
1022 logger.debug("Could not find associated operation");
1027 * Commit the abatement to the history database.
1029 * @param message the abatement message
1030 * @param outcome the abatement outcome
1032 public void commitAbatement(String message, String outcome) {
1033 logger.info("commitAbatement: {}. {}", message, outcome);
1035 if (this.currentOperation == null) {
1037 this.currentOperation = this.operationHistory.getLast();
1038 } catch (NoSuchElementException e) {
1039 logger.error("{}: commitAbatement threw an exception ", this, e);
1043 this.currentOperation.clOperation.setEnd(Instant.now());
1044 this.currentOperation.clOperation.setMessage(message);
1045 this.currentOperation.clOperation.setOutcome(outcome);
1047 // Store commit in DB
1049 this.storeOperationInDataBase();
1051 // Clear the current operation field
1053 this.currentOperation = null;
1057 * Construct a ControlLoopResponse object from actor response and input event.
1059 * @param response the response from actor
1060 * @param event the input event
1062 * @return a ControlLoopResponse
1064 public ControlLoopResponse getControlLoopResponse(Object response, VirtualControlLoopEvent event) {
1065 if (response instanceof PciResponseWrapper) {
1067 // Cast SDNR response and handle it
1069 return SdnrActorServiceProvider.getControlLoopResponse((PciResponseWrapper) response, event);