2 * ============LICENSE_START=======================================================
3 * controlloop operation manager
4 * ================================================================================
5 * Copyright (C) 2017-2020 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 * Modifications Copyright (C) 2019 Bell Canada.
9 * ================================================================================
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.controlloop.eventmanager;
26 import java.io.Serializable;
27 import java.sql.Timestamp;
28 import java.time.Instant;
29 import java.util.AbstractMap;
30 import java.util.HashMap;
31 import java.util.LinkedList;
32 import java.util.List;
34 import java.util.NoSuchElementException;
35 import java.util.Optional;
36 import java.util.Properties;
37 import javax.persistence.EntityManager;
38 import javax.persistence.Persistence;
39 import org.apache.commons.lang3.tuple.Pair;
40 import org.eclipse.persistence.config.PersistenceUnitProperties;
41 import org.onap.aai.domain.yang.GenericVnf;
42 import org.onap.aai.domain.yang.ServiceInstance;
43 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
44 import org.onap.policy.aai.AaiCqResponse;
45 import org.onap.policy.aai.util.AaiException;
46 import org.onap.policy.appc.Response;
47 import org.onap.policy.appc.ResponseCode;
48 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
49 import org.onap.policy.cds.CdsResponse;
50 import org.onap.policy.controlloop.ControlLoopEvent;
51 import org.onap.policy.controlloop.ControlLoopException;
52 import org.onap.policy.controlloop.ControlLoopOperation;
53 import org.onap.policy.controlloop.ControlLoopResponse;
54 import org.onap.policy.controlloop.VirtualControlLoopEvent;
55 import org.onap.policy.controlloop.actor.appc.AppcActorServiceProvider;
56 import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
57 import org.onap.policy.controlloop.actor.cds.CdsActorServiceProvider;
58 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
59 import org.onap.policy.controlloop.actor.sdnc.SdncActorServiceProvider;
60 import org.onap.policy.controlloop.actor.sdnr.SdnrActorServiceProvider;
61 import org.onap.policy.controlloop.actor.so.SoActorServiceProvider;
62 import org.onap.policy.controlloop.actor.vfc.VfcActorServiceProvider;
63 import org.onap.policy.controlloop.policy.Policy;
64 import org.onap.policy.controlloop.policy.PolicyResult;
65 import org.onap.policy.controlloop.policy.TargetType;
66 import org.onap.policy.drools.system.PolicyEngineConstants;
67 import org.onap.policy.guard.OperationsHistory;
68 import org.onap.policy.guard.Util;
69 import org.onap.policy.sdnc.SdncResponse;
70 import org.onap.policy.sdnr.PciResponseWrapper;
71 import org.onap.policy.so.SoResponseWrapper;
72 import org.onap.policy.vfc.VfcResponse;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
76 public class ControlLoopOperationManager implements Serializable {
77 private static final String SUCCESS_MSG = " Success";
78 private static final String FAILED_MSG = " Failed";
79 private static final long serialVersionUID = -3773199283624595410L;
80 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
82 private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
83 private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
84 private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
86 private static final String AAI_SERVICE_INSTANCE_ID_KEY = "service-instance.service-instance-id";
87 private static final String PNF_NAME = "pnf.pnf-name";
90 // These properties are not changeable, but accessible
91 // for Drools Rule statements.
93 public final ControlLoopEvent onset;
94 public final Policy policy;
97 // Properties used to track the Operation
99 private int attempts = 0;
100 private Operation currentOperation = null;
101 private LinkedList<Operation> operationHistory = new LinkedList<>();
102 private PolicyResult policyResult = null;
103 private ControlLoopEventManager eventManager = null;
104 private String targetEntity;
105 private String guardApprovalStatus = "NONE"; // "NONE", "PERMIT", "DENY"
106 private AaiCqResponse aaiCqResponse;
107 private transient Object operationRequest;
110 * Construct an instance.
112 * @param onset the onset event
113 * @param policy the policy
114 * @param em the event manager
115 * @throws ControlLoopException if an error occurs
117 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy,
118 ControlLoopEventManager em) throws ControlLoopException {
121 this.policy = policy;
122 this.guardApprovalStatus = "NONE";
123 this.eventManager = em;
126 if (TargetType.VNF.equals(policy.getTarget().getType())
127 || TargetType.VFMODULE.equals(policy.getTarget().getType())) {
129 this.eventManager.getCqResponse((VirtualControlLoopEvent) onset);
132 this.targetEntity = getTarget(policy);
136 } catch (AaiException e) {
137 throw new ControlLoopException(e.getMessage(), e);
141 private void initActor(Policy policy) throws AaiException, ControlLoopException {
143 // Let's make a sanity check
145 switch (policy.getActor()) {
160 throw new ControlLoopException(
161 "ControlLoopEventManager: policy has an unknown actor.");
165 private void initAppc(Policy policy) throws AaiException {
166 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
168 * The target vnf-id may not be the same as the source vnf-id specified in the yaml, the
170 * vnf-id is retrieved by a named query to A&AI.
172 GenericVnf genvnf = this.aaiCqResponse
173 .getGenericVnfByModelInvariantId(policy.getTarget().getResourceID());
174 if (genvnf == null) {
175 logger.info("Target entity could not be found");
176 throw new AaiException("Target vnf-id could not be found");
178 this.targetEntity = genvnf.getVnfId();
183 public ControlLoopEventManager getEventManager() {
187 public void setEventManager(ControlLoopEventManager eventManager) {
188 this.eventManager = eventManager;
191 public String getTargetEntity() {
192 return this.targetEntity;
196 public String toString() {
197 return "ControlLoopOperationManager [onset="
198 + (onset != null ? onset.getRequestId() : "null") + ", policy="
199 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
200 + ", policyResult=" + policyResult + ", currentOperation=" + currentOperation
201 + ", operationHistory=" + operationHistory + "]";
205 // Internal class used for tracking
207 private class Operation implements Serializable {
208 private static final long serialVersionUID = 1L;
210 private ControlLoopOperation clOperation = new ControlLoopOperation();
211 private PolicyResult policyResult = null;
212 private int attempt = 0;
215 public String toString() {
216 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult
217 + ", operation=" + clOperation + "]";
221 public Object getOperationRequest() {
222 return operationRequest;
225 public String getGuardApprovalStatus() {
226 return guardApprovalStatus;
229 public void setGuardApprovalStatus(String guardApprovalStatus) {
230 this.guardApprovalStatus = guardApprovalStatus;
234 * Get the target for a policy.
236 * @param policy the policy
238 * @throws ControlLoopException if an error occurs
240 public String getTarget(Policy policy) throws ControlLoopException {
241 if (policy.getTarget() == null) {
242 throw new ControlLoopException("The target is null");
245 if (policy.getTarget().getType() == null) {
246 throw new ControlLoopException("The target type is null");
249 switch (policy.getTarget().getType()) {
251 return getPnfTarget();
254 return getVfModuleTarget();
256 return getVfModuleTarget();
258 throw new ControlLoopException("The target type is not supported");
262 private String getVfModuleTarget() throws ControlLoopException {
263 VirtualControlLoopEvent virtualOnsetEvent = (VirtualControlLoopEvent) this.onset;
264 if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
265 return virtualOnsetEvent.getAai().get(VSERVER_VSERVER_NAME);
266 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
267 return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID);
268 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
270 * If the onset is enriched with the vnf-id, we don't need an A&AI response
272 if (virtualOnsetEvent.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
273 return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID);
277 * If the vnf-name was retrieved from the onset then the vnf-id must be obtained from
279 * manager's A&AI GET query
282 String vnfId = this.aaiCqResponse.getDefaultGenericVnf().getVnfId();
284 throw new AaiException("No vnf-id found");
288 } catch (AaiException e) {
289 throw new ControlLoopException(e.getMessage(), e);
292 throw new ControlLoopException("Target does not match target type");
295 private String getPnfTarget() throws ControlLoopException {
296 VirtualControlLoopEvent virtualOnsetEvent = (VirtualControlLoopEvent) this.onset;
297 if (!PNF_NAME.equalsIgnoreCase(onset.getTarget())) {
298 throw new ControlLoopException(
299 "Target in the onset event is either null or does not match target key expected in AAI section.");
301 return virtualOnsetEvent.getAai().get(PNF_NAME);
305 * Start an operation.
307 * @param onset the onset event
308 * @return the operation request
309 * @throws ControlLoopException if an error occurs
311 public Object startOperation(/* VirtualControlLoopEvent */ControlLoopEvent onset)
312 throws ControlLoopException {
313 verifyOperatonCanRun();
318 this.policyResult = null;
319 Operation operation = new Operation();
320 operation.attempt = ++this.attempts;
321 operation.clOperation.setActor(this.policy.getActor());
322 operation.clOperation.setOperation(this.policy.getRecipe());
323 operation.clOperation.setTarget(this.policy.getTarget().toString());
324 operation.clOperation.setSubRequestId(Integer.toString(operation.attempt));
326 // Now determine which actor we need to construct a request for
329 switch (policy.getActor()) {
331 return startAppcOperation(onset, operation);
333 return startSoOperation(onset, operation);
335 return startVfcOperation(onset, operation);
337 return startSdnrOperation(onset, operation);
339 return startSdncOperation(onset, operation);
341 return startCdsOperation(onset, operation);
343 throw new ControlLoopException(
344 "invalid actor " + policy.getActor() + " on policy");
347 } catch (AaiException e) {
348 throw new ControlLoopException(e.getMessage(), e);
352 private Object startAppcOperation(ControlLoopEvent onset, Operation operation) {
354 * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an
358 this.currentOperation = operation;
359 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
360 this.operationRequest =
361 AppcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
362 operation.clOperation, this.policy, this.targetEntity);
364 this.operationRequest =
365 AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
366 operation.clOperation, this.policy, this.targetEntity);
369 // Save the operation
372 return operationRequest;
375 private Object startSoOperation(ControlLoopEvent onset, Operation operation) {
376 SoActorServiceProvider soActorSp = new SoActorServiceProvider();
377 this.operationRequest = soActorSp.constructRequestCq((VirtualControlLoopEvent) onset,
378 operation.clOperation, this.policy, this.aaiCqResponse);
380 // Save the operation
381 this.currentOperation = operation;
383 if (this.operationRequest == null) {
384 this.policyResult = PolicyResult.FAILURE;
387 return operationRequest;
390 private Object startVfcOperation(ControlLoopEvent onset, Operation operation) {
391 this.operationRequest =
392 VfcActorServiceProvider.constructRequestCq((VirtualControlLoopEvent) onset,
393 operation.clOperation, this.policy, this.aaiCqResponse);
394 this.currentOperation = operation;
395 if (this.operationRequest == null) {
396 this.policyResult = PolicyResult.FAILURE;
398 return operationRequest;
401 private Object startSdnrOperation(ControlLoopEvent onset, Operation operation) {
403 * If the recipe is ModifyConfig or ModifyConfigANR, a SDNR request is constructed.
405 this.currentOperation = operation;
406 this.operationRequest = SdnrActorServiceProvider
407 .constructRequest((VirtualControlLoopEvent) onset, operation.clOperation, this.policy);
409 // Save the operation
411 if (this.operationRequest == null) {
412 this.policyResult = PolicyResult.FAILURE;
415 return operationRequest;
418 private Object startSdncOperation(ControlLoopEvent onset, Operation operation) {
419 SdncActorServiceProvider provider = new SdncActorServiceProvider();
420 this.operationRequest = provider.constructRequest((VirtualControlLoopEvent) onset,
421 operation.clOperation, this.policy);
422 this.currentOperation = operation;
423 if (this.operationRequest == null) {
424 this.policyResult = PolicyResult.FAILURE;
426 return operationRequest;
429 private Object startCdsOperation(ControlLoopEvent onset, Operation operation)
430 throws AaiException {
432 CdsActorServiceProvider provider = new CdsActorServiceProvider();
433 Optional<ExecutionServiceInput> optionalRequest =
434 provider.constructRequest((VirtualControlLoopEvent) onset, operation.clOperation,
435 this.policy, this.buildAaiParams());
437 this.currentOperation = operation;
438 if (optionalRequest.isPresent()) {
439 this.operationRequest = optionalRequest.get();
441 this.operationRequest = null;
442 this.policyResult = PolicyResult.FAILURE;
445 return this.operationRequest;
449 * Build AAI parameters for CDS operation.
451 * @return a map containing vnf id key and value for the vnf to apply the action to.
452 * @throws AaiException if the vnf can not be found.
454 private Map<String, String> buildAaiParams() throws AaiException {
456 Map<String, String> result = new HashMap<>();
458 if (TargetType.VNF.equals(policy.getTarget().getType())
459 || TargetType.VFMODULE.equals(policy.getTarget().getType())) {
461 ServiceInstance serviceInstance = this.aaiCqResponse.getServiceInstance();
462 if (serviceInstance == null) {
463 logger.info("Target entity service instance could not be found");
464 throw new AaiException("Target service instance could not be found");
467 GenericVnf genericVnf = this.aaiCqResponse
468 .getGenericVnfByModelInvariantId(policy.getTarget().getResourceID());
469 if (genericVnf == null) {
470 logger.info("Target entity generic vnf could not be found");
471 throw new AaiException("Target generic vnf could not be found");
474 result.put(AAI_SERVICE_INSTANCE_ID_KEY, serviceInstance.getServiceInstanceId());
475 result.put(GENERIC_VNF_VNF_ID, genericVnf.getVnfId());
477 } else if (TargetType.PNF.equals(policy.getTarget().getType())) {
478 result = this.eventManager.getPnf((VirtualControlLoopEvent) onset);
488 * @param response the response
489 * @return a PolicyResult
491 public PolicyResult onResponse(Object response) {
493 // Which response is it?
495 if (response instanceof Response) {
497 // Cast APPC response and handle it
499 return onResponse((Response) response);
500 } else if (response instanceof AppcLcmDmaapWrapper) {
502 // Cast LCM response and handle it
504 return onResponse((AppcLcmDmaapWrapper) response);
505 } else if (response instanceof PciResponseWrapper) {
507 // Cast SDNR response and handle it
509 return onResponse((PciResponseWrapper) response);
510 } else if (response instanceof SoResponseWrapper) {
512 // Cast SO response and handle it
514 return onResponse((SoResponseWrapper) response);
515 } else if (response instanceof VfcResponse) {
517 // Cast VFC response and handle it
519 return onResponse((VfcResponse) response);
520 } else if (response instanceof SdncResponse) {
522 // Cast SDNC response and handle it
524 return onResponse((SdncResponse) response);
525 } else if (response instanceof CdsResponse) {
527 // Cast CDS response and handle it
529 return onResponse((CdsResponse) response);
536 * This method handles operation responses from APPC.
538 * @param appcResponse the APPC response
539 * @return The result of the response handling
541 private PolicyResult onResponse(Response appcResponse) {
543 // Determine which subrequestID (ie. attempt)
545 Integer operationAttempt = getSubRequestId(appcResponse);
546 if (operationAttempt == null) {
547 this.completeOperation(operationAttempt,
548 "Policy was unable to parse APP-C SubRequestID (it was null).",
549 PolicyResult.FAILURE_EXCEPTION);
550 return PolicyResult.FAILURE_EXCEPTION;
553 // Sanity check the response message
555 if (appcResponse.getStatus() == null) {
557 // We cannot tell what happened if this doesn't exist
559 this.completeOperation(operationAttempt,
560 "Policy was unable to parse APP-C response status field (it was null).",
561 PolicyResult.FAILURE_EXCEPTION);
562 return PolicyResult.FAILURE_EXCEPTION;
565 // Get the Response Code
567 ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode());
570 // We are unaware of this code
572 this.completeOperation(operationAttempt,
573 "Policy was unable to parse APP-C response status code field.",
574 PolicyResult.FAILURE_EXCEPTION);
575 return PolicyResult.FAILURE_EXCEPTION;
578 return onResponse(appcResponse, operationAttempt, code);
581 private PolicyResult onResponse(Response appcResponse, Integer operationAttempt,
584 // Ok, let's figure out what APP-C's response is
589 // This is good, they got our original message and
592 // Is there any need to track this?
598 // We'll consider these two codes as exceptions
600 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
601 PolicyResult.FAILURE_EXCEPTION);
602 return getTimeoutResult(PolicyResult.FAILURE_EXCEPTION);
607 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
608 PolicyResult.SUCCESS);
609 return getTimeoutResult(PolicyResult.SUCCESS);
614 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
615 PolicyResult.FAILURE);
616 return getTimeoutResult(PolicyResult.FAILURE);
623 * This method handles operation responses from LCM.
625 * @param dmaapResponse the LCM response
626 * @return The result of the response handling
628 private PolicyResult onResponse(AppcLcmDmaapWrapper dmaapResponse) {
630 * Parse out the operation attempt using the subrequestid
632 Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(
633 dmaapResponse.getBody().getOutput().getCommonHeader().getSubRequestId());
634 if (operationAttempt == null) {
635 this.completeOperation(operationAttempt,
636 "Policy was unable to parse APP-C SubRequestID (it was null).",
637 PolicyResult.FAILURE_EXCEPTION);
638 return PolicyResult.FAILURE_EXCEPTION;
642 * Process the APPCLCM response to see what PolicyResult should be returned
644 AbstractMap.SimpleEntry<PolicyResult, String> result =
645 AppcLcmActorServiceProvider.processResponse(dmaapResponse);
647 if (result.getKey() != null) {
648 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
649 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
652 return result.getKey();
658 * This method handles operation responses from SDNR.
660 * @param dmaapResponse the SDNR response
661 * @return the result of the response handling
663 private PolicyResult onResponse(PciResponseWrapper dmaapResponse) {
665 * Parse out the operation attempt using the subrequestid
667 Integer operationAttempt = SdnrActorServiceProvider
668 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
669 if (operationAttempt == null) {
670 this.completeOperation(operationAttempt,
671 "Policy was unable to parse SDNR SubRequestID.", PolicyResult.FAILURE_EXCEPTION);
672 return PolicyResult.FAILURE_EXCEPTION;
676 * Process the SDNR response to see what PolicyResult should be returned
678 Pair<PolicyResult, String> result =
679 SdnrActorServiceProvider.processResponse(dmaapResponse);
681 if (result.getLeft() != null) {
682 this.completeOperation(operationAttempt, result.getRight(), result.getLeft());
683 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
686 return result.getLeft();
692 * This method handles operation responses from SO.
694 * @param msoResponse the SO response
695 * @return The result of the response handling
697 private PolicyResult onResponse(SoResponseWrapper msoResponse) {
698 switch (msoResponse.getSoResponse().getHttpResponseCode()) {
702 // Consider it as success
704 this.completeOperation(this.attempts,
705 msoResponse.getSoResponse().getHttpResponseCode() + SUCCESS_MSG,
706 PolicyResult.SUCCESS);
707 return getTimeoutResult(PolicyResult.SUCCESS);
710 // Consider it as failure
712 this.completeOperation(this.attempts,
713 msoResponse.getSoResponse().getHttpResponseCode() + FAILED_MSG,
714 PolicyResult.FAILURE);
715 return getTimeoutResult(PolicyResult.FAILURE);
720 * This method handles operation responses from VFC.
722 * @param vfcResponse the VFC response
723 * @return The result of the response handling
725 private PolicyResult onResponse(VfcResponse vfcResponse) {
726 if ("finished".equalsIgnoreCase(vfcResponse.getResponseDescriptor().getStatus())) {
728 // Consider it as success
730 this.completeOperation(this.attempts, SUCCESS_MSG, PolicyResult.SUCCESS);
731 return getTimeoutResult(PolicyResult.SUCCESS);
734 // Consider it as failure
736 this.completeOperation(this.attempts, FAILED_MSG, PolicyResult.FAILURE);
737 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
740 // increment operation attempts for retries
742 return PolicyResult.FAILURE;
747 * This method handles operation responses from SDNC.
749 * @param sdncResponse the VFC response
750 * @return The result of the response handling
752 private PolicyResult onResponse(SdncResponse sdncResponse) {
753 if ("200".equals(sdncResponse.getResponseOutput().getResponseCode())) {
755 // Consider it as success
757 this.completeOperation(this.attempts, SUCCESS_MSG, PolicyResult.SUCCESS);
758 return getTimeoutResult(PolicyResult.SUCCESS);
761 // Consider it as failure
763 this.completeOperation(this.attempts, FAILED_MSG, PolicyResult.FAILURE);
764 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
767 // increment operation attempts for retries
769 return PolicyResult.FAILURE;
774 * This method handles operation responses from CDS.
776 * @param response the CDS response
777 * @return The result of the response handling
779 private PolicyResult onResponse(CdsResponse response) {
780 if (response != null && CdsActorConstants.SUCCESS.equals(response.getStatus())) {
782 // Consider it as success
784 this.completeOperation(this.attempts, SUCCESS_MSG, PolicyResult.SUCCESS);
785 return getTimeoutResult(PolicyResult.SUCCESS);
788 // Consider it as failure
790 this.completeOperation(this.attempts, FAILED_MSG, PolicyResult.FAILURE);
791 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
794 // increment operation attempts for retries
796 return PolicyResult.FAILURE;
800 private PolicyResult getTimeoutResult(PolicyResult result) {
801 return (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult) ? null : result);
804 private Integer getSubRequestId(Response appcResponse) {
806 return Integer.valueOf(appcResponse.getCommonHeader().getSubRequestId());
807 } catch (NumberFormatException e) {
809 // We cannot tell what happened if this doesn't exist
816 * Get the operation timeout.
818 * @return the timeout
820 public Integer getOperationTimeout() {
824 if (this.policy == null) {
825 logger.debug("getOperationTimeout returning 0");
828 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
829 return this.policy.getTimeout();
833 * Get the operation timeout as a String.
835 * @param defaultTimeout the default timeout
836 * @return the timeout as a String
838 public String getOperationTimeoutString(int defaultTimeout) {
839 Integer to = this.getOperationTimeout();
840 if (to == null || to == 0) {
841 return Integer.toString(defaultTimeout) + "s";
843 return to.toString() + "s";
846 public PolicyResult getOperationResult() {
847 return this.policyResult;
851 * Get the operation as a message.
853 * @return the operation as a message
855 public String getOperationMessage() {
856 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
857 return this.currentOperation.clOperation.toMessage();
860 if (!this.operationHistory.isEmpty()) {
861 return this.operationHistory.getLast().clOperation.toMessage();
867 * Get the operation as a message including the guard result.
869 * @param guardResult the guard result
870 * @return the operation as a message including the guard result
872 public String getOperationMessage(String guardResult) {
873 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
874 return this.currentOperation.clOperation.toMessage() + ", Guard result: " + guardResult;
877 if (!this.operationHistory.isEmpty()) {
878 return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: "
885 * Get the operation history.
887 * @return the operation history
889 public String getOperationHistory() {
890 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
891 return this.currentOperation.clOperation.toHistory();
894 if (!this.operationHistory.isEmpty()) {
895 return this.operationHistory.getLast().clOperation.toHistory();
903 * @return the list of control loop operations
905 public List<ControlLoopOperation> getHistory() {
906 LinkedList<ControlLoopOperation> history = new LinkedList<>();
907 for (Operation op : this.operationHistory) {
908 history.add(new ControlLoopOperation(op.clOperation));
915 * Set the operation has timed out.
917 public void setOperationHasTimedOut() {
921 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
925 * Set the operation has been denied by guard.
927 public void setOperationHasGuardDeny() {
931 this.completeOperation(this.attempts, "Operation denied by Guard",
932 PolicyResult.FAILURE_GUARD);
935 public void setOperationHasException(String message) {
936 this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
940 * Is the operation complete.
942 * @return <code>true</code> if the operation is complete, <code>false</code> otherwise
944 public boolean isOperationComplete() {
946 // Is there currently a result?
948 if (this.policyResult == null) {
950 // either we are in process or we
956 // We have some result, check if the operation failed
958 if (this.policyResult.equals(PolicyResult.FAILURE)) {
960 // Check if there were no retries specified
962 if (getMaxRetries() < 1) {
964 // The result is the failure
971 if (this.attempts > getMaxRetries()) {
973 // No more attempts allowed, reset
974 // that our actual result is failure due to retries
976 this.policyResult = PolicyResult.FAILURE_RETRIES;
980 // There are more attempts available to try the
987 // Other results mean we are done
992 public boolean isOperationRunning() {
993 return (this.currentOperation != null);
997 * This method verifies that the operation manager may run an operation.
999 * @return True if the operation can run, false otherwise
1000 * @throws ControlLoopException if the operation cannot run
1002 private void verifyOperatonCanRun() throws ControlLoopException {
1004 // They shouldn't call us if we currently running something
1006 if (this.currentOperation != null) {
1008 // what do we do if we are already running an operation?
1010 throw new ControlLoopException(
1011 "current operation is not null (an operation is already running)");
1014 // Check if we have maxed out on retries
1016 if (getMaxRetries() < 1) {
1018 // No retries are allowed, so check have we even made
1019 // one attempt to execute the operation?
1021 if (this.attempts >= 1) {
1023 // We have, let's ensure our PolicyResult is set
1025 if (this.policyResult == null) {
1026 this.policyResult = PolicyResult.FAILURE_RETRIES;
1031 throw new ControlLoopException(
1032 "current operation failed and retries are not allowed");
1036 // Have we maxed out on retries?
1038 if (this.attempts > getMaxRetries()) {
1039 if (this.policyResult == null) {
1040 this.policyResult = PolicyResult.FAILURE_RETRIES;
1042 throw new ControlLoopException(
1043 "current oepration has failed after " + this.attempts + " retries");
1049 * Gets the maximum number of retries.
1051 * @return the maximum number of retries, or {@code 0}, if not specified
1053 public int getMaxRetries() {
1054 return (policy.getRetry() != null ? policy.getRetry() : 0);
1057 private void storeOperationInDataBase() {
1058 // Only store in DB if enabled
1059 boolean guardEnabled = "false".equalsIgnoreCase(
1060 PolicyEngineConstants.getManager().getEnvironmentProperty("guard.disabled"));
1061 if (!guardEnabled) {
1066 Properties props = new Properties();
1067 if (PolicyEngineConstants.getManager().getEnvironmentProperty(Util.ONAP_KEY_URL) != null
1068 && PolicyEngineConstants.getManager().getEnvironmentProperty(Util.ONAP_KEY_USER) != null
1069 && PolicyEngineConstants.getManager()
1070 .getEnvironmentProperty(Util.ONAP_KEY_PASS) != null) {
1071 props.put(Util.ECLIPSE_LINK_KEY_URL,
1072 PolicyEngineConstants.getManager().getEnvironmentProperty(Util.ONAP_KEY_URL));
1073 props.put(Util.ECLIPSE_LINK_KEY_USER,
1074 PolicyEngineConstants.getManager().getEnvironmentProperty(Util.ONAP_KEY_USER));
1075 props.put(Util.ECLIPSE_LINK_KEY_PASS,
1076 PolicyEngineConstants.getManager().getEnvironmentProperty(Util.ONAP_KEY_PASS));
1077 props.put(PersistenceUnitProperties.CLASSLOADER,
1078 ControlLoopOperationManager.class.getClassLoader());
1081 String opsHistPu = System.getProperty("OperationsHistoryPU");
1082 if (!"OperationsHistoryPUTest".equals(opsHistPu)) {
1083 opsHistPu = "OperationsHistoryPU";
1089 em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager();
1090 } catch (Exception e) {
1091 logger.error("storeOperationInDataBase threw: ", e);
1095 OperationsHistory newEntry = new OperationsHistory();
1097 newEntry.setClosedLoopName(this.onset.getClosedLoopControlName());
1098 newEntry.setRequestId(this.onset.getRequestId().toString());
1099 newEntry.setActor(this.currentOperation.clOperation.getActor());
1100 newEntry.setOperation(this.currentOperation.clOperation.getOperation());
1101 newEntry.setTarget(this.targetEntity);
1102 newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart()));
1103 newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId());
1105 .setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli()));
1106 newEntry.setMessage(this.currentOperation.clOperation.getMessage());
1107 newEntry.setOutcome(this.currentOperation.clOperation.getOutcome());
1109 em.getTransaction().begin();
1110 em.persist(newEntry);
1111 em.getTransaction().commit();
1116 private void completeOperation(Integer attempt, String message, PolicyResult result) {
1117 if (attempt == null) {
1118 logger.debug("attempt cannot be null (i.e. subRequestID)");
1121 if (this.currentOperation != null) {
1122 if (this.currentOperation.attempt == attempt.intValue()) {
1123 this.currentOperation.clOperation.setEnd(Instant.now());
1124 this.currentOperation.clOperation.setMessage(message);
1125 this.currentOperation.clOperation.setOutcome(result.toString());
1126 this.currentOperation.policyResult = result;
1128 // Save it in history
1130 this.operationHistory.add(this.currentOperation);
1131 this.storeOperationInDataBase();
1133 // Set our last result
1135 this.policyResult = result;
1137 // Clear the current operation field
1139 this.currentOperation = null;
1142 logger.debug("not current");
1144 for (Operation op : this.operationHistory) {
1145 if (op.attempt == attempt.intValue()) {
1146 op.clOperation.setEnd(Instant.now());
1147 op.clOperation.setMessage(message);
1148 op.clOperation.setOutcome(result.toString());
1149 op.policyResult = result;
1153 logger.debug("Could not find associated operation");
1157 * Commit the abatement to the history database.
1159 * @param message the abatement message
1160 * @param outcome the abatement outcome
1162 public void commitAbatement(String message, String outcome) {
1163 logger.info("commitAbatement: {}. {}", message, outcome);
1165 if (this.currentOperation == null) {
1167 this.currentOperation = this.operationHistory.getLast();
1168 } catch (NoSuchElementException e) {
1169 logger.error("{}: commitAbatement threw an exception ", this, e);
1173 this.currentOperation.clOperation.setEnd(Instant.now());
1174 this.currentOperation.clOperation.setMessage(message);
1175 this.currentOperation.clOperation.setOutcome(outcome);
1177 // Store commit in DB
1179 this.storeOperationInDataBase();
1181 // Clear the current operation field
1183 this.currentOperation = null;
1187 * Construct a ControlLoopResponse object from actor response and input event.
1189 * @param response the response from actor
1190 * @param event the input event
1192 * @return a ControlLoopResponse
1194 public ControlLoopResponse getControlLoopResponse(Object response,
1195 VirtualControlLoopEvent event) {
1196 if (response instanceof PciResponseWrapper) {
1198 // Cast SDNR response and handle it
1200 return SdnrActorServiceProvider.getControlLoopResponse((PciResponseWrapper) response,