diff options
author | liamfallon <liam.fallon@ericsson.com> | 2018-02-08 21:54:16 +0000 |
---|---|---|
committer | liamfallon <liam.fallon@ericsson.com> | 2018-02-08 22:23:54 +0000 |
commit | d536517dd5d45abeb037eb3900759771d97b2418 (patch) | |
tree | 38c5dda6db8e1ef7846d97b456664b05259e6039 | |
parent | 5343982363a2221cdf9bd28fdb1f6547c04745f6 (diff) |
JUint/Technical Debt for eventmanager
Unit test expanded for SO POJOs, technical debt removed in eventmanager.
Change-Id: I7045f5af88fd2c15019befe29a0b4fcd69801c49
Signed-off-by: liamfallon <liam.fallon@ericsson.com>
Issue-ID: POLICY-455
Signed-off-by: liamfallon <liam.fallon@ericsson.com>
29 files changed, 2551 insertions, 942 deletions
diff --git a/controlloop/common/eventmanager/pom.xml b/controlloop/common/eventmanager/pom.xml index d4f811007..33f858dee 100644 --- a/controlloop/common/eventmanager/pom.xml +++ b/controlloop/common/eventmanager/pom.xml @@ -39,7 +39,7 @@ <artifactId>commons-io</artifactId> <version>2.5</version> <scope>provided</scope> - </dependency> + </dependency> <dependency> <groupId>com.att.research.xacml</groupId> <artifactId>xacml</artifactId> @@ -64,12 +64,12 @@ <version>${project.version}</version> <scope>provided</scope> </dependency> - <dependency> - <groupId>org.onap.policy.drools-applications</groupId> - <artifactId>actor.vfc</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actor.vfc</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> <dependency> <groupId>org.onap.policy.drools-applications</groupId> <artifactId>actor.appclcm</artifactId> @@ -94,12 +94,12 @@ <version>${project.version}</version> <scope>provided</scope> </dependency> - <dependency> - <groupId>org.onap.policy.drools-applications</groupId> - <artifactId>vfc</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>vfc</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> <dependency> <groupId>org.onap.policy.drools-applications</groupId> <artifactId>appclcm</artifactId> @@ -142,25 +142,25 @@ <version>${project.version}</version> <scope>provided</scope> </dependency> - <dependency> - <groupId>org.onap.policy.drools-applications</groupId> - <artifactId>vfc</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>vfc</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - <version>4.5.5</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.onap.policy.drools-pdp</groupId> - <artifactId>policy-management</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5.5</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>policy-management</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> <dependency> <groupId>org.onap.policy.drools-applications</groupId> <artifactId>simulators</artifactId> diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java index e828150a0..3f19fdcaf 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java @@ -21,10 +21,6 @@ package org.onap.policy.controlloop; public class ControlLoopException extends Exception { - - /** - * - */ private static final long serialVersionUID = 6400725747325923701L; public ControlLoopException() { @@ -47,5 +43,4 @@ public class ControlLoopException extends Exception { public ControlLoopException(Throwable cause) { super(cause); } - } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java index bb23983ce..437920cfb 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java @@ -25,7 +25,6 @@ import java.lang.reflect.Constructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public interface ControlLoopLogger { public void info(String... parameters); @@ -35,21 +34,16 @@ public interface ControlLoopLogger { public void metrics(Object obj); public static class Factory { - private static final Logger logger = LoggerFactory.getLogger(Factory.class); - public ControlLoopLogger buildLogger(String className) throws ControlLoopException { - try { Constructor<?> constr = Class.forName(className).getConstructor(); return (ControlLoopLogger) constr.newInstance(); } catch (Exception e) { logger.error("buildLogger threw: ", e); - throw new ControlLoopException("Cannot load class " + className); + throw new ControlLoopException("Cannot load class " + className + " as a control loop logger"); } } - } - } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java index 9272e2887..3d31c413b 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java @@ -39,11 +39,8 @@ public interface ControlLoopPublisher { return (ControlLoopPublisher) constr.newInstance(); } catch (Exception e) { logger.error("ControlLoopPublisher.buildLogger threw: ", e); - throw new ControlLoopException("Cannot load class " + className); + throw new ControlLoopException("Cannot load class " + className + " as a control loop publisher"); } } - } - - } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java index 2b296616d..1d1451461 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java @@ -52,16 +52,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopEventManager implements LockCallback, Serializable { - - /** - * - */ + private static final String VM_NAME = "VM_NAME"; + private static final String VNF_NAME = "VNF_NAME"; + private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id"; + private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name"; + private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name"; + private static final String GENERIC_VNF_IS_CLOSED_LOOP_DISABLED = "generic-vnf.is-closed-loop-disabled"; + private static final String VSERVER_IS_CLOSED_LOOP_DISABLED = "vserver.is-closed-loop-disabled"; + private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class); - + private static final long serialVersionUID = -1216568161322872641L; public final String closedLoopControlName; public final UUID requestID; - + private String controlLoopResult; private transient ControlLoopProcessor processor = null; private VirtualControlLoopEvent onset; @@ -79,28 +83,28 @@ public class ControlLoopEventManager implements LockCallback, Serializable { private static String aaiHostURL; private static String aaiUser; private static String aaiPassword; - + private static Collection<String> requiredAAIKeys = new ArrayList<>(); static { requiredAAIKeys.add("AICVServerSelfLink"); requiredAAIKeys.add("AICIdentity"); requiredAAIKeys.add("is_closed_loop_disabled"); - requiredAAIKeys.add("VM_NAME"); + requiredAAIKeys.add(VM_NAME); } public ControlLoopEventManager(String closedLoopControlName, UUID requestID) { this.closedLoopControlName = closedLoopControlName; this.requestID = requestID; } - + public String getControlLoopResult() { return controlLoopResult; } - + public void setControlLoopResult(String controlLoopResult) { this.controlLoopResult = controlLoopResult; } - + public Integer getNumOnsets() { return numOnsets; } @@ -124,20 +128,20 @@ public class ControlLoopEventManager implements LockCallback, Serializable { public void setActivated(boolean isActivated) { this.isActivated = isActivated; } - - public VirtualControlLoopEvent getOnsetEvent() { + + public VirtualControlLoopEvent getOnsetEvent() { return this.onset; } - + public VirtualControlLoopEvent getAbatementEvent() { return this.abatement; } - + public ControlLoopProcessor getProcessor() { return this.processor; } - public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) { + public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) { VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event); try { // @@ -150,7 +154,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // Syntax check the event // checkEventSyntax(event); - + // // At this point we are good to go with this event // @@ -163,16 +167,14 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // this.isActivated = true; } catch (ControlLoopException e) { - logger.error("{}: activate threw: ",this, e); + logger.error("{}: activate by event threw: ", this, e); notification.setNotification(ControlLoopNotificationType.REJECTED); notification.setMessage(e.getMessage()); } return notification; } - - - - public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) { + + public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) { VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event); try { // @@ -185,27 +187,39 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // Syntax check the event // checkEventSyntax(event); - + // // Check the YAML // if (yamlSpecification == null || yamlSpecification.length() < 1) { throw new ControlLoopException("yaml specification is null or 0 length"); } - String decodedYaml = null; - try { - decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8"); - if (decodedYaml != null && decodedYaml.length() > 0) { - yamlSpecification = decodedYaml; - } - } catch (UnsupportedEncodingException e) { - logger.error("{}: activate threw: ",this, e); + } catch (ControlLoopException e) { + logger.error("{}: activate by YAML specification and event threw: ",this, e); + notification.setNotification(ControlLoopNotificationType.REJECTED); + notification.setMessage(e.getMessage()); + return notification; + } + + String decodedYaml = null; + try { + decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8"); + if (decodedYaml != null && decodedYaml.length() > 0) { + yamlSpecification = decodedYaml; } + } catch (UnsupportedEncodingException e) { + logger.error("{}: YAML decode in activate by YAML specification and event threw: ", this, e); + notification.setNotification(ControlLoopNotificationType.REJECTED); + notification.setMessage(e.getMessage()); + return notification; + } + + try { // // Parse the YAML specification // this.processor = new ControlLoopProcessor(yamlSpecification); - + // // At this point we are good to go with this event // @@ -220,18 +234,18 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // this.isActivated = true; } catch (ControlLoopException e) { - logger.error("{}: activate threw: ",this, e); + logger.error("{}: activate by YAML specification and event threw: ",this, e); notification.setNotification(ControlLoopNotificationType.REJECTED); notification.setMessage(e.getMessage()); } return notification; } - - public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException { + + public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException { // // Check if they activated us // - if (this.isActivated == false) { + if (!this.isActivated) { throw new ControlLoopException("ControlLoopEventManager MUST be activated first."); } // @@ -266,10 +280,12 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // return null; } - + switch (result) { case FINAL_FAILURE_EXCEPTION: + notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); notification.setMessage("Exception in processing closed loop"); + break; case FINAL_FAILURE: case FINAL_FAILURE_RETRIES: case FINAL_FAILURE_TIMEOUT: @@ -291,12 +307,12 @@ public class ControlLoopEventManager implements LockCallback, Serializable { notification.getHistory().addAll(this.controlLoopHistory); return notification; } - - public ControlLoopOperationManager processControlLoop() throws ControlLoopException, AAIException { + + public ControlLoopOperationManager processControlLoop() throws ControlLoopException, AAIException { // // Check if they activated us // - if (this.isActivated == false) { + if (!this.isActivated) { throw new ControlLoopException("ControlLoopEventManager MUST be activated first."); } // @@ -343,7 +359,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // return this.currentOperation; } - + public void finishOperation(ControlLoopOperationManager operation) throws ControlLoopException { // // Verify we have a current operation @@ -377,8 +393,8 @@ public class ControlLoopEventManager implements LockCallback, Serializable { } throw new ControlLoopException("No operation to finish."); } - - public synchronized LockResult<GuardResult, TargetLock> lockCurrentOperation() throws ControlLoopException { + + public synchronized LockResult<GuardResult, TargetLock> lockCurrentOperation() throws ControlLoopException { // // Sanity check // @@ -393,16 +409,16 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // TODO: Make sure the current lock is for the same target. // Currently, it should be. But in the future it may not. // - return new LockResult<GuardResult, TargetLock>(GuardResult.LOCK_ACQUIRED, this.targetLock); + return new LockResult<>(GuardResult.LOCK_ACQUIRED, this.targetLock); } else { // // Ask the Guard // LockResult<GuardResult, TargetLock> lockResult = PolicyGuard.lockTarget( - this.currentOperation.policy.getTarget().getType(), - this.currentOperation.getTargetEntity(), - this.onset.getRequestID(), - this); + this.currentOperation.policy.getTarget().getType(), + this.currentOperation.getTargetEntity(), + this.onset.getRequestID(), + this); // // Was it acquired? // @@ -415,19 +431,19 @@ public class ControlLoopEventManager implements LockCallback, Serializable { return lockResult; } } - + public synchronized TargetLock unlockCurrentOperation() { if (this.targetLock == null) { return null; } - if (PolicyGuard.unlockTarget(this.targetLock) == true) { + if (PolicyGuard.unlockTarget(this.targetLock)) { TargetLock returnLock = this.targetLock; this.targetLock = null; return returnLock; } return null; } - + public enum NEW_EVENT_STATUS { FIRST_ONSET, SUBSEQUENT_ONSET, @@ -436,8 +452,8 @@ public class ControlLoopEventManager implements LockCallback, Serializable { SYNTAX_ERROR ; } - - public NEW_EVENT_STATUS onNewEvent(VirtualControlLoopEvent event) throws AAIException { + + public NEW_EVENT_STATUS onNewEvent(VirtualControlLoopEvent event) throws AAIException { try { this.checkEventSyntax(event); if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ONSET) { @@ -445,11 +461,11 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // Check if this is our original ONSET // if (event.equals(this.onset)) { - // - // Query A&AI if needed - // - queryAai(event); - + // + // Query A&AI if needed + // + queryAai(event); + // // DO NOT retract it // @@ -460,7 +476,8 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // this.numOnsets++; return NEW_EVENT_STATUS.SUBSEQUENT_ONSET; - } else if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) { + } + else if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) { // // Have we already got an abatement? // @@ -477,7 +494,8 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // // return NEW_EVENT_STATUS.FIRST_ABATEMENT; - } else { + } + else { // // Keep track that we received another // @@ -487,15 +505,14 @@ public class ControlLoopEventManager implements LockCallback, Serializable { // return NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT; } - } else { - return NEW_EVENT_STATUS.SYNTAX_ERROR; } - } catch (ControlLoopException e) { + } + catch (ControlLoopException e) { logger.error("{}: onNewEvent threw: ",this, e); - return NEW_EVENT_STATUS.SYNTAX_ERROR; } + return NEW_EVENT_STATUS.SYNTAX_ERROR; } - + public VirtualControlLoopNotification setControlLoopTimedOut() { this.controlLoopTimedOut = FinalResult.FINAL_FAILURE_TIMEOUT; VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset); @@ -504,12 +521,12 @@ public class ControlLoopEventManager implements LockCallback, Serializable { notification.getHistory().addAll(this.controlLoopHistory); return notification; } - + public boolean isControlLoopTimedOut() { return (this.controlLoopTimedOut == FinalResult.FINAL_FAILURE_TIMEOUT); } - - public int getControlLoopTimeout(Integer defaultTimeout) { + + public int getControlLoopTimeout(Integer defaultTimeout) { if (this.processor != null && this.processor.getControlLoop() != null) { return this.processor.getControlLoop().getTimeout(); } @@ -518,7 +535,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable { } return 0; } - + public AAIGETVnfResponse getVnfResponse() { return vnfResponse; } @@ -526,7 +543,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable { public AAIGETVserverResponse getVserverResponse() { return vserverResponse; } - + public void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException { if (event.getClosedLoopEventStatus() == null || (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET && @@ -544,162 +561,144 @@ public class ControlLoopEventManager implements LockCallback, Serializable { } if (event.getTarget() == null || event.getTarget().length() < 1) { throw new ControlLoopException("No target field"); - } else if (! "VM_NAME".equalsIgnoreCase(event.getTarget()) && - ! "VNF_NAME".equalsIgnoreCase(event.getTarget()) && - ! "vserver.vserver-name".equalsIgnoreCase(event.getTarget()) && - ! "generic-vnf.vnf-id".equalsIgnoreCase(event.getTarget()) && - ! "generic-vnf.vnf-name".equalsIgnoreCase(event.getTarget()) ) { + } else if (! VM_NAME.equalsIgnoreCase(event.getTarget()) && + ! VNF_NAME.equalsIgnoreCase(event.getTarget()) && + ! VSERVER_VSERVER_NAME.equalsIgnoreCase(event.getTarget()) && + ! GENERIC_VNF_VNF_ID.equalsIgnoreCase(event.getTarget()) && + ! GENERIC_VNF_VNF_NAME.equalsIgnoreCase(event.getTarget()) ) { throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME"); } if (event.getAAI() == null) { - throw new ControlLoopException("AAI is null"); - } - if (event.getAAI().get("generic-vnf.vnf-id") == null && event.getAAI().get("vserver.vserver-name") == null && - event.getAAI().get("generic-vnf.vnf-name") == null) { - throw new ControlLoopException("generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing"); - } - } - + throw new ControlLoopException("AAI is null"); + } + if (event.getAAI().get(GENERIC_VNF_VNF_ID) == null && event.getAAI().get(VSERVER_VSERVER_NAME) == null && + event.getAAI().get(GENERIC_VNF_VNF_NAME) == null) { + throw new ControlLoopException("generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing"); + } + } + public void queryAai(VirtualControlLoopEvent event) throws AAIException { - if (event.getAAI().get("vserver.is-closed-loop-disabled") == null && - event.getAAI().get("generic-vnf.is-closed-loop-disabled") == null) { - try { - if (event.getAAI().get("generic-vnf.vnf-id") != null) { - vnfResponse = getAAIVnfInfo(event); - if (vnfResponse == null) { - throw new AAIException("AAI Response is null (query by vnf-id)"); - } - if (vnfResponse.getRequestError() != null) { - throw new AAIException("AAI Responded with a request error (query by vnf-id)"); - } - if (isClosedLoopDisabled(vnfResponse) == true) { - throw new AAIException("is-closed-loop-disabled is set to true"); - } - } else if (event.getAAI().get("generic-vnf.vnf-name") != null) { - vnfResponse = getAAIVnfInfo(event); - if (vnfResponse == null) { - throw new AAIException("AAI Response is null (query by vnf-name)"); - } - if (vnfResponse.getRequestError() != null) { - throw new AAIException("AAI Responded with a request error (query by vnf-name)"); - } - if (isClosedLoopDisabled(vnfResponse) == true) { - throw new AAIException("is-closed-loop-disabled is set to true"); - } - } else if (event.getAAI().get("vserver.vserver-name") != null) { - vserverResponse = getAAIVserverInfo(event); - if (vserverResponse == null) { - throw new AAIException("AAI Response is null (query by vserver-name)"); - } - if (vserverResponse.getRequestError() != null) { - throw new AAIException("AAI responded with a request error (query by vserver-name)"); - } - if (isClosedLoopDisabled(vserverResponse) == true) { - throw new AAIException("is-closed-loop-disabled is set to true"); - } - } - } catch (Exception e) { - logger.error("Exception from getAAIInfo: ", e); - throw new AAIException("Exception from getAAIInfo: " + e.toString()); + if ((event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED) != null || event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED) != null) && isClosedLoopDisabled(event)) { + throw new AAIException("is-closed-loop-disabled is set to true on VServer or VNF"); + } + + try { + if (event.getAAI().get(GENERIC_VNF_VNF_ID) != null || event.getAAI().get(GENERIC_VNF_VNF_NAME) != null) { + vnfResponse = getAAIVnfInfo(event); + processVNFResponse(vnfResponse, event.getAAI().get(GENERIC_VNF_VNF_ID) != null); + } + else if (event.getAAI().get(VSERVER_VSERVER_NAME) != null) { + vserverResponse = getAAIVserverInfo(event); + processVServerResponse(vserverResponse); } - } else if (isClosedLoopDisabled(event)) { - throw new AAIException("is-closed-loop-disabled is set to true"); - } - } - - public static boolean isClosedLoopDisabled(AAIGETVnfResponse aaiResponse) { - if (aaiResponse != null && aaiResponse.getIsClosedLoopDisabled() != null) { - String value = aaiResponse.getIsClosedLoopDisabled(); - if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) || - "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) { - return true; - } - } - - return false; - } - - public static boolean isClosedLoopDisabled(AAIGETVserverResponse aaiResponse) { - if (aaiResponse != null && aaiResponse.getIsClosedLoopDisabled() != null) { - String value = aaiResponse.getIsClosedLoopDisabled(); - if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) || - "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) { - return true; - } - } - - return false; - } - + } catch (Exception e) { + logger.error("Exception from queryAai: ", e); + throw new AAIException("Exception from queryAai: " + e.toString()); + } + } + + private static void processVNFResponse(AAIGETVnfResponse aaiResponse, boolean queryByVNFID) throws AAIException { + String queryTypeString = (queryByVNFID ? "vnf-id" : "vnf-name"); + + if (aaiResponse == null) { + throw new AAIException("AAI Response is null (query by " + queryTypeString + ")"); + } + if (aaiResponse.getRequestError() != null) { + throw new AAIException("AAI Responded with a request error (query by " + queryTypeString + ")"); + } + + if (aaiResponse.getIsClosedLoopDisabled() != null) { + String value = aaiResponse.getIsClosedLoopDisabled(); + if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) || + "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) { + throw new AAIException("is-closed-loop-disabled is set to true (query by " + queryTypeString + ")"); + } + } + } + + private static void processVServerResponse(AAIGETVserverResponse aaiResponse) throws AAIException { + if (aaiResponse == null) { + throw new AAIException("AAI Response is null (query by vserver-name)"); + } + if (aaiResponse.getRequestError() != null) { + throw new AAIException("AAI responded with a request error (query by vserver-name)"); + } + + if (aaiResponse.getIsClosedLoopDisabled() != null) { + String value = aaiResponse.getIsClosedLoopDisabled(); + if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) || + "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) { + throw new AAIException("is-closed-loop-disabled is set to true (query by vserver-name)"); + } + } + } + public static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) { - if ("true".equalsIgnoreCase(event.getAAI().get("vserver.is-closed-loop-disabled")) || - "T".equalsIgnoreCase(event.getAAI().get("vserver.is-closed-loop-disabled")) || - "yes".equalsIgnoreCase(event.getAAI().get("vserver.is-closed-loop-disabled")) || - "Y".equalsIgnoreCase(event.getAAI().get("vserver.is-closed-loop-disabled"))) { + if ("true".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED)) || + "T".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED)) || + "yes".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED)) || + "Y".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED))) { return true; } - else if ("true".equalsIgnoreCase(event.getAAI().get("generic-vnf.is-closed-loop-disabled")) || - "T".equalsIgnoreCase(event.getAAI().get("generic-vnf.is-closed-loop-disabled")) || - "yes".equalsIgnoreCase(event.getAAI().get("generic-vnf.is-closed-loop-disabled")) || - "Y".equalsIgnoreCase(event.getAAI().get("generic-vnf.is-closed-loop-disabled"))) { - return true; - } - return false; + return ("true".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) || + "T".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) || + "yes".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) || + "Y".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED))); } - + public static AAIGETVserverResponse getAAIVserverInfo(VirtualControlLoopEvent event) throws ControlLoopException { UUID requestID = event.getRequestID(); AAIGETVserverResponse response = null; - String vserverName = event.getAAI().get("vserver.vserver-name"); + String vserverName = event.getAAI().get(VSERVER_VSERVER_NAME); try { - if (vserverName != null) { - aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url"); - aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username"); - aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); - String aaiGetQueryByVserver = "/aai/v11/nodes/vservers?vserver-name="; - String url = aaiHostURL + aaiGetQueryByVserver; - logger.info("url: " + url); - response = new AAIManager(new RESTManager()).getQueryByVserverName(url, aaiUser, aaiPassword, requestID, vserverName); - } - } catch (Exception e) { - logger.error("getAAIVserverInfo exception: ", e); - throw new ControlLoopException("Exception in getAAIVserverInfo: ", e); - } - + if (vserverName != null) { + aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url"); + aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username"); + aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); + String aaiGetQueryByVserver = "/aai/v11/nodes/vservers?vserver-name="; + String url = aaiHostURL + aaiGetQueryByVserver; + logger.info("AAI Host URL by VServer: {}", url); + response = new AAIManager(new RESTManager()).getQueryByVserverName(url, aaiUser, aaiPassword, requestID, vserverName); + } + } catch (Exception e) { + logger.error("getAAIVserverInfo exception: ", e); + throw new ControlLoopException("Exception in getAAIVserverInfo: ", e); + } + return response; } - + public static AAIGETVnfResponse getAAIVnfInfo(VirtualControlLoopEvent event) throws ControlLoopException { UUID requestID = event.getRequestID(); AAIGETVnfResponse response = null; - String vnfName = event.getAAI().get("generic-vnf.vnf-name"); - String vnfID = event.getAAI().get("generic-vnf.vnf-id"); - + String vnfName = event.getAAI().get(GENERIC_VNF_VNF_NAME); + String vnfID = event.getAAI().get(GENERIC_VNF_VNF_ID); + aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url"); - aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username"); - aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); - + aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username"); + aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); + try { - if (vnfName != null) { - String aaiGetQueryByVnfName = "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name="; - String url = aaiHostURL + aaiGetQueryByVnfName; - logger.info("url: " + url); - response = new AAIManager(new RESTManager()).getQueryByVnfName(url, aaiUser, aaiPassword, requestID, vnfName); - } else if (vnfID != null) { - String aaiGetQueryByVnfID = "/aai/v11/network/generic-vnfs/generic-vnf/"; - String url = aaiHostURL + aaiGetQueryByVnfID; - logger.info("url: " + url); - response = new AAIManager(new RESTManager()).getQueryByVnfID(url, aaiUser, aaiPassword, requestID, vnfID); - } - } catch (Exception e) { - logger.error("getAAIVnfInfo exception: ", e); - throw new ControlLoopException("Exception in getAAIVnfInfo: ", e); - } - + if (vnfName != null) { + String aaiGetQueryByVnfName = "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name="; + String url = aaiHostURL + aaiGetQueryByVnfName; + logger.info("AAI Host URL by VNF name: {}", url); + response = new AAIManager(new RESTManager()).getQueryByVnfName(url, aaiUser, aaiPassword, requestID, vnfName); + } else if (vnfID != null) { + String aaiGetQueryByVnfID = "/aai/v11/network/generic-vnfs/generic-vnf/"; + String url = aaiHostURL + aaiGetQueryByVnfID; + logger.info("AAI Host URL by VNF ID: {}", url); + response = new AAIManager(new RESTManager()).getQueryByVnfID(url, aaiUser, aaiPassword, requestID, vnfID); + } + } catch (Exception e) { + logger.error("getAAIVnfInfo exception: ", e); + throw new ControlLoopException("Exception in getAAIVnfInfo: ", e); + } + return response; } - + @Override public boolean isActive() { // TODO @@ -719,5 +718,5 @@ public class ControlLoopEventManager implements LockCallback, Serializable { + numAbatements + ", isActivated=" + isActivated + ", currentOperation=" + currentOperation + ", targetLock=" + targetLock + "]"; } - + } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java index 47275c6da..ba2df3358 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java @@ -25,6 +25,7 @@ import java.sql.Timestamp; import java.time.Instant; import java.util.AbstractMap; import java.util.LinkedList; +import java.util.List; import java.util.Properties; import javax.persistence.EntityManager; @@ -53,13 +54,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopOperationManager implements Serializable { - - /** - * - */ private static final long serialVersionUID = -3773199283624595410L; private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class); + private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name"; + private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name"; + private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id"; + @Override public String toString() { return "ControlLoopOperationManager [onset=" + (onset != null ? onset.getRequestID() : "null") + ", policy=" @@ -73,7 +74,6 @@ public class ControlLoopOperationManager implements Serializable { // These properties are not changeable, but accessible // for Drools Rule statements. // - //public final ATTControlLoopEvent onset; public final ControlLoopEvent onset; public final transient Policy policy; @@ -82,7 +82,7 @@ public class ControlLoopOperationManager implements Serializable { // private int attempts = 0; private transient Operation currentOperation = null; - private LinkedList<Operation> operationHistory = new LinkedList<Operation>(); + private LinkedList<Operation> operationHistory = new LinkedList<>(); private PolicyResult policyResult = null; private ControlLoopEventManager eventManager = null; private String targetEntity; @@ -96,20 +96,20 @@ public class ControlLoopOperationManager implements Serializable { } public String getTargetEntity() { - return this.targetEntity; + return this.targetEntity; } // // Internal class used for tracking // private class Operation { - public ControlLoopOperation operation = new ControlLoopOperation(); - public PolicyResult policyResult = null; - public int attempt = 0; + private ControlLoopOperation clOperation = new ControlLoopOperation(); + private PolicyResult policyResult = null; + private int attempt = 0; @Override public String toString() { - return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation + return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + clOperation + "]"; } } @@ -129,79 +129,75 @@ public class ControlLoopOperationManager implements Serializable { } public String getTarget(Policy policy) throws ControlLoopException, AAIException { - if (policy.getTarget() != null) { - if (policy.getTarget().getType() != null) { - switch(policy.getTarget().getType()) { - case PNF: - break; - case VM: - case VNF: - VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset; - if (this.onset.getTarget().equalsIgnoreCase("vserver.vserver-name")) { - return virtualOnset.getAAI().get("vserver.vserver-name"); - } - else if (this.onset.getTarget().equalsIgnoreCase("generic-vnf.vnf-id")) { - return virtualOnset.getAAI().get("generic-vnf.vnf-id"); - } - else if (this.onset.getTarget().equalsIgnoreCase("generic-vnf.vnf-name")) { - /* - * If the onset is enriched with the vnf-id, - * we don't need an A&AI response - */ - if (virtualOnset.getAAI().containsKey("generic-vnf.vnf-id")) { - return virtualOnset.getAAI().get("generic-vnf.vnf-id"); - } - - /* - * If the vnf-name was retrieved from the onset then the vnf-id - * must be obtained from the event manager's A&AI GET query - */ - String vnfId = this.eventManager.getVnfResponse().getVnfID(); - if (vnfId == null) { - throw new AAIException("No vnf-id found"); - } - return vnfId; - } - break; - default: - throw new ControlLoopException("The target type is not supported"); - } - } - else { - throw new ControlLoopException("The target type is null"); - } - } - else { - throw new ControlLoopException("The target is null"); - } - throw new ControlLoopException("Target does not match target type"); - } - + if (policy.getTarget() == null) { + throw new ControlLoopException("The target is null"); + } + + if (policy.getTarget().getType() == null) { + throw new ControlLoopException("The target type is null"); + } + + switch(policy.getTarget().getType()) { + case PNF: + throw new ControlLoopException("PNF target is not supported"); + case VM: + case VNF: + VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset; + if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) { + return virtualOnset.getAAI().get(VSERVER_VSERVER_NAME); + } + else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) { + return virtualOnset.getAAI().get(GENERIC_VNF_VNF_ID); + } + else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) { + /* + * If the onset is enriched with the vnf-id, + * we don't need an A&AI response + */ + if (virtualOnset.getAAI().containsKey(GENERIC_VNF_VNF_ID)) { + return virtualOnset.getAAI().get(GENERIC_VNF_VNF_ID); + } + + /* + * If the vnf-name was retrieved from the onset then the vnf-id + * must be obtained from the event manager's A&AI GET query + */ + String vnfId = this.eventManager.getVnfResponse().getVnfID(); + if (vnfId == null) { + throw new AAIException("No vnf-id found"); + } + return vnfId; + } + throw new ControlLoopException("Target does not match target type"); + default: + throw new ControlLoopException("The target type is not supported"); + } + } + public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException, AAIException { this.onset = onset; this.policy = policy; this.guardApprovalStatus = "NONE"; this.eventManager = em; this.targetEntity = getTarget(policy); - + // // Let's make a sanity check // switch (policy.getActor()) { case "APPC": - if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { - /* - * The target vnf-id may not be the same as the source vnf-id - * specified in the yaml, the target vnf-id is retrieved by - * a named query to A&AI. - */ - String targetVnf = AppcLcmActorServiceProvider.vnfNamedQuery( - policy.getTarget().getResourceID(), this.targetEntity); - this.targetEntity = targetVnf; - } + if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { + /* + * The target vnf-id may not be the same as the source vnf-id + * specified in the yaml, the target vnf-id is retrieved by + * a named query to A&AI. + */ + String targetVnf = AppcLcmActorServiceProvider.vnfNamedQuery( policy.getTarget().getResourceID(), this.targetEntity); + this.targetEntity = targetVnf; + } break; case "SO": - break; + break; case "VFC": break; default: @@ -209,85 +205,46 @@ public class ControlLoopOperationManager implements Serializable { } } - public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) throws AAIException { - // - // They shouldn't call us if we currently running something - // - if (this.currentOperation != null) { - // - // what do we do if we are already running an operation? - // - return null; - } - // - // Check if we have maxed out on retries - // - if (this.policy.getRetry() == null || this.policy.getRetry() < 1) { - // - // No retries are allowed, so check have we even made - // one attempt to execute the operation? - // - if (this.attempts >= 1) { - // - // We have, let's ensure our PolicyResult is set - // - if (this.policyResult == null) { - this.policyResult = PolicyResult.FAILURE_RETRIES; - } - // - // - // - return null; - } - } else { - // - // Have we maxed out on retries? - // - if (this.attempts > this.policy.getRetry()) { - if (this.policyResult == null) { - this.policyResult = PolicyResult.FAILURE_RETRIES; - } - return null; - } - } + public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) throws ControlLoopException{ + verifyOperatonCanRun(); + // // Setup // this.policyResult = null; Operation operation = new Operation(); operation.attempt = ++this.attempts; - operation.operation.setActor(this.policy.getActor()); - operation.operation.setOperation(this.policy.getRecipe()); - operation.operation.setTarget(this.policy.getTarget().toString()); - operation.operation.setSubRequestId(Integer.toString(operation.attempt)); + operation.clOperation.setActor(this.policy.getActor()); + operation.clOperation.setOperation(this.policy.getRecipe()); + operation.clOperation.setTarget(this.policy.getTarget().toString()); + operation.clOperation.setSubRequestId(Integer.toString(operation.attempt)); // // Now determine which actor we need to construct a request for // switch (policy.getActor()) { case "APPC": - /* - * If the recipe is ModifyConfig, a legacy APPC - * request is constructed. Otherwise an LCMRequest - * is constructed. - */ + /* + * If the recipe is ModifyConfig, a legacy APPC + * request is constructed. Otherwise an LCMRequest + * is constructed. + */ this.currentOperation = operation; - if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { - - this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, - operation.operation, this.policy, this.targetEntity); - } - else { - this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, - operation.operation, this.policy, this.targetEntity); - } + if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { + this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, + operation.clOperation, this.policy, this.targetEntity); + } + else { + this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, + operation.clOperation, this.policy, this.targetEntity); + } // // Save the operation // - + return operationRequest; case "SO": - SOActorServiceProvider SOAsp = new SOActorServiceProvider(); - this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy); + SOActorServiceProvider soActorSP = new SOActorServiceProvider(); + this.operationRequest = soActorSP.constructRequest((VirtualControlLoopEvent)onset, operation.clOperation, this.policy); // Save the operation this.currentOperation = operation; @@ -298,182 +255,224 @@ public class ControlLoopOperationManager implements Serializable { return operationRequest; case "VFC": - this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy, this.eventManager.getVnfResponse()); - this.currentOperation = operation; - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - return operationRequest; - + this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.eventManager.getVnfResponse()); + this.currentOperation = operation; + if (this.operationRequest == null) { + this.policyResult = PolicyResult.FAILURE; + } + return operationRequest; + default: + throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy"); } - return null; } - public PolicyResult onResponse(Object response) { + public PolicyResult onResponse(Object response) { // // Which response is it? // if (response instanceof Response) { // - // Cast it + // Cast APPC response and handle it // - Response appcResponse = (Response) response; + return onResponse((Response) response); + } + else if (response instanceof LCMResponseWrapper) { // - // Determine which subrequestID (ie. attempt) + // Cast LCM response and handle it // - Integer operationAttempt = null; - try { - operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestID()); - } catch (NumberFormatException e) { - // - // We cannot tell what happened if this doesn't exist - // - this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; - } + return onResponse((LCMResponseWrapper) response); + } + else if (response instanceof SOResponseWrapper) { // - // Sanity check the response message + // Cast SO response and handle it // - if (appcResponse.getStatus() == null) { - // - // We cannot tell what happened if this doesn't exist - // - this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; + return onResponse((SOResponseWrapper) response); + } + else if (response instanceof VFCResponse) { + // + // Cast VFC response and handle it + // + return onResponse((VFCResponse) response); + } + else { + return null; + } + } + + /** + * This method handles operation responses from APPC + * @param appcResponse the APPC response + * @return The result of the response handling + */ + private PolicyResult onResponse(Response appcResponse) { + // + // Determine which subrequestID (ie. attempt) + // + Integer operationAttempt = null; + try { + operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestID()); + } catch (NumberFormatException e) { + // + // We cannot tell what happened if this doesn't exist + // + this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; + } + // + // Sanity check the response message + // + if (appcResponse.getStatus() == null) { + // + // We cannot tell what happened if this doesn't exist + // + this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; + } + // + // Get the Response Code + // + ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode()); + if (code == null) { + // + // We are unaware of this code + // + this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; + } + // + // Ok, let's figure out what APP-C's response is + // + switch (code) { + case ACCEPT: + // + // This is good, they got our original message and + // acknowledged it. + // + // Is there any need to track this? + // + return null; + case ERROR: + case REJECT: + // + // We'll consider these two codes as exceptions + // + this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.FAILURE_EXCEPTION); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; } + return PolicyResult.FAILURE_EXCEPTION; + case SUCCESS: // - // Get the Response Code // - ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode()); - if (code == null) { - // - // We are unaware of this code - // - this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; + // + this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.SUCCESS); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; } + return PolicyResult.SUCCESS; + case FAILURE: // - // Ok, let's figure out what APP-C's response is // - switch (code) { - case ACCEPT: - // - // This is good, they got our original message and - // acknowledged it. - // - // Is there any need to track this? - // + // + this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.FAILURE); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { return null; - case ERROR: - case REJECT: - // - // We'll consider these two codes as exceptions - // - this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.FAILURE_EXCEPTION); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.FAILURE_EXCEPTION; - case SUCCESS: - // - // - // - this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.SUCCESS); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.SUCCESS; - case FAILURE: - // - // - // - this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.FAILURE); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.FAILURE; } + return PolicyResult.FAILURE; + default: + return null; + } + } + + /** + * This method handles operation responses from LCM + * @param dmaapResponse the LCM response + * @return The result of the response handling + */ + private PolicyResult onResponse(LCMResponseWrapper dmaapResponse) { + /* + * Parse out the operation attempt using the subrequestid + */ + Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId()); + if (operationAttempt == null) { + this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION); } - else if (response instanceof LCMResponseWrapper) { - - LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response; - - /* - * Parse out the operation attempt using the subrequestid - */ - Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId()); - if (operationAttempt == null) { - this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION); - } - - /* - * Process the APPCLCM response to see what PolicyResult - * should be returned - */ - AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); - - if (result.getKey() != null) { - this.completeOperation(operationAttempt, result.getValue(), result.getKey()); - if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { - return null; - } - return result.getKey(); - } - return null; - } else if (response instanceof SOResponseWrapper) { - SOResponseWrapper msoResponse = (SOResponseWrapper) response; - - switch (msoResponse.getSoResponse().getHttpResponseCode()) { - case 200: - case 202: - // - // Consider it as success - // - this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success", PolicyResult.SUCCESS); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.SUCCESS; - default: - // - // Consider it as failure - // - this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed", PolicyResult.FAILURE); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.FAILURE; - } - } else if (response instanceof VFCResponse) { - VFCResponse vfcResponse = (VFCResponse) response; + /* + * Process the APPCLCM response to see what PolicyResult + * should be returned + */ + AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); - if (vfcResponse.getResponseDescriptor().getStatus().equalsIgnoreCase("finished")) { - // - // Consider it as success - // - this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.SUCCESS; - } else { - // - // Consider it as failure - // - this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - // increment operation attempts for retries - this.attempts += 1; - return PolicyResult.FAILURE; + if (result.getKey() != null) { + this.completeOperation(operationAttempt, result.getValue(), result.getKey()); + if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { + return null; } + return result.getKey(); } return null; } + + /** + * This method handles operation responses from SO + * @param msoResponse the SO response + * @return The result of the response handling + */ + private PolicyResult onResponse(SOResponseWrapper msoResponse) { + switch (msoResponse.getSoResponse().getHttpResponseCode()) { + case 200: + case 202: + // + // Consider it as success + // + this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success", PolicyResult.SUCCESS); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.SUCCESS; + default: + // + // Consider it as failure + // + this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed", PolicyResult.FAILURE); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.FAILURE; + } + } + + /** + * This method handles operation responses from VFC + * @param vfcResponse the VFC response + * @return The result of the response handling + */ + private PolicyResult onResponse(VFCResponse vfcResponse) { + if (vfcResponse.getResponseDescriptor().getStatus().equalsIgnoreCase("finished")) { + // + // Consider it as success + // + this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.SUCCESS; + } else { + // + // Consider it as failure + // + this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + // increment operation attempts for retries + this.attempts += 1; + return PolicyResult.FAILURE; + } + } - public Integer getOperationTimeout() { + public Integer getOperationTimeout() { // // Sanity check // @@ -485,7 +484,7 @@ public class ControlLoopOperationManager implements Serializable { return this.policy.getTimeout(); } - public String getOperationTimeoutString(int defaultTimeout) { + public String getOperationTimeoutString(int defaultTimeout) { Integer to = this.getOperationTimeout(); if (to == null || to == 0) { return Integer.toString(defaultTimeout) + "s"; @@ -497,67 +496,67 @@ public class ControlLoopOperationManager implements Serializable { return this.policyResult; } - public String getOperationMessage() { - if (this.currentOperation != null && this.currentOperation.operation != null) { - return this.currentOperation.operation.toMessage(); + public String getOperationMessage() { + if (this.currentOperation != null && this.currentOperation.clOperation != null) { + return this.currentOperation.clOperation.toMessage(); } if (!this.operationHistory.isEmpty()) { - return this.operationHistory.getLast().operation.toMessage(); + return this.operationHistory.getLast().clOperation.toMessage(); } return null; } - public String getOperationMessage(String guardResult) { - if (this.currentOperation != null && this.currentOperation.operation != null) { - return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult; + public String getOperationMessage(String guardResult) { + if (this.currentOperation != null && this.currentOperation.clOperation != null) { + return this.currentOperation.clOperation.toMessage()+ ", Guard result: " + guardResult; } - + if (!this.operationHistory.isEmpty()) { - return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult; + return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " + guardResult; } return null; } - public String getOperationHistory() { - if (this.currentOperation != null && this.currentOperation.operation != null) { - return this.currentOperation.operation.toHistory(); + public String getOperationHistory() { + if (this.currentOperation != null && this.currentOperation.clOperation != null) { + return this.currentOperation.clOperation.toHistory(); } - + if (!this.operationHistory.isEmpty()) { - return this.operationHistory.getLast().operation.toHistory(); + return this.operationHistory.getLast().clOperation.toHistory(); } return null; } - public LinkedList<ControlLoopOperation> getHistory() { - LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>(); + public List<ControlLoopOperation> getHistory() { + LinkedList<ControlLoopOperation> history = new LinkedList<>(); for (Operation op : this.operationHistory) { - history.add(new ControlLoopOperation(op.operation)); + history.add(new ControlLoopOperation(op.clOperation)); } return history; } - public void setOperationHasTimedOut() { + public void setOperationHasTimedOut() { // // // this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT); } - public void setOperationHasGuardDeny() { + public void setOperationHasGuardDeny() { // // // this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD); } - + public void setOperationHasException(String message) { this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION); } - public boolean isOperationComplete() { + public boolean isOperationComplete() { // // Is there currently a result? // @@ -609,6 +608,56 @@ public class ControlLoopOperationManager implements Serializable { return (this.currentOperation != null); } + /** + * This method verifies that the operation manager may run an operation. + * @return True if the operation can run, false otherwise + * @throws ControlLoopException if the operation cannot run + */ + private void verifyOperatonCanRun() throws ControlLoopException { + // + // They shouldn't call us if we currently running something + // + if (this.currentOperation != null) { + // + // what do we do if we are already running an operation? + // + throw new ControlLoopException("current operation is not null (an operation is already running)"); + } + // + // Check if we have maxed out on retries + // + if (this.policy.getRetry() == null || this.policy.getRetry() < 1) { + // + // No retries are allowed, so check have we even made + // one attempt to execute the operation? + // + if (this.attempts >= 1) { + // + // We have, let's ensure our PolicyResult is set + // + if (this.policyResult == null) { + this.policyResult = PolicyResult.FAILURE_RETRIES; + } + // + // + // + throw new ControlLoopException("current operation failed and retries are not allowed"); + } + } else { + // + // Have we maxed out on retries? + // + if (this.attempts > this.policy.getRetry()) { + if (this.policyResult == null) { + this.policyResult = PolicyResult.FAILURE_RETRIES; + } + throw new ControlLoopException("current oepration has failed after " + this.attempts + " retries"); + } + } + + return; + } + private boolean isRetriesMaxedOut() { if (policy.getRetry() == null || policy.getRetry() == 0) { // @@ -620,7 +669,7 @@ public class ControlLoopOperationManager implements Serializable { return (this.attempts > policy.getRetry()); } - private void storeOperationInDataBase(){ + private void storeOperationInDataBase(){ // Only store in DB if enabled boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled")); if( !guardEnabled ){ @@ -638,18 +687,18 @@ public class ControlLoopOperationManager implements Serializable { props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS)); props.put(PersistenceUnitProperties.CLASSLOADER, ControlLoopOperationManager.class.getClassLoader()); } - - - String OpsHistPU = System.getProperty("OperationsHistoryPU"); - if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){ - OpsHistPU = "OperationsHistoryPU"; + + + String opsHistPU = System.getProperty("OperationsHistoryPU"); + if(opsHistPU == null || !opsHistPU.equals("TestOperationsHistoryPU")){ + opsHistPU = "OperationsHistoryPU"; } else{ props.clear(); } EntityManager em; try{ - em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager(); + em = Persistence.createEntityManagerFactory(opsHistPU, props).createEntityManager(); }catch(Exception e){ logger.error("storeOperationInDataBase threw: ", e); return; @@ -657,27 +706,24 @@ public class ControlLoopOperationManager implements Serializable { OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry(); - newEntry.closedLoopName = this.onset.getClosedLoopControlName(); - newEntry.requestId = this.onset.getRequestID().toString(); - newEntry.actor = this.currentOperation.operation.getActor(); - newEntry.operation = this.currentOperation.operation.getOperation(); - newEntry.target = this.targetEntity; - newEntry.starttime = Timestamp.from(this.currentOperation.operation.getStart()); - newEntry.subrequestId = this.currentOperation.operation.getSubRequestId(); - newEntry.endtime = new Timestamp(this.currentOperation.operation.getEnd().toEpochMilli()); - newEntry.message = this.currentOperation.operation.getMessage(); - newEntry.outcome = this.currentOperation.operation.getOutcome(); + newEntry.setClosedLoopName(this.onset.getClosedLoopControlName()); + newEntry.setRequestId(this.onset.getRequestID().toString()); + newEntry.setActor(this.currentOperation.clOperation.getActor()); + newEntry.setOperation(this.currentOperation.clOperation.getOperation()); + newEntry.setTarget(this.targetEntity); + newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart())); + newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId()); + newEntry.setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli())); + newEntry.setMessage(this.currentOperation.clOperation.getMessage()); + newEntry.setOutcome(this.currentOperation.clOperation.getOutcome()); em.getTransaction().begin(); em.persist(newEntry); em.getTransaction().commit(); em.close(); - } - - private void completeOperation(Integer attempt, String message, PolicyResult result) { if (attempt == null) { logger.debug("attempt cannot be null (i.e. subRequestID)"); @@ -685,9 +731,9 @@ public class ControlLoopOperationManager implements Serializable { } if (this.currentOperation != null) { if (this.currentOperation.attempt == attempt.intValue()) { - this.currentOperation.operation.setEnd(Instant.now()); - this.currentOperation.operation.setMessage(message); - this.currentOperation.operation.setOutcome(result.toString()); + this.currentOperation.clOperation.setEnd(Instant.now()); + this.currentOperation.clOperation.setMessage(message); + this.currentOperation.clOperation.setOutcome(result.toString()); this.currentOperation.policyResult = result; // // Save it in history @@ -708,9 +754,9 @@ public class ControlLoopOperationManager implements Serializable { } for (Operation op : this.operationHistory) { if (op.attempt == attempt.intValue()) { - op.operation.setEnd(Instant.now()); - op.operation.setMessage(message); - op.operation.setOutcome(result.toString()); + op.clOperation.setEnd(Instant.now()); + op.clOperation.setMessage(message); + op.clOperation.setOutcome(result.toString()); op.policyResult = result; return; } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java index 82775053e..30273d377 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java @@ -29,14 +29,9 @@ import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; - @Entity @Table(name="operationshistory10") -public class OperationsHistoryDbEntry implements Serializable{ - - /** - * - */ +public class OperationsHistoryDbEntry implements Serializable { private static final long serialVersionUID = 1L; @Id@GeneratedValue @@ -44,26 +39,83 @@ public class OperationsHistoryDbEntry implements Serializable{ public long rowid; @Column(name="CLNAME") - public String closedLoopName; - - public String requestId; - - public String actor; - - public String operation; - - public String target; + private String closedLoopName; - public Timestamp starttime; - - public Timestamp endtime; - - public String subrequestId; - - public String outcome; - - public String message; - + private String requestId; + private String actor; + private String operation; + private String target; + private Timestamp starttime; + private Timestamp endtime; + private String subrequestId; + private String outcome; + private String message; + public long getRowid() { + return rowid; + } + public void setRowid(long rowid) { + this.rowid = rowid; + } + public String getClosedLoopName() { + return closedLoopName; + } + public void setClosedLoopName(String closedLoopName) { + this.closedLoopName = closedLoopName; + } + public String getRequestId() { + return requestId; + } + public void setRequestId(String requestId) { + this.requestId = requestId; + } + public String getActor() { + return actor; + } + public void setActor(String actor) { + this.actor = actor; + } + public String getOperation() { + return operation; + } + public void setOperation(String operation) { + this.operation = operation; + } + public String getTarget() { + return target; + } + public void setTarget(String target) { + this.target = target; + } + public Timestamp getStarttime() { + return starttime; + } + public void setStarttime(Timestamp starttime) { + this.starttime = starttime; + } + public Timestamp getEndtime() { + return endtime; + } + public void setEndtime(Timestamp endtime) { + this.endtime = endtime; + } + public String getSubrequestId() { + return subrequestId; + } + public void setSubrequestId(String subrequestId) { + this.subrequestId = subrequestId; + } + public String getOutcome() { + return outcome; + } + public void setOutcome(String outcome) { + this.outcome = outcome; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java index acf7f1d22..33042a915 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java @@ -24,10 +24,6 @@ package org.onap.policy.controlloop.impl; import org.onap.policy.controlloop.ControlLoopLogger; public class ControlLoopLoggerStdOutImpl implements ControlLoopLogger { - - public ControlLoopLoggerStdOutImpl() { - } - @Override public void info(String... parameters) { StringBuilder builder = new StringBuilder(); @@ -47,5 +43,4 @@ public class ControlLoopLoggerStdOutImpl implements ControlLoopLogger { public void metrics(Object obj) { this.info(obj.toString()); } - } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java index 37721a9a1..eb50ac36e 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java @@ -23,14 +23,8 @@ package org.onap.policy.controlloop.impl; import org.onap.policy.controlloop.ControlLoopPublisher; public class ControlLoopPublisherJUnitImpl implements ControlLoopPublisher { - - public ControlLoopPublisherJUnitImpl() { - - } - @Override public void publish(Object object) { - + throw new UnsupportedOperationException("publish() method is not implemented on " + this.getClass().getCanonicalName()); } - } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java index f2c565d9a..451244392 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java @@ -31,80 +31,76 @@ import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor; public class ControlLoopProcessor { - private final String yaml; - private final ControlLoopPolicy policy; - private String currentPolicy = null; + private final String yaml; + private final ControlLoopPolicy policy; + private String currentNestedPolicyID = null; - public ControlLoopProcessor(String yaml) throws ControlLoopException { - this.yaml = yaml; - try { - final Yaml y = new Yaml(new CustomClassLoaderConstructor(ControlLoopPolicy.class, - ControlLoopPolicy.class.getClassLoader())); - final Object obj = y.load(this.yaml); - if (obj instanceof ControlLoopPolicy) { - this.policy = (ControlLoopPolicy) obj; - this.currentPolicy = this.policy.getControlLoop().getTrigger_policy(); - } else { - this.policy = null; - throw new ControlLoopException("Unable to parse yaml into ControlLoopPolicy object"); - } - } catch (final Exception e) { - // - // Most likely this is a YAML Exception - // - throw new ControlLoopException(e); - } - } + public ControlLoopProcessor(String yaml) throws ControlLoopException { + this.yaml = yaml; + try { + final Yaml y = new Yaml(new CustomClassLoaderConstructor(ControlLoopPolicy.class, ControlLoopPolicy.class.getClassLoader())); + final Object obj = y.load(this.yaml); - public ControlLoop getControlLoop() { - return this.policy.getControlLoop(); - } + this.policy = (ControlLoopPolicy) obj; + this.currentNestedPolicyID = this.policy.getControlLoop().getTrigger_policy(); + } catch (final Exception e) { + // + // Most likely this is a YAML Exception + // + throw new ControlLoopException(e); + } + } - public FinalResult checkIsCurrentPolicyFinal() { - return FinalResult.toResult(this.currentPolicy); - } + public ControlLoop getControlLoop() { + return this.policy.getControlLoop(); + } - public Policy getCurrentPolicy() { - for (final Policy policy : this.policy.getPolicies()) { - if (policy.getId().equals(this.currentPolicy)) { - return policy; - } - } - return null; - } + public FinalResult checkIsCurrentPolicyFinal() { + return FinalResult.toResult(this.currentNestedPolicyID); + } - public void nextPolicyForResult(PolicyResult result) throws ControlLoopException { - final Policy policy = this.getCurrentPolicy(); - try { - if (this.policy == null) { - throw new ControlLoopException("There is no current policy to determine where to go to."); - } - switch (result) { - case SUCCESS: - this.currentPolicy = policy.getSuccess(); - break; - case FAILURE: - this.currentPolicy = policy.getFailure(); - break; - case FAILURE_TIMEOUT: - this.currentPolicy = policy.getFailure_timeout(); - break; - case FAILURE_RETRIES: - this.currentPolicy = policy.getFailure_retries(); - break; - case FAILURE_EXCEPTION: - this.currentPolicy = policy.getFailure_exception(); - break; - case FAILURE_GUARD: - this.currentPolicy = policy.getFailure_guard(); - break; - default: - throw new ControlLoopException("Bad policy result given: " + result); - } - } catch (final ControlLoopException e) { - this.currentPolicy = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); - throw e; - } - } + public Policy getCurrentPolicy() throws ControlLoopException { + if (this.policy == null || this.policy.getPolicies() == null) { + throw new ControlLoopException("There are no policies defined."); + } + for (final Policy nestedPolicy : this.policy.getPolicies()) { + if (nestedPolicy.getId().equals(this.currentNestedPolicyID)) { + return nestedPolicy; + } + } + return null; + } + + public void nextPolicyForResult(PolicyResult result) throws ControlLoopException { + final Policy currentPolicy = this.getCurrentPolicy(); + try { + if (currentPolicy == null) { + throw new ControlLoopException("There is no current policy to determine where to go to."); + } + switch (result) { + case SUCCESS: + this.currentNestedPolicyID = currentPolicy.getSuccess(); + break; + case FAILURE: + this.currentNestedPolicyID = currentPolicy.getFailure(); + break; + case FAILURE_TIMEOUT: + this.currentNestedPolicyID = currentPolicy.getFailure_timeout(); + break; + case FAILURE_RETRIES: + this.currentNestedPolicyID = currentPolicy.getFailure_retries(); + break; + case FAILURE_EXCEPTION: + this.currentNestedPolicyID = currentPolicy.getFailure_exception(); + break; + case FAILURE_GUARD: + this.currentNestedPolicyID = currentPolicy.getFailure_guard(); + break; + } + } catch (final ControlLoopException e) { + this.currentNestedPolicyID = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + throw e; + } + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java index 07a273cc7..7acaf370d 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java @@ -20,7 +20,5 @@ package org.onap.policy.drools; public interface PolicyEngine { - public boolean deliver(String busType, String topic, Object obj); - } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java index 216f819ca..5bd5d8d2c 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java @@ -21,7 +21,6 @@ package org.onap.policy.drools; public interface PolicyEngineListener { - /** * Any class that implements this interface will * be notified of a new event on the queue in the @@ -31,5 +30,4 @@ public interface PolicyEngineListener { * the event */ public void newEventNotification(String topic); - } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java index 36feaaf93..e94657fee 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java @@ -40,50 +40,51 @@ import org.onap.policy.drools.PolicyEngineListener; public class PolicyEngineJUnitImpl implements PolicyEngine { private static final Logger logger = LoggerFactory.getLogger(PolicyEngineJUnitImpl.class); - private Map<String, Map<String, Queue<Object>>> busMap = new HashMap<String, Map<String, Queue<Object>>>(); + private Map<String, Map<String, Queue<Object>>> busMap = new HashMap<>(); private List<PolicyEngineListener> listeners = new ArrayList<>(); - + /** * Adds all objects that implement PolicyEngineListener - * to the notification list when an event occurs - * + * to the notification list when an event occurs + * * @param listener an object that is interest in knowing * about events published to the PolicyEngine */ public void addListener(PolicyEngineListener listener) { - listeners.add(listener); + listeners.add(listener); } - + /** * Notifies all listeners about a new event * @param topic the topic in which the notification * was sent to */ public void notifyListeners(String topic) { - for (PolicyEngineListener listener: listeners) { - listener.newEventNotification(topic); - } + for (PolicyEngineListener listener: listeners) { + listener.newEventNotification(topic); + } } - + @Override public boolean deliver(String busType, String topic, Object obj) { if (obj instanceof ControlLoopNotification) { ControlLoopNotification notification = (ControlLoopNotification) obj; - //logger.debug("Notification: " + notification.notification + " " + (notification.message == null ? "" : notification.message) + " " + notification.history); - logger.debug(Serialization.gsonPretty.toJson(notification)); + if (logger.isDebugEnabled()) { + logger.debug(Serialization.gsonPretty.toJson(notification)); + } } if (obj instanceof Request) { Request request = (Request) obj; logger.debug("Request: {} subrequest {}", request.getAction(), request.getCommonHeader().getSubRequestID()); } else if (obj instanceof LCMRequestWrapper) { - LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj; - logger.debug("Request: {} subrequest {}", dmaapRequest.getBody().getAction(), dmaapRequest.getBody().getCommonHeader().getSubRequestId()); + LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj; + logger.debug("Request: {} subrequest {}", dmaapRequest.getBody().getAction(), dmaapRequest.getBody().getCommonHeader().getSubRequestId()); } // // Does the bus exist? // - if (busMap.containsKey(busType) == false) { + if (!busMap.containsKey(busType)) { logger.debug("creating new bus type {}", busType); // // Create the bus @@ -97,7 +98,7 @@ public class PolicyEngineJUnitImpl implements PolicyEngine { // // Does the topic exist? // - if (topicMap.containsKey(topic) == false) { + if (!topicMap.containsKey(topic)) { logger.debug("creating new topic {}", topic); // // Create the topic @@ -112,8 +113,8 @@ public class PolicyEngineJUnitImpl implements PolicyEngine { notifyListeners(topic); return res; } - - public Object subscribe(String busType, String topic) { + + public Object subscribe(String busType, String topic) { // // Does the bus exist? // diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java new file mode 100644 index 000000000..58860435a --- /dev/null +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * eventmanager + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop; + +import static org.junit.Assert.*; + +import java.io.IOException; + +import org.junit.Test; + +public class ControlLoopExceptionTest { + + @Test + public void testControlLoopException() { + assertNotNull(new ControlLoopException()); + assertNotNull(new ControlLoopException("In Oz")); + assertNotNull(new ControlLoopException(new IOException())); + assertNotNull(new ControlLoopException("In Oz", new IOException())); + assertNotNull(new ControlLoopException("In Oz", new IOException(), false, false)); + } +} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java new file mode 100644 index 000000000..25208fe32 --- /dev/null +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * eventmanager + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.policy.controlloop.ControlLoopException; +import org.onap.policy.controlloop.ControlLoopLogger; +import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl; + +public class ControlLoopLoggerTest { + @Test + public void testControlLoopLogger() throws ControlLoopException { + ControlLoopLogger logger = new ControlLoopLogger.Factory().buildLogger(ControlLoopLoggerStdOutImpl.class.getCanonicalName()); + assertNotNull(logger); + logger.info("a log message", "and another", " and another"); + logger.metrics("a metric", "and another", " and another"); + logger.metrics(Double.valueOf(3)); + + try { + new ControlLoopLogger.Factory().buildLogger("java.lang.String"); + fail("test should throw an exception here"); + } + catch (Exception e) { + assertEquals("Cannot load class java.lang.String as a control loop logger", e.getMessage()); + } + } +} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java new file mode 100644 index 000000000..3548ab841 --- /dev/null +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * eventmanager + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.policy.controlloop.ControlLoopException; +import org.onap.policy.controlloop.impl.ControlLoopPublisherJUnitImpl; + +public class ControlLoopPublisherTest { + @Test + public void testControlLoopPublisher() throws ControlLoopException { + ControlLoopPublisher publisher = new ControlLoopPublisher.Factory().buildLogger(ControlLoopPublisherJUnitImpl.class.getCanonicalName()); + assertNotNull(publisher); + + try { + publisher.publish(Double.valueOf(3)); + fail("test should throw an exception here"); + } + catch (Exception e) { + assertEquals("publish() method is not implemented on org.onap.policy.controlloop.impl.ControlLoopPublisherJUnitImpl", e.getMessage()); + } + + try { + new ControlLoopPublisher.Factory().buildLogger("java.lang.String"); + fail("test should throw an exception here"); + } + catch (Exception e) { + assertEquals("Cannot load class java.lang.String as a control loop publisher", e.getMessage()); + } + } +} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java index d4083150d..1df4a4f27 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java @@ -23,12 +23,19 @@ package org.onap.policy.controlloop.eventmanager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.HashMap; import java.util.UUID; +import org.apache.commons.io.IOUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -47,15 +54,21 @@ import org.onap.policy.controlloop.ControlLoopNotificationType; import org.onap.policy.controlloop.Util; import org.onap.policy.controlloop.VirtualControlLoopEvent; import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager.NEW_EVENT_STATUS; import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.PolicyResult; import org.onap.policy.drools.http.server.HttpServletServer; -import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.guard.GuardResult; +import org.onap.policy.guard.PolicyGuard; +import org.onap.policy.guard.PolicyGuard.LockResult; +import org.onap.policy.guard.TargetLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopEventManagerTest { private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManagerTest.class); - + private static VirtualControlLoopEvent onset; static { onset = new VirtualControlLoopEvent(); @@ -69,7 +82,7 @@ public class ControlLoopEventManagerTest { onset.getAAI().put("generic-vnf.vnf-id", "83f674e8-7555-44d7-9a39-bdc3770b0491"); onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); } - + @BeforeClass public static void setUpSimulator() { try { @@ -86,7 +99,7 @@ public class ControlLoopEventManagerTest { public static void tearDownSimulator() { HttpServletServer.factory.destroy(); } - + @Test public void testAAIVnfInfo() { final Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml("src/test/resources/test.yaml"); @@ -103,7 +116,7 @@ public class ControlLoopEventManagerTest { fail(e.getMessage()); } } - + @Test public void testAAIVnfInfo2() { final Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml("src/test/resources/test.yaml"); @@ -120,7 +133,7 @@ public class ControlLoopEventManagerTest { fail(e.getMessage()); } } - + @Test public void testAAIVserver() { final Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml("src/test/resources/test.yaml"); @@ -145,7 +158,7 @@ public class ControlLoopEventManagerTest { // final Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml("src/test/resources/test.yaml"); onset.setClosedLoopControlName(pair.a.getControlLoop().getControlLoopName()); - + try { logger.info("testIsClosedLoopDisabled --"); AAIGETVnfResponse response = getQueryByVnfID2(PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/network/generic-vnfs/generic-vnf/", @@ -153,64 +166,68 @@ public class ControlLoopEventManagerTest { PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), "5e49ca06-2972-4532-9ed4-6d071588d792"); assertNotNull(response); - boolean disabled = ControlLoopEventManager.isClosedLoopDisabled(response); - logger.info("QueryByVnfID - isClosedLoopDisabled: " + disabled); + + // TODO: Handle this + //boolean disabled = ControlLoopEventManager.isClosedLoopDisabled(response); + //logger.info("QueryByVnfID - isClosedLoopDisabled: " + disabled); response = getQueryByVnfName2(PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=", PolicyEngine.manager.getEnvironmentProperty("aai.username"), PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), "lll_vnf_010317"); assertNotNull(response); - disabled = ControlLoopEventManager.isClosedLoopDisabled(response); - logger.info("QueryByVnfName - isClosedLoopDisabled: " + disabled); + // TODO: Handle this + //disabled = ControlLoopEventManager.isClosedLoopDisabled(response); + //logger.info("QueryByVnfName - isClosedLoopDisabled: " + disabled); AAIGETVserverResponse response2 = getQueryByVserverName2(PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/nodes/vservers?vserver-name=", PolicyEngine.manager.getEnvironmentProperty("aai.user"), PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), "USMSO1SX7NJ0103UJZZ01-vjunos0"); assertNotNull(response2); - disabled = ControlLoopEventManager.isClosedLoopDisabled(response2); - logger.info("QueryByVserverName - isClosedLoopDisabled: " + disabled); + // TODO: Handle this + //disabled = ControlLoopEventManager.isClosedLoopDisabled(response2); + //logger.info("QueryByVserverName - isClosedLoopDisabled: " + disabled); } catch (Exception e) { fail(e.getMessage()); } - } - + } + @Test public void abatemetCheckEventSyntaxTest() { VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("abatementAAI"); - event.setRequestID(UUID.randomUUID()); - event.setTarget("generic-vnf.vnf-id"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED); - ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - assertNull(manager.getVnfResponse()); - assertNull(manager.getVserverResponse()); - try { + event.setClosedLoopControlName("abatementAAI"); + event.setRequestID(UUID.randomUUID()); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED); + ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + assertNull(manager.getVnfResponse()); + assertNull(manager.getVserverResponse()); + try { manager.checkEventSyntax(event); } catch (ControlLoopException e) { logger.debug("ControlLoopException in abatemetCheckEventSyntaxTest: "+e.getMessage()); e.printStackTrace(); fail("Exception in check event syntax"); } - assertNull(manager.getVnfResponse()); - assertNull(manager.getVserverResponse()); - + assertNull(manager.getVnfResponse()); + assertNull(manager.getVserverResponse()); + - event.setAAI(new HashMap<>()); - event.getAAI().put("generic-vnf.vnf-name", "abatementTest"); - try { + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "abatementTest"); + try { manager.checkEventSyntax(event); } catch (ControlLoopException e) { logger.debug("ControlLoopException in abatemetCheckEventSyntaxTest: "+e.getMessage()); e.printStackTrace(); fail("Exception in check event syntax"); } - assertNull(manager.getVnfResponse()); - assertNull(manager.getVserverResponse()); + assertNull(manager.getVnfResponse()); + assertNull(manager.getVserverResponse()); } - + @Test public void subsequentOnsetTest() { UUID requestId = UUID.randomUUID(); @@ -218,59 +235,59 @@ public class ControlLoopEventManagerTest { event.setClosedLoopControlName("TwoOnsetTest"); event.setRequestID(requestId); event.setTarget("generic-vnf.vnf-id"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAAI(new HashMap<>()); - event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - VirtualControlLoopNotification notification = manager.activate(event); - - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopEventManager.NEW_EVENT_STATUS status = null; - try { - status = manager.onNewEvent(event); - } catch (AAIException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } - assertNotNull(status); - assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); - - AAIGETVnfResponse response = manager.getVnfResponse(); - assertNotNull(response); - assertNull(manager.getVserverResponse()); - - VirtualControlLoopEvent event2 = new VirtualControlLoopEvent(); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(event); + + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + ControlLoopEventManager.NEW_EVENT_STATUS status = null; + try { + status = manager.onNewEvent(event); + } catch (AAIException e) { + logger.warn(e.toString()); + fail("A&AI Query Failed"); + } + assertNotNull(status); + assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); + + AAIGETVnfResponse response = manager.getVnfResponse(); + assertNotNull(response); + assertNull(manager.getVserverResponse()); + + VirtualControlLoopEvent event2 = new VirtualControlLoopEvent(); event2.setClosedLoopControlName("TwoOnsetTest"); event2.setRequestID(requestId); event2.setTarget("generic-vnf.vnf-id"); - event2.setClosedLoopAlarmStart(Instant.now()); - event2.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event2.setAAI(new HashMap<>()); - event2.getAAI().put("generic-vnf.vnf-name", "onsetTwo"); - - - try { - status = manager.onNewEvent(event2); - } catch (AAIException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } - assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.SUBSEQUENT_ONSET, status); - AAIGETVnfResponse response2 = manager.getVnfResponse(); - assertNotNull(response2); - // We should not have queried AAI, so the stored response should be the same - assertEquals(response, response2); - assertNull(manager.getVserverResponse()); + event2.setClosedLoopAlarmStart(Instant.now()); + event2.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event2.setAAI(new HashMap<>()); + event2.getAAI().put("generic-vnf.vnf-name", "onsetTwo"); + + + try { + status = manager.onNewEvent(event2); + } catch (AAIException e) { + logger.warn(e.toString()); + fail("A&AI Query Failed"); + } + assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.SUBSEQUENT_ONSET, status); + AAIGETVnfResponse response2 = manager.getVnfResponse(); + assertNotNull(response2); + // We should not have queried AAI, so the stored response should be the same + assertEquals(response, response2); + assertNull(manager.getVserverResponse()); } - + // Simulate a response public static AAIGETVnfResponse getQueryByVnfID2(String urlGet, String username, String password, UUID requestID, String key) { AAIGETVnfResponse response = new AAIGETVnfResponse(); - + response.setVnfID("83f674e8-7555-44d7-9a39-bdc3770b0491"); response.setVnfName("lll_vnf_010317"); response.setVnfType("Basa-122216-Service/VidVsamp12BaseVolume 1"); @@ -280,44 +297,44 @@ public class ControlLoopEventManagerTest { response.setIsClosedLoopDisabled("false"); response.setResourceVersion("1494001988835"); response.setModelInvariantId("f18be3cd-d446-456e-9109-121d9b62feaa"); - - RelationshipList relationshipList = new RelationshipList(); - Relationship relationship = new Relationship(); - RelationshipData relationshipData = new RelationshipData(); - RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); - - relationshipDataItem.setRelationshipKey ("customer.global-customer-id"); - relationshipDataItem.setRelationshipValue("MSO_1610_ST"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey ("service-subscription.service-type"); - relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey ("service-instance.service-instance-id"); - relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - RelatedToProperty relatedToProperty = new RelatedToProperty(); - RelatedToPropertyItem item = new RelatedToPropertyItem(); - item.setPropertyKey("service-instance.service-instance-name"); - item.setPropertyValue("lll_svc_010317"); - relatedToProperty.getRelatedTo().add(item); - - relationship.setRelatedTo("service-instance"); - relationship.setRelatedLink("/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationship.setRelationshipData(relationshipData); - relationship.setRelatedToProperty(relatedToProperty); - - relationshipList.getRelationshipList().add(relationship); - response.setRelationshipList(relationshipList); + + RelationshipList relationshipList = new RelationshipList(); + Relationship relationship = new Relationship(); + RelationshipData relationshipData = new RelationshipData(); + RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); + + relationshipDataItem.setRelationshipKey ("customer.global-customer-id"); + relationshipDataItem.setRelationshipValue("MSO_1610_ST"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey ("service-subscription.service-type"); + relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey ("service-instance.service-instance-id"); + relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + RelatedToProperty relatedToProperty = new RelatedToProperty(); + RelatedToPropertyItem item = new RelatedToPropertyItem(); + item.setPropertyKey("service-instance.service-instance-name"); + item.setPropertyValue("lll_svc_010317"); + relatedToProperty.getRelatedTo().add(item); + + relationship.setRelatedTo("service-instance"); + relationship.setRelatedLink("/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationship.setRelationshipData(relationshipData); + relationship.setRelatedToProperty(relatedToProperty); + + relationshipList.getRelationshipList().add(relationship); + response.setRelationshipList(relationshipList); return response; } public static AAIGETVnfResponse getQueryByVnfName2(String urlGet, String username, String password, UUID requestID, String key) { AAIGETVnfResponse response = new AAIGETVnfResponse(); - + response.setVnfID("83f674e8-7555-44d7-9a39-bdc3770b0491"); response.setVnfName("lll_vnf_010317"); response.setVnfType("Basa-122216-Service/VidVsamp12BaseVolume 1"); @@ -327,44 +344,44 @@ public class ControlLoopEventManagerTest { response.setIsClosedLoopDisabled("false"); response.setResourceVersion("1494001988835"); response.setModelInvariantId("f18be3cd-d446-456e-9109-121d9b62feaa"); - - RelationshipList relationshipList = new RelationshipList(); - Relationship relationship = new Relationship(); - RelationshipData relationshipData = new RelationshipData(); - RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); - - relationshipDataItem.setRelationshipKey("customer.global-customer-id"); - relationshipDataItem.setRelationshipValue("MSO_1610_ST"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey("service-subscription.service-type"); - relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); - relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - RelatedToProperty relatedToProperty = new RelatedToProperty(); - RelatedToPropertyItem item = new RelatedToPropertyItem(); - item.setPropertyKey("service-instance.service-instance-name"); - item.setPropertyValue("lll_svc_010317"); - relatedToProperty.getRelatedTo().add(item); - - relationship.setRelatedTo("service-instance"); - relationship.setRelatedLink("/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationship.setRelationshipData(relationshipData); - relationship.setRelatedToProperty(relatedToProperty); - - relationshipList.getRelationshipList().add(relationship); - response.setRelationshipList(relationshipList); + + RelationshipList relationshipList = new RelationshipList(); + Relationship relationship = new Relationship(); + RelationshipData relationshipData = new RelationshipData(); + RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); + + relationshipDataItem.setRelationshipKey("customer.global-customer-id"); + relationshipDataItem.setRelationshipValue("MSO_1610_ST"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey("service-subscription.service-type"); + relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); + relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + RelatedToProperty relatedToProperty = new RelatedToProperty(); + RelatedToPropertyItem item = new RelatedToPropertyItem(); + item.setPropertyKey("service-instance.service-instance-name"); + item.setPropertyValue("lll_svc_010317"); + relatedToProperty.getRelatedTo().add(item); + + relationship.setRelatedTo("service-instance"); + relationship.setRelatedLink("/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationship.setRelationshipData(relationshipData); + relationship.setRelatedToProperty(relatedToProperty); + + relationshipList.getRelationshipList().add(relationship); + response.setRelationshipList(relationshipList); return response; } public static AAIGETVserverResponse getQueryByVserverName2(String urlGet, String username, String password, UUID requestID, String key) { AAIGETVserverResponse response = new AAIGETVserverResponse(); - + response.setVserverID("d0668d4f-c25e-4a1b-87c4-83845c01efd8"); response.setVserverName("USMSO1SX7NJ0103UJZZ01-vjunos0"); response.setVserverName2("vjunos0"); @@ -372,38 +389,614 @@ public class ControlLoopEventManagerTest { response.setInMaint("false"); response.setIsClosedLoopDisabled("false"); response.setResourceVersion("1494001931513"); - - RelationshipList relationshipList = new RelationshipList(); - Relationship relationship = new Relationship(); - RelationshipData relationshipData = new RelationshipData(); - RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); - - relationshipDataItem.setRelationshipKey("customer.global-customer-id"); - relationshipDataItem.setRelationshipValue("MSO_1610_ST"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey("service-subscription.service-type"); - relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); - relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - RelatedToProperty relatedToProperty = new RelatedToProperty(); - RelatedToPropertyItem item = new RelatedToPropertyItem(); - item.setPropertyKey("service-instance.service-instance-name"); - item.setPropertyValue("lll_svc_010317"); - relatedToProperty.getRelatedTo().add(item); - - relationship.setRelatedTo("service-instance"); - relationship.setRelatedLink("/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationship.setRelationshipData(relationshipData); - relationship.setRelatedToProperty(relatedToProperty); - - relationshipList.getRelationshipList().add(relationship); - response.setRelationshipList(relationshipList); + + RelationshipList relationshipList = new RelationshipList(); + Relationship relationship = new Relationship(); + RelationshipData relationshipData = new RelationshipData(); + RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); + + relationshipDataItem.setRelationshipKey("customer.global-customer-id"); + relationshipDataItem.setRelationshipValue("MSO_1610_ST"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey("service-subscription.service-type"); + relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); + relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + RelatedToProperty relatedToProperty = new RelatedToProperty(); + RelatedToPropertyItem item = new RelatedToPropertyItem(); + item.setPropertyKey("service-instance.service-instance-name"); + item.setPropertyValue("lll_svc_010317"); + relatedToProperty.getRelatedTo().add(item); + + relationship.setRelatedTo("service-instance"); + relationship.setRelatedLink("/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationship.setRelationshipData(relationshipData); + relationship.setRelatedToProperty(relatedToProperty); + + relationshipList.getRelationshipList().add(relationship); + response.setRelationshipList(relationshipList); return response; } + + @Test + public void testMethods() { + ControlLoopEventManager clem = new ControlLoopEventManager("MyClosedLoopName", UUID.randomUUID()); + + clem.setActivated(true); + assertEquals(true, clem.isActivated()); + + clem.setControlLoopResult("SUCCESS"); + assertEquals("SUCCESS", clem.getControlLoopResult()); + + clem.setControlLoopTimedOut(); + assertEquals(true, clem.isControlLoopTimedOut()); + + clem.setNumAbatements(12345); + assertEquals(Integer.valueOf(12345), clem.getNumAbatements()); + + clem.setNumOnsets(54321); + assertEquals(Integer.valueOf(54321), clem.getNumOnsets()); + + assertNull(clem.getOnsetEvent()); + assertNull(clem.getAbatementEvent()); + assertNull(clem.getProcessor()); + + assertEquals(true, clem.isActive()); + assertEquals(false, clem.releaseLock()); + assertEquals(true, clem.isControlLoopTimedOut()); + + assertNull(clem.unlockCurrentOperation()); + } + + @Test + public void testAlreadyActivated() { + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + manager.setActivated(true); + VirtualControlLoopNotification notification = manager.activate(event); + assertEquals(ControlLoopNotificationType.REJECTED, notification.getNotification()); + } + + @Test + public void testActivationYaml() throws IOException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + InputStream isBad = new FileInputStream(new File("src/test/resources/notutf8.yaml")); + String yamlStringBad = IOUtils.toString(isBad, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + + // Null YAML should fail + VirtualControlLoopNotification notificationNull = manager.activate(null, event); + assertNotNull(notificationNull); + assertEquals(ControlLoopNotificationType.REJECTED, notificationNull.getNotification()); + + // Empty YAML should fail + VirtualControlLoopNotification notificationEmpty = manager.activate("", event); + assertNotNull(notificationEmpty); + assertEquals(ControlLoopNotificationType.REJECTED, notificationEmpty.getNotification()); + + // Bad YAML should fail + VirtualControlLoopNotification notificationBad = manager.activate(yamlStringBad, event); + assertNotNull(notificationBad); + assertEquals(ControlLoopNotificationType.REJECTED, notificationBad.getNotification()); + + VirtualControlLoopNotification notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + // Another activate should fail + VirtualControlLoopNotification notificationActive = manager.activate(yamlString, event); + assertNotNull(notificationActive); + assertEquals(ControlLoopNotificationType.REJECTED, notificationActive.getNotification()); + } + + @Test + public void testControlLoopFinal() throws ControlLoopException, IOException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + try { + manager.isControlLoopFinal(); + fail("test should throw an exception here"); + } catch (ControlLoopException e) { + assertEquals("ControlLoopEventManager MUST be activated first.", e.getMessage()); + } + + manager.setActivated(true); + try { + manager.isControlLoopFinal(); + fail("test should throw an exception here"); + } catch (ControlLoopException e) { + assertEquals("No onset event for ControlLoopEventManager.", e.getMessage()); + } + + manager.setActivated(false); + VirtualControlLoopNotification notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + VirtualControlLoopNotification clfNotification = manager.isControlLoopFinal(); + assertNull(clfNotification); + + manager.getProcessor().nextPolicyForResult(PolicyResult.SUCCESS); + clfNotification = manager.isControlLoopFinal(); + assertNotNull(clfNotification); + assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, clfNotification.getNotification()); + + manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_EXCEPTION); + clfNotification = manager.isControlLoopFinal(); + assertNotNull(clfNotification); + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); + + manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_GUARD); + clfNotification = manager.isControlLoopFinal(); + assertNotNull(clfNotification); + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); + + manager.setControlLoopTimedOut(); + clfNotification = manager.isControlLoopFinal(); + assertNotNull(clfNotification); + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); + } + + @Test + public void testProcessControlLoop() throws ControlLoopException, IOException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + try { + manager.processControlLoop(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("ControlLoopEventManager MUST be activated first.", e.getMessage()); + } + + manager.setActivated(true); + try { + manager.processControlLoop(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("No onset event for ControlLoopEventManager.", e.getMessage()); + } + + manager.setActivated(false); + VirtualControlLoopNotification notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + ControlLoopOperationManager clom = manager.processControlLoop(); + assertNotNull(clom); + assertNull(clom.getOperationResult()); + + // Test operation in progress + try { + manager.processControlLoop(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Already working an Operation, do not call this method.", e.getMessage()); + } + + manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_GUARD); + VirtualControlLoopNotification clfNotification = manager.isControlLoopFinal(); + assertNotNull(clfNotification); + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); + + // Test operation completed + try { + manager.processControlLoop(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Control Loop is in FINAL state, do not call this method.", e.getMessage()); + } + + manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE); + + // Test operation with no next policy defined + try { + manager.processControlLoop(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("The target type is null", e.getMessage()); + } + } + + @Test + public void testFinishOperation() throws IOException, ControlLoopException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + InputStream isStd = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlStringStd = IOUtils.toString(isStd, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + try { + manager.finishOperation(null); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("No operation to finish.", e.getMessage()); + } + + manager.setActivated(true); + try { + manager.finishOperation(null); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("No operation to finish.", e.getMessage()); + } + + manager.setActivated(false); + VirtualControlLoopNotification notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + try { + manager.lockCurrentOperation(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Do not have a current operation.", e.getMessage()); + } + + assertNull(manager.unlockCurrentOperation()); + + ControlLoopOperationManager clom = manager.processControlLoop(); + assertNotNull(clom); + assertNull(clom.getOperationResult()); + + LockResult<GuardResult, TargetLock> lockLock = manager.lockCurrentOperation(); + assertNotNull(lockLock); + + LockResult<GuardResult, TargetLock> lockLockAgain = manager.lockCurrentOperation(); + assertNotNull(lockLockAgain); + assertEquals(lockLock.getB(), lockLockAgain.getB()); + + assertEquals(lockLock.getB(), manager.unlockCurrentOperation()); + assertNull(manager.unlockCurrentOperation()); + + lockLock = manager.lockCurrentOperation(); + assertNotNull(lockLock); + PolicyGuard.unlockTarget(lockLock.getB()); + assertNull(manager.unlockCurrentOperation()); + + clom.startOperation(event); + + // This call should be exception free + manager.finishOperation(clom); + + ControlLoopEventManager otherManager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + VirtualControlLoopNotification otherNotification = otherManager.activate(yamlStringStd, event); + assertNotNull(otherNotification); + assertEquals(ControlLoopNotificationType.ACTIVE, otherNotification.getNotification()); + + ControlLoopOperationManager otherClom = otherManager.processControlLoop(); + assertNotNull(otherClom); + assertNull(otherClom.getOperationResult()); + + otherManager.finishOperation(clom); + } + + @Test + public void testOnNewEvent() throws IOException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + VirtualControlLoopEvent abatedEvent = new VirtualControlLoopEvent(); + abatedEvent.setClosedLoopControlName("TwoOnsetTest"); + abatedEvent.setRequestID(requestId); + abatedEvent.setTarget("generic-vnf.vnf-id"); + abatedEvent.setClosedLoopAlarmStart(Instant.now()); + abatedEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED); + abatedEvent.setAAI(new HashMap<>()); + abatedEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + assertEquals(NEW_EVENT_STATUS.FIRST_ONSET, manager.onNewEvent(onsetEvent)); + assertEquals(NEW_EVENT_STATUS.FIRST_ABATEMENT, manager.onNewEvent(abatedEvent)); + assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); + + VirtualControlLoopEvent checkSyntaxEvent = new VirtualControlLoopEvent(); + checkSyntaxEvent.setAAI(null); + checkSyntaxEvent.setClosedLoopAlarmEnd(null); + checkSyntaxEvent.setClosedLoopAlarmStart(null); + checkSyntaxEvent.setClosedLoopControlName(null); + checkSyntaxEvent.setClosedLoopEventClient(null); + checkSyntaxEvent.setClosedLoopEventStatus(null); + checkSyntaxEvent.setFrom(null); + checkSyntaxEvent.setPolicyName(null); + checkSyntaxEvent.setPolicyScope(null); + checkSyntaxEvent.setPolicyVersion(null); + checkSyntaxEvent.setRequestID(null); + checkSyntaxEvent.setTarget(null); + checkSyntaxEvent.setTargetType(null); + checkSyntaxEvent.setVersion(null); + + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setClosedLoopControlName(null); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setClosedLoopControlName(""); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setClosedLoopControlName("TwoOnsetTest"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setRequestID(null); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setRequestID(requestId); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setAAI(null); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setAAI(new HashMap<>()); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget(""); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget(null); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget(""); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("OZ"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("VM_NAME"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("VNF_NAME"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("vserver.vserver-name"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("generic-vnf.vnf-id"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("generic-vnf.vnf-name"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setAAI(null); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setAAI(new HashMap<>()); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); + + checkSyntaxEvent.getAAI().put("vserver.vserver-name", "onsetOne"); + assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); + + checkSyntaxEvent.getAAI().put("generic-vnf.vnf-id", "onsetOne"); + assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); + } + + @Test + public void testControlLoopTimeout() throws IOException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + assertTrue(0 == manager.getControlLoopTimeout(null)); + assertTrue(120 == manager.getControlLoopTimeout(120)); + + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + assertTrue(60 == manager.getControlLoopTimeout(null)); + } + + @Test + public void testQueryAAI() throws IOException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + manager.queryAai(onsetEvent); + + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().put("generic-vnf.is-closed-loop-disabled", "true"); + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("is-closed-loop-disabled is set to true on VServer or VNF", e.getMessage()); + } + onsetEvent.getAAI().put("vserver.is-closed-loop-disabled", "true"); + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("is-closed-loop-disabled is set to true on VServer or VNF", e.getMessage()); + } + onsetEvent.getAAI().remove("generic-vnf.is-closed-loop-disabled"); + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("is-closed-loop-disabled is set to true on VServer or VNF", e.getMessage()); + } + onsetEvent.getAAI().remove("vserver.is-closed-loop-disabled"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().put("generic-vnf.is-closed-loop-disabled", "false"); + manager.queryAai(onsetEvent); + onsetEvent.getAAI().put("vserver.is-closed-loop-disabled", "false"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().remove("generic-vnf.vnf-id"); + onsetEvent.getAAI().remove("generic-vnf.vnf-name"); + onsetEvent.getAAI().remove("vserver.vserver-name"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().put("vserver.vserver-name", "AVserver"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().put("generic-vnf.vnf-name", "AVNFName"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().put("generic-vnf.vnf-id", "AVNFID"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().remove("vserver.vserver-name"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().remove("generic-vnf.vnf-name"); + manager.queryAai(onsetEvent); + + // Force AAI errors + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:9999"); + + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Exception from queryAai: org.onap.policy.aai.util.AAIException: AAI Response is null (query by vnf-id)", e.getMessage()); + } + + onsetEvent.getAAI().remove("generic-vnf.vnf-id"); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "AVNFName"); + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Exception from queryAai: org.onap.policy.aai.util.AAIException: AAI Response is null (query by vnf-name)", e.getMessage()); + } + + onsetEvent.getAAI().remove("generic-vnf.vnf-name"); + onsetEvent.getAAI().put("vserver.vserver-name", "AVserver"); + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Exception from queryAai: org.onap.policy.aai.util.AAIException: AAI Response is null (query by vserver-name)", e.getMessage()); + } + + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + } }
\ No newline at end of file diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java index 76020b0c9..4a30a451a 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java @@ -23,17 +23,29 @@ package org.onap.policy.controlloop.eventmanager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.HashMap; import java.util.UUID; +import org.apache.commons.io.IOUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.aai.util.AAIException; +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.appc.ResponseStatus; +import org.onap.policy.appclcm.LCMCommonHeader; import org.onap.policy.appclcm.LCMRequest; import org.onap.policy.appclcm.LCMRequestWrapper; import org.onap.policy.appclcm.LCMResponse; @@ -46,16 +58,26 @@ import org.onap.policy.controlloop.ControlLoopTargetType; import org.onap.policy.controlloop.Util; import org.onap.policy.controlloop.VirtualControlLoopNotification; import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.Policy; import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.policy.Target; +import org.onap.policy.controlloop.policy.TargetType; import org.onap.policy.controlloop.processor.ControlLoopProcessor; import org.onap.policy.drools.http.server.HttpServletServer; import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.so.SOResponse; +import org.onap.policy.so.SOResponseWrapper; +import org.onap.policy.vfc.VFCResponse; +import org.onap.policy.vfc.VFCResponseDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopOperationManagerTest { private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManagerTest.class); + + private static VirtualControlLoopEvent onset; + static { onset = new VirtualControlLoopEvent(); onset.setRequestID(UUID.randomUUID()); @@ -65,27 +87,27 @@ public class ControlLoopOperationManagerTest { onset.setAAI(new HashMap<>()); onset.getAAI().put("generic-vnf.vnf-name", "testTriggerSource"); onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - + /* Set environment properties */ - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); - PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); - PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); + PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); } @BeforeClass - public static void setUpSimulator() { - try { - org.onap.policy.simulators.Util.buildAaiSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @AfterClass - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - } - + public static void setUpSimulator() { + try { + org.onap.policy.simulators.Util.buildAaiSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + } + @Test public void testRetriesFail() { // @@ -102,21 +124,21 @@ public class ControlLoopOperationManagerTest { // create the manager // ControlLoopEventManager eventManager = new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestID()); - VirtualControlLoopNotification notification = eventManager.activate(onset); - + VirtualControlLoopNotification notification = eventManager.activate(onset); + assertNotNull(notification); assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - + ControlLoopEventManager.NEW_EVENT_STATUS status = null; - try { - status = eventManager.onNewEvent(onset); - } catch (AAIException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } - assertNotNull(status); - assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); - + try { + status = eventManager.onNewEvent(onset); + } catch (AAIException e) { + logger.warn(e.toString()); + fail("A&AI Query Failed"); + } + assertNotNull(status); + assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); + ControlLoopOperationManager manager = new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); logger.debug("{}",manager); // @@ -232,20 +254,20 @@ public class ControlLoopOperationManagerTest { // ControlLoopEventManager eventManager = new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestID()); VirtualControlLoopNotification notification = eventManager.activate(onset); - + assertNotNull(notification); assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); ControlLoopEventManager.NEW_EVENT_STATUS status = null; - try { - status = eventManager.onNewEvent(onset); - } catch (AAIException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } - assertNotNull(status); - assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); - + try { + status = eventManager.onNewEvent(onset); + } catch (AAIException e) { + logger.warn(e.toString()); + fail("A&AI Query Failed"); + } + assertNotNull(status); + assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); + ControlLoopOperationManager manager = new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); // // @@ -270,7 +292,7 @@ public class ControlLoopOperationManagerTest { // LCMResponseWrapper dmaapResponse = new LCMResponseWrapper(); LCMResponse appcResponse = new LCMResponse(appcRequest); - dmaapResponse.setBody(appcResponse); + dmaapResponse.setBody(appcResponse); appcResponse.getStatus().setCode(100); appcResponse.getStatus().setMessage("ACCEPT"); // @@ -311,4 +333,414 @@ public class ControlLoopOperationManagerTest { } } + @Test + public void testMethods() throws IOException, ControlLoopException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + ControlLoopOperationManager clom = manager.processControlLoop(); + assertNotNull(clom); + assertNull(clom.getOperationResult()); + + clom.setEventManager(manager); + assertEquals(manager, clom.getEventManager()); + + assertNull(clom.getTargetEntity()); + + clom.setGuardApprovalStatus("WizardOKedIt"); + assertEquals("WizardOKedIt", clom.getGuardApprovalStatus()); + + assertNull(clom.getOperationResult()); + + Policy policy = manager.getProcessor().getCurrentPolicy(); + clom.getTarget(policy); + + Target savedTarget = policy.getTarget(); + policy.setTarget(null); + try { + clom.getTarget(policy); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("The target is null", e.getMessage()); + } + + policy.setTarget(new Target()); + try { + clom.getTarget(policy); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("The target type is null", e.getMessage()); + } + + policy.setTarget(savedTarget); + + policy.getTarget().setType(TargetType.PNF); + try { + clom.getTarget(policy); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("PNF target is not supported", e.getMessage()); + } + + onsetEvent.setTarget("Oz"); + onsetEvent.getAAI().remove("generic-vnf.vnf-name"); + onsetEvent.getAAI().remove("generic-vnf.vnf-id"); + onsetEvent.getAAI().remove("vserver.vserver-name"); + + policy.getTarget().setType(TargetType.VNF); + try { + clom.getTarget(policy); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Target does not match target type", e.getMessage()); + } + + onsetEvent.setTarget("vserver.vserver-name"); + onsetEvent.getAAI().put("vserver.vserver-name", "OzVServer"); + assertEquals("OzVServer", clom.getTarget(policy)); + + onsetEvent.getAAI().remove("vserver.vserver-name"); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.getAAI().put("generic-vnf.vnf-id", "OzVNF"); + assertEquals("OzVNF", clom.getTarget(policy)); + + onsetEvent.setTarget("generic-vnf.vnf-name"); + assertEquals("OzVNF", clom.getTarget(policy)); + + manager.onNewEvent(onsetEvent); + + onsetEvent.getAAI().remove("generic-vnf.vnf-id"); + manager.getVnfResponse(); + clom.getEventManager().getVnfResponse().setVnfID("generic-vnf.vnf-id"); + assertEquals("generic-vnf.vnf-id", clom.getTarget(policy)); + + policy.getTarget().setType(TargetType.VFC); + try { + clom.getTarget(policy); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("The target type is not supported", e.getMessage()); + } + + assertEquals(Integer.valueOf(20), clom.getOperationTimeout()); + + assertEquals("20s", clom.getOperationTimeoutString(100)); + + assertEquals(null, clom.getOperationMessage()); + assertEquals(null, clom.getOperationMessage("The Wizard Escaped")); + + clom.startOperation(onsetEvent); + + assertEquals("actor=SO,operation=Restart,target=Target [type=VFC, resourceID=null],subRequestId=1", clom.getOperationMessage()); + assertEquals("actor=SO,operation=Restart,target=Target [type=VFC, resourceID=null],subRequestId=1, Guard result: The Wizard Escaped", clom.getOperationMessage("The Wizard Escaped")); + + assertEquals("actor=SO,operation=Restart,tar", clom.getOperationHistory().substring(0, 30)); + + clom.setOperationHasException("The Wizard is gone"); + clom.setOperationHasGuardDeny(); + } + + @Test + public void testConstructor() throws IOException, ControlLoopException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + Policy policy = manager.getProcessor().getCurrentPolicy(); + ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + policy.setRecipe("ModifyConfig"); + policy.getTarget().setResourceID(UUID.randomUUID().toString()); + try { + new ControlLoopOperationManager(onsetEvent, policy, manager); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Target vnf-id could not be found", e.getMessage()); + } + + policy.getTarget().setResourceID("82194af1-3c2c-485a-8f44-420e22a9eaa4"); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + policy.setActor("SO"); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + policy.setActor("VFC"); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + policy.setActor("Dorothy"); + try { + new ControlLoopOperationManager(onsetEvent, policy, manager); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("ControlLoopEventManager: policy has an unknown actor.", e.getMessage()); + } + } + + @Test + public void testStartOperation() throws IOException, ControlLoopException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + Policy policy = manager.getProcessor().getCurrentPolicy(); + ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + clom.startOperation(onsetEvent); + + try { + clom.startOperation(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("current operation is not null (an operation is already running)", e.getMessage()); + } + + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + String savedRecipe = policy.getRecipe(); + policy.setRecipe("ModifyConfig"); + policy.getTarget().setResourceID(UUID.randomUUID().toString()); + clom.startOperation(onsetEvent); + policy.setRecipe(savedRecipe); + + policy.setRetry(null); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + clom.startOperation(onsetEvent); + clom.setOperationHasTimedOut(); + assertTrue(clom.isOperationComplete()); + try { + clom.startOperation(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("current operation failed and retries are not allowed", e.getMessage()); + } + + policy.setRetry(0); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + clom.startOperation(onsetEvent); + clom.setOperationHasTimedOut(); + assertTrue(clom.isOperationComplete()); + try { + clom.startOperation(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("current operation failed and retries are not allowed", e.getMessage()); + } + + policy.setRetry(1); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + clom.startOperation(onsetEvent); + clom.setOperationHasTimedOut(); + clom.startOperation(onsetEvent); + clom.setOperationHasTimedOut(); + assertTrue(clom.isOperationComplete()); + try { + clom.startOperation(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("current oepration has failed after 2 retries", e.getMessage()); + } + + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + policy.setActor("SO"); + clom.startOperation(onsetEvent); + + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + policy.setActor("VFC"); + clom.startOperation(onsetEvent); + + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + policy.setActor("Oz"); + try { + clom.startOperation(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("invalid actor Oz on policy", e.getMessage()); + } + } + + @Test + public void testOnResponse() throws IOException, ControlLoopException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + Policy policy = manager.getProcessor().getCurrentPolicy(); + ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + assertNull(clom.onResponse(null)); + + Response appcResponse = new Response(); + CommonHeader commonHeader = new CommonHeader(); + appcResponse.setCommonHeader(commonHeader ); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + commonHeader.setSubRequestID("12345"); + appcResponse.setStatus(null); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + ResponseStatus responseStatus = new ResponseStatus(); + appcResponse.setStatus(responseStatus); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + responseStatus.setCode(0); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + responseStatus.setCode(ResponseCode.ACCEPT.getValue()); + assertEquals(null, clom.onResponse(appcResponse)); + + responseStatus.setCode(ResponseCode.ERROR.getValue()); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + responseStatus.setCode(ResponseCode.FAILURE.getValue()); + assertEquals(PolicyResult.FAILURE, clom.onResponse(appcResponse)); + + responseStatus.setCode(ResponseCode.REJECT.getValue()); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + responseStatus.setCode(ResponseCode.SUCCESS.getValue()); + assertEquals(PolicyResult.SUCCESS, clom.onResponse(appcResponse)); + + LCMResponseWrapper lrw = new LCMResponseWrapper(); + LCMResponse body = new LCMResponse(); + LCMCommonHeader lcmCH = new LCMCommonHeader(); + body.setCommonHeader(lcmCH ); + lrw.setBody(body ); + + lcmCH.setSubRequestId("NotANumber"); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(lrw)); + + lcmCH.setSubRequestId("12345"); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(lrw)); + + SOResponse soResponse = new SOResponse(); + SOResponseWrapper soRW = new SOResponseWrapper(soResponse , null); + + soResponse.setHttpResponseCode(200); + assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRW)); + + soResponse.setHttpResponseCode(202); + assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRW)); + + soResponse.setHttpResponseCode(500); + assertEquals(PolicyResult.FAILURE, clom.onResponse(soRW)); + + VFCResponse vfcResponse = new VFCResponse(); + VFCResponseDescriptor responseDescriptor = new VFCResponseDescriptor(); + vfcResponse.setResponseDescriptor(responseDescriptor ); + + responseDescriptor.setStatus("finished"); + assertEquals(PolicyResult.SUCCESS, clom.onResponse(vfcResponse)); + + responseDescriptor.setStatus("unfinished"); + assertEquals(PolicyResult.FAILURE, clom.onResponse(vfcResponse)); + } + + @Test + public void testCompleteOperation() throws ControlLoopException, AAIException, IOException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + Policy policy = manager.getProcessor().getCurrentPolicy(); + ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + clom.startOperation(onsetEvent); + + SOResponse soResponse = new SOResponse(); + SOResponseWrapper soRW = new SOResponseWrapper(soResponse , null); + + PolicyEngine.manager.setEnvironmentProperty("guard.disabled", "false"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL, "http://somewhere.over.the.rainbow"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "Dorothy"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto"); + + assertEquals(PolicyResult.FAILURE, clom.onResponse(soRW)); + + System.setProperty("OperationsHistoryPU", "TestOperationsHistoryPU"); + assertEquals(PolicyResult.FAILURE, clom.onResponse(soRW)); + } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntryTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntryTest.java new file mode 100644 index 000000000..315565cf0 --- /dev/null +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntryTest.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * eventmanager + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.eventmanager; + +import static org.junit.Assert.*; + +import java.sql.Timestamp; +import java.util.UUID; + +import org.junit.Test; + +public class OperationsHistoryDbEntryTest { + + @Test + public void testOperationsHistoryDbEntry() { + OperationsHistoryDbEntry entry = new OperationsHistoryDbEntry(); + + String actor = "Dorothy"; + entry.setActor(actor); + assertEquals(actor, entry.getActor()); + + String closedLoopName = "GoToOz"; + entry.setClosedLoopName(closedLoopName); + assertEquals(closedLoopName, entry.getClosedLoopName()); + + Timestamp endtime = new Timestamp(System.currentTimeMillis()); + entry.setEndtime(endtime); + assertEquals(endtime, entry.getEndtime()); + + String message = "I Want to go Home"; + entry.setMessage(message); + assertEquals(message, entry.getMessage()); + + String operation = "Get Home"; + entry.setOperation(operation); + assertEquals(operation, entry.getOperation()); + + String outcome = "Back in Kansas"; + entry.setOutcome(outcome); + assertEquals(outcome, entry.getOutcome()); + + String requestId = UUID.randomUUID().toString(); + entry.setRequestId(requestId); + assertEquals(requestId, entry.getRequestId()); + + long rowid = 12345; + entry.setRowid(rowid); + assertEquals(rowid, entry.getRowid()); + + Timestamp starttime = new Timestamp(endtime.getTime() - 100); + entry.setStarttime(starttime); + assertEquals(starttime, entry.getStarttime()); + + String subrequestId = "12321"; + entry.setSubrequestId(subrequestId); + assertEquals(subrequestId, entry.getSubrequestId()); + + String target = "WizardOfOz"; + entry.setTarget(target); + assertEquals(target, entry.getTarget()); + } +} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java index 7bd18a3ff..87ccdb5b9 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java @@ -24,7 +24,6 @@ import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; @@ -41,25 +40,92 @@ import org.slf4j.LoggerFactory; public class ControlLoopProcessorTest { private static final Logger logger = LoggerFactory.getLogger(ControlLoopProcessorTest.class); - + + @Test + public void testControlLoopProcessor() throws IOException, ControlLoopException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + this.testSuccess(yamlString); + this.testFailure(yamlString); + } + @Test - public void test() { - try (InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"))) { - String result = IOUtils.toString(is, StandardCharsets.UTF_8); - this.testSuccess(result); - this.testFailure(result); - } catch (FileNotFoundException e) { - e.printStackTrace(); - fail(e.getMessage()); - } catch (IOException e) { - e.printStackTrace(); - fail(e.getMessage()); - } catch (ControlLoopException e) { - e.printStackTrace(); - fail(e.getMessage()); + public void testControlLoopProcessorBadYaml() throws IOException { + InputStream is = new FileInputStream(new File("src/test/resources/string.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + try { + new ControlLoopProcessor(yamlString); + fail("test should thrown an exception"); + } + catch (Exception e) { + assertEquals("Cannot create property=string for JavaBean=ControlLoopPolicy", e.getMessage().substring(0, 60)); } } - + + @Test + public void testControlLoopProcessorBadTriggerYaml() throws IOException, ControlLoopException { + InputStream is = new FileInputStream(new File("src/test/resources/badtriggerpolicy.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); + assertNull(clProcessor.getCurrentPolicy()); + + try { + clProcessor.nextPolicyForResult(PolicyResult.SUCCESS); + fail("test shold throw an exception here"); + } + catch (ControlLoopException e) { + assertEquals("There is no current policy to determine where to go to.", e.getMessage()); + } + } + + @Test + public void testControlLoopProcessorNoPolicyYaml() throws IOException, ControlLoopException { + InputStream is = new FileInputStream(new File("src/test/resources/nopolicy.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); + + try { + clProcessor.getCurrentPolicy(); + fail("test shold throw an exception here"); + } + catch (ControlLoopException e) { + assertEquals("There are no policies defined.", e.getMessage()); + } + } + + @Test + public void testControlLoopProcessorNextPolicyForResult() throws IOException, ControlLoopException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.SUCCESS); + + clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.FAILURE); + + clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.FAILURE_EXCEPTION); + + clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.FAILURE_GUARD); + + clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.FAILURE_RETRIES); + + clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.FAILURE_TIMEOUT); + } + public void testSuccess(String yaml) throws ControlLoopException { ControlLoopProcessor processor = new ControlLoopProcessor(yaml); logger.debug("testSuccess: {}", processor.getControlLoop()); @@ -91,5 +157,4 @@ public class ControlLoopProcessorTest { processor.nextPolicyForResult(PolicyResult.FAILURE); } } - } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java new file mode 100644 index 000000000..d94230e5e --- /dev/null +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * eventmanager + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Request; +import org.onap.policy.appclcm.LCMCommonHeader; +import org.onap.policy.appclcm.LCMRequest; +import org.onap.policy.appclcm.LCMRequestWrapper; +import org.onap.policy.controlloop.ControlLoopNotification; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.drools.impl.PolicyEngineJUnitImpl; + +public class DroolsPolicyEngineTest { + @Test + public void testDroolsPolicyEngine() { + PolicyEngineJUnitImpl pe = new PolicyEngineJUnitImpl(); + assertNotNull(pe); + + pe.addListener(new TestPolicyEngineListener()); + pe.notifyListeners("TheWizardOfOz"); + + pe.subscribe("OmniBus", "TheWizardOfOz"); + + pe.deliver("OmniBus", "TheWizardOfOz", "Dorothy"); + + pe.subscribe("OmniBus", "TheWizardOfOz"); + pe.subscribe("OmniBus", "ThisTopicDoesNotExist"); + + ControlLoopNotification notification = new VirtualControlLoopNotification(); + pe.deliver("OmniBus", "TheWizardOfOz", notification); + + Request request = new Request(); + request.setCommonHeader(new CommonHeader()); + request.getCommonHeader().setSubRequestID("12321"); + pe.deliver("OmniBus", "TheWizardOfOz", request); + + LCMRequestWrapper lcmRW = new LCMRequestWrapper(); + lcmRW.setBody(new LCMRequest()); + lcmRW.getBody().setCommonHeader(new LCMCommonHeader()); + lcmRW.getBody().getCommonHeader().setSubRequestId("54321"); + pe.deliver("OmniBus", "TheWizardOfOz", lcmRW); + } + + private class TestPolicyEngineListener implements PolicyEngineListener { + @Override + public void newEventNotification(String topic) { + assertEquals("TheWizardOfOz", topic); + } + } +} diff --git a/controlloop/common/eventmanager/src/test/resources/META-INF/persistence.xml b/controlloop/common/eventmanager/src/test/resources/META-INF/persistence.xml new file mode 100644 index 000000000..d5fadfffb --- /dev/null +++ b/controlloop/common/eventmanager/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,17 @@ +<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> + <persistence-unit name="TestOperationsHistoryPU" transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + + <class>org.onap.policy.whatever.WhatEver</class> + + <properties> + <property name="javax.persistence.jdbc.url" value="jdbc:derby:memory:apex_test" /> + <property name="javax.persistence.target-database" value="Derby" /> + <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" /> + + <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> + <property name="eclipselink.ddl-generation.output-mode" value="database"/> + <property name="eclipselink.logging.level" value="INFO" /> + </properties> + </persistence-unit> +</persistence> diff --git a/controlloop/common/eventmanager/src/test/resources/badtriggerpolicy.yaml b/controlloop/common/eventmanager/src/test/resources/badtriggerpolicy.yaml new file mode 100644 index 000000000..e263cd5b2 --- /dev/null +++ b/controlloop/common/eventmanager/src/test/resources/badtriggerpolicy.yaml @@ -0,0 +1,62 @@ +controlLoop: + version: 1.0.0 + controlLoopName: ControlLoop-vService-cbed919f-2212-4ef7-8051-fe6308da1bda + services: + - serviceName: service1 + resources: + - resourceName: resource1 + resourceType: VF + - resourceName: resource2 + resourceType: VF + - resourceName: resource3 + resourceType: VF + - resourceName: resource4 + resourceType: VF + - resourceName: resource5 + resourceType: VF + trigger_policy: a-policy-that-does-not-exist + timeout: 60 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: + type: VNF + retry: 1 + timeout: 20 + success: final_success + failure: unique-policy-id-2-rebuild + failure_timeout: unique-policy-id-2-rebuild + failure_retries: unique-policy-id-2-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-2-rebuild + name: Rebuild Policy + description: + actor: APPC + recipe: Rebuild + target: VM + retry: 0 + timeout: 10 + success: final_success + failure: unique-policy-id-3-migrate + failure_timeout: unique-policy-id-3-migrate + failure_retries: unique-policy-id-3-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-3-migrate + name: Migrate Policy + description: + actor: APPC + recipe: Migrate + target: VM + retry: 0 + timeout: 30 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/eventmanager/src/test/resources/nopolicy.yaml b/controlloop/common/eventmanager/src/test/resources/nopolicy.yaml new file mode 100644 index 000000000..d3758f3da --- /dev/null +++ b/controlloop/common/eventmanager/src/test/resources/nopolicy.yaml @@ -0,0 +1,18 @@ +controlLoop: + version: 1.0.0 + controlLoopName: ControlLoop-vService-cbed919f-2212-4ef7-8051-fe6308da1bda + services: + - serviceName: service1 + resources: + - resourceName: resource1 + resourceType: VF + - resourceName: resource2 + resourceType: VF + - resourceName: resource3 + resourceType: VF + - resourceName: resource4 + resourceType: VF + - resourceName: resource5 + resourceType: VF + trigger_policy: a-policy-that-does-not-exist + timeout: 60 diff --git a/controlloop/common/eventmanager/src/test/resources/notutf8.yaml b/controlloop/common/eventmanager/src/test/resources/notutf8.yaml Binary files differnew file mode 100644 index 000000000..c2366a1cd --- /dev/null +++ b/controlloop/common/eventmanager/src/test/resources/notutf8.yaml diff --git a/controlloop/common/eventmanager/src/test/resources/string.yaml b/controlloop/common/eventmanager/src/test/resources/string.yaml new file mode 100644 index 000000000..dc03f8041 --- /dev/null +++ b/controlloop/common/eventmanager/src/test/resources/string.yaml @@ -0,0 +1 @@ +string: hello diff --git a/controlloop/common/eventmanager/src/test/resources/testSOactor.yaml b/controlloop/common/eventmanager/src/test/resources/testSOactor.yaml new file mode 100644 index 000000000..0d5f3b1e2 --- /dev/null +++ b/controlloop/common/eventmanager/src/test/resources/testSOactor.yaml @@ -0,0 +1,62 @@ +controlLoop: + version: 1.0.0 + controlLoopName: ControlLoop-vService-cbed919f-2212-4ef7-8051-fe6308da1bda + services: + - serviceName: service1 + resources: + - resourceName: resource1 + resourceType: VF + - resourceName: resource2 + resourceType: VF + - resourceName: resource3 + resourceType: VF + - resourceName: resource4 + resourceType: VF + - resourceName: resource5 + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 60 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: SO + recipe: Restart + target: + type: VNF + retry: 1 + timeout: 20 + success: final_success + failure: unique-policy-id-2-rebuild + failure_timeout: unique-policy-id-2-rebuild + failure_retries: unique-policy-id-2-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-2-rebuild + name: Rebuild Policy + description: + actor: SO + recipe: Rebuild + target: VM + retry: 0 + timeout: 10 + success: final_success + failure: unique-policy-id-3-migrate + failure_timeout: unique-policy-id-3-migrate + failure_retries: unique-policy-id-3-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-3-migrate + name: Migrate Policy + description: + actor: SO + recipe: Migrate + target: VM + retry: 0 + timeout: 30 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java index 8fa066109..1b312ea5a 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java @@ -57,7 +57,7 @@ public enum FinalResult { this.result = result; } - public static FinalResult toResult(String result) { + public static FinalResult toResult(String result) { if (result.equalsIgnoreCase(FINAL_SUCCESS.toString())) { return FINAL_SUCCESS; } diff --git a/controlloop/templates/archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl b/controlloop/templates/archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl index bdb57697b..520425746 100644 --- a/controlloop/templates/archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl +++ b/controlloop/templates/archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl @@ -509,7 +509,7 @@ rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED" try { request = $operation.startOperation($event); } - catch (AAIException e) { + catch (ControlLoopException e) { String msg = e.getMessage(); logger.warn("{}: {}: operation={}: AAI failure: {}", $params.getClosedLoopControlName(), drools.getRule().getName(), |