diff options
Diffstat (limited to 'controlloop/common/policy-yaml')
24 files changed, 3702 insertions, 3416 deletions
diff --git a/controlloop/common/policy-yaml/pom.xml b/controlloop/common/policy-yaml/pom.xml index 6f87a978a..8e313cb62 100644 --- a/controlloop/common/policy-yaml/pom.xml +++ b/controlloop/common/policy-yaml/pom.xml @@ -9,6 +9,18 @@ <artifactId>policy-yaml</artifactId> <dependencies> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + <version>1.7.25</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>ch.qos.logback</groupId> + <artifactId>logback-classic</artifactId> + <version>1.2.3</version> + <scope>provided</scope> + </dependency> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java index 2710fcde2..f0c680784 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java @@ -21,600 +21,594 @@ package org.onap.policy.controlloop.compiler; import java.io.InputStream; +import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import org.jgrapht.DirectedGraph; import org.jgrapht.graph.ClassBasedEdgeFactory; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DirectedMultigraph; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - import org.onap.policy.controlloop.policy.ControlLoop; import org.onap.policy.controlloop.policy.ControlLoopPolicy; import org.onap.policy.controlloop.policy.FinalResult; import org.onap.policy.controlloop.policy.Policy; import org.onap.policy.controlloop.policy.PolicyResult; import org.onap.policy.controlloop.policy.TargetType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -public class ControlLoopCompiler { - - public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { - // - // Ensure the control loop is sane - // - validateControlLoop(policy.controlLoop, callback); - // - // Validate the policies - // - validatePolicies(policy, callback); - - return policy; - } - - public static ControlLoopPolicy compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - Object obj = yaml.load(yamlSpecification); - if (obj == null) { - throw new CompilerException("Could not parse yaml specification."); - } - if (! (obj instanceof ControlLoopPolicy)) { - throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object"); - } - return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback); - } - - private static void validateControlLoop(ControlLoop controlLoop, ControlLoopCompilerCallback callback) throws CompilerException { - if (controlLoop == null) { - if (callback != null) { - callback.onError("controlLoop cannot be null"); - } - } - if (controlLoop.controlLoopName == null | controlLoop.controlLoopName.length() < 1) { - if (callback != null) { - callback.onError("Missing controlLoopName"); - } - } - if (! controlLoop.version.contentEquals(ControlLoop.VERSION)) { - if (callback != null) { - callback.onError("Unsupported version for this compiler"); - } - } - if (controlLoop.trigger_policy == null || controlLoop.trigger_policy.length() < 1) { - throw new CompilerException("trigger_policy is not valid"); - } - // - } +public class ControlLoopCompiler implements Serializable{ + private static final long serialVersionUID = 1L; + private static Logger LOGGER = LoggerFactory.getLogger(ControlLoopCompiler.class.getName()); + + public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { + // + // Ensure the control loop is sane + // + validateControlLoop(policy.getControlLoop(), callback); + // + // Validate the policies + // + validatePolicies(policy, callback); + + return policy; + } + + public static ControlLoopPolicy compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(yamlSpecification); + if (obj == null) { + throw new CompilerException("Could not parse yaml specification."); + } + if (! (obj instanceof ControlLoopPolicy)) { + throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object"); + } + return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback); + } + + private static void validateControlLoop(ControlLoop controlLoop, ControlLoopCompilerCallback callback) throws CompilerException { + if (controlLoop == null && callback != null) { + callback.onError("controlLoop cannot be null"); + } + if (controlLoop!=null){ + if ((controlLoop.getControlLoopName() == null || controlLoop.getControlLoopName().length() < 1) && callback != null) { + callback.onError("Missing controlLoopName"); + } + if ((!controlLoop.getVersion().contentEquals(ControlLoop.getVERSION())) && callback != null) { + callback.onError("Unsupported version for this compiler"); + } + if (controlLoop.getTrigger_policy() == null || controlLoop.getTrigger_policy().length() < 1) { + throw new CompilerException("trigger_policy is not valid"); + } + } + } - private static void validatePolicies(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { - if (policy == null) { - throw new CompilerException("policy cannot be null"); - } - // - // Chenfei: verify controlLoop overall timeout should be no less than the sum of operational policy timeouts - // - if (policy.policies == null) { + private static void validatePolicies(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { + if (policy == null) { + throw new CompilerException("policy cannot be null"); + } + // + // verify controlLoop overall timeout should be no less than the sum of operational policy timeouts + // + if (policy.getPolicies() == null) { callback.onWarning("controlLoop is an open loop."); } else{ int sum = 0; - for (Policy operPolicy : policy.policies) { - sum += operPolicy.timeout.intValue(); - } - if (policy.controlLoop.timeout.intValue() < sum) { - if (callback != null) { - callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts."); - } - } - // - // For this version we can use a directed multigraph, in the future we may not be able to - // - DirectedGraph<NodeWrapper, LabeledEdge> graph = new DirectedMultigraph<NodeWrapper, LabeledEdge>(new ClassBasedEdgeFactory<NodeWrapper, LabeledEdge>(LabeledEdge.class)); - // - // Check to see if the trigger Event is for OpenLoop, we do so by - // attempting to create a FinalResult object from it. If its a policy id, this should - // return null. - // - FinalResult triggerResult = FinalResult.toResult(policy.controlLoop.trigger_policy); - TriggerNodeWrapper triggerNode; - // - // Did this turn into a FinalResult object? - // - if (triggerResult != null) { - // - // Ensure they didn't use some other FinalResult code - // - if (triggerResult != FinalResult.FINAL_OPENLOOP) { - throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); - } - // - // They really shouldn't have any policies attached. - // - if (policy.policies != null || policy.policies.size() > 0) { - if (callback != null) { - callback.onWarning("Open Loop policy contains policies. The policies will never be invoked."); - } - } - return; - // - } else { - // - // Ok, not a FinalResult object so let's assume that it is a Policy. Which it should be. - // - triggerNode = new TriggerNodeWrapper(policy.controlLoop.controlLoopName); - } - // - // Add in the trigger node - // - graph.addVertex(triggerNode); - // - // Add in our Final Result nodes. All paths should end to these nodes. - // - FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS); - FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE); - FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT); - FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES); - FinalResultNodeWrapper finalFailureException = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION); - FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD); - graph.addVertex(finalSuccess); - graph.addVertex(finalFailure); - graph.addVertex(finalFailureTimeout); - graph.addVertex(finalFailureRetries); - graph.addVertex(finalFailureException); - graph.addVertex(finalFailureGuard); - // - // Work through the policies and add them in as nodes. - // - Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<Policy, PolicyNodeWrapper>(); - for (Policy operPolicy : policy.policies) { - // - // Check the policy id and make sure its sane - // - boolean okToAdd = true; - if (operPolicy.id == null || operPolicy.id.length() < 1) { - if (callback != null) { - callback.onError("Operational Policy has an bad ID"); - } - okToAdd = false; - } - // - // Check if they decided to make the ID a result object - // - if (PolicyResult.toResult(operPolicy.id) != null) { - if (callback != null) { - callback.onError("Policy id is set to a PolicyResult " + operPolicy.id); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.id) != null) { - if (callback != null) { - callback.onError("Policy id is set to a FinalResult " + operPolicy.id); - } - okToAdd = false; - } - // - // Check that the actor/recipe/target are valid - // - if (operPolicy.actor == null) { - if (callback != null) { - callback.onError("Policy actor is null"); - } - okToAdd = false; - } - // - // Construct a list for all valid actors - // - ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI"); - // - if (operPolicy.actor != null && (!actors.contains(operPolicy.actor)) ) { - if (callback != null) { - callback.onError("Policy actor is invalid"); - } - okToAdd = false; - } - if (operPolicy.recipe == null) { - if (callback != null) { - callback.onError("Policy recipe is null"); - } - okToAdd = false; - } - // - // TODO: - // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these) - // - ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>() - .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig")) - .put("AOTS", ImmutableList.of("checkMaintenanceWindow", "checkENodeBTicketHours", "checkEquipmentStatus", "checkEimStatus", "checkEquipmentMaintenance")) - .put("MSO", ImmutableList.of("VF Module Create")) - .put("SDNO", ImmutableList.of("health-diagnostic-type", "health-diagnostic", "health-diagnostic-history", "health-diagnostic-commands", "health-diagnostic-aes")) - .put("SDNR", ImmutableList.of("Restart", "Reboot")) - .build(); - // - if (operPolicy.recipe != null && (!recipes.getOrDefault(operPolicy.actor, Collections.emptyList()).contains(operPolicy.recipe))) { - if (callback != null) { - callback.onError("Policy recipe is invalid"); - } - okToAdd = false; - } - if (operPolicy.target == null) { - if (callback != null) { - callback.onError("Policy target is null"); - } - okToAdd = false; - } - if (operPolicy.target != null && operPolicy.target.type != TargetType.VM && operPolicy.target.type != TargetType.VFC && operPolicy.target.type != TargetType.PNF) { - if (callback != null) { - callback.onError("Policy target is invalid"); - } - okToAdd = false; - } - // - // Check that policy results are connected to either default final * or another policy - // - if (FinalResult.toResult(operPolicy.success) != null && operPolicy.success != FinalResult.FINAL_SUCCESS.toString()) { - if (callback != null) { - callback.onError("Policy success is neither another policy nor FINAL_SUCCESS"); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.failure) != null && operPolicy.failure != FinalResult.FINAL_FAILURE.toString()) { - if (callback != null) { - callback.onError("Policy failure is neither another policy nor FINAL_FAILURE"); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.failure_retries) != null && operPolicy.failure_retries != FinalResult.FINAL_FAILURE_RETRIES.toString()) { - if (callback != null) { - callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES"); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.failure_timeout) != null && operPolicy.failure_timeout != FinalResult.FINAL_FAILURE_TIMEOUT.toString()) { - if (callback != null) { - callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT"); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.failure_exception) != null && operPolicy.failure_exception != FinalResult.FINAL_FAILURE_EXCEPTION.toString()) { - if (callback != null) { - callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION"); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.failure_guard) != null && operPolicy.failure_guard != FinalResult.FINAL_FAILURE_GUARD.toString()) { - if (callback != null) { - callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD"); - } - okToAdd = false; - } - // - // Is it still ok to add? - // - if (okToAdd == false) { - // - // Do not add it in - // - continue; - } - // - // Create wrapper policy node and save it into our map so we can - // easily retrieve it. - // - PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy); - mapNodes.put(operPolicy, node); - graph.addVertex(node); - // - // Is this the trigger policy? - // - if (operPolicy.id.equals(policy.controlLoop.trigger_policy)) { - // - // Yes add an edge from our trigger event node to this policy - // - graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET"))); - } - } - // - // last sweep to connect remaining edges for policy results - // - for (Policy operPolicy : policy.policies) { - PolicyNodeWrapper node = mapNodes.get(operPolicy); - // - // Just ensure this has something - // - if (node == null) { - continue; - } - if (FinalResult.isResult(operPolicy.success, FinalResult.FINAL_SUCCESS)) { - graph.addEdge(node, finalSuccess, new LabeledEdge(node, finalSuccess, new FinalResultEdgeWrapper(FinalResult.FINAL_SUCCESS))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.success); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.id + " success is connected to unknown policy " + operPolicy.success); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.SUCCESS))); - } - } - if (FinalResult.isResult(operPolicy.failure, FinalResult.FINAL_FAILURE)) { - graph.addEdge(node, finalFailure, new LabeledEdge(node, finalFailure, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.id + " failure is connected to unknown policy " + operPolicy.failure); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE))); - } - } - if (FinalResult.isResult(operPolicy.failure_timeout, FinalResult.FINAL_FAILURE_TIMEOUT)) { - graph.addEdge(node, finalFailureTimeout, new LabeledEdge(node, finalFailureTimeout, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_timeout); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.id + " failure_timeout is connected to unknown policy " + operPolicy.failure_timeout); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_TIMEOUT))); - } - } - if (FinalResult.isResult(operPolicy.failure_retries, FinalResult.FINAL_FAILURE_RETRIES)) { - graph.addEdge(node, finalFailureRetries, new LabeledEdge(node, finalFailureRetries, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_RETRIES))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_retries); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.id + " failure_retries is connected to unknown policy " + operPolicy.failure_retries); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_RETRIES))); - } - } - if (FinalResult.isResult(operPolicy.failure_exception, FinalResult.FINAL_FAILURE_EXCEPTION)) { - graph.addEdge(node, finalFailureException, new LabeledEdge(node, finalFailureException, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_exception); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.id + " failure_exception is connected to unknown policy " + operPolicy.failure_exception); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_EXCEPTION))); - } - } - if (FinalResult.isResult(operPolicy.failure_guard, FinalResult.FINAL_FAILURE_GUARD)) { - graph.addEdge(node, finalFailureGuard, new LabeledEdge(node, finalFailureGuard, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_GUARD))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_guard); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.id + " failure_guard is connected to unknown policy " + operPolicy.failure_guard); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_GUARD))); - } - } - } - // - // Now validate all the nodes/edges - // - for (NodeWrapper node : graph.vertexSet()) { - if (node instanceof TriggerNodeWrapper) { - System.out.println("Trigger Node " + node.toString()); - if (graph.inDegreeOf(node) > 0 ) { - // - // Really should NEVER get here unless someone messed up the code above. - // - throw new CompilerException("No inputs to event trigger"); - } - // - // Should always be 1, except in the future we may support multiple events - // - if (graph.outDegreeOf(node) > 1) { - throw new CompilerException("The event trigger should only go to ONE node"); - } - } else if (node instanceof FinalResultNodeWrapper) { - System.out.println("FinalResult Node " + node.toString()); - // - // FinalResult nodes should NEVER have an out edge - // - if (graph.outDegreeOf(node) > 0) { - throw new CompilerException("FinalResult nodes should never have any out edges."); - } - } else if (node instanceof PolicyNodeWrapper) { - System.out.println("Policy Node " + node.toString()); - // - // All Policy Nodes should have the 5 out degrees defined. - // - if (graph.outDegreeOf(node) != 6) { - throw new CompilerException("Policy node should ALWAYS have 6 out degrees."); - } - // - // Chenfei: All Policy Nodes should have at least 1 in degrees - // - if (graph.inDegreeOf(node) == 0) { - if (callback != null) { - callback.onWarning("Policy " + node.getID() + " is not reachable."); - } - } - } - for (LabeledEdge edge : graph.outgoingEdgesOf(node)){ - System.out.println(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID()); - } - } - } - } - - private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) { - for (Policy key : mapNodes.keySet()) { - if (key.id.equals(id)) { - return mapNodes.get(key); - } - } - return null; - } - - private interface NodeWrapper { - - public String getID(); - - } - - private static class TriggerNodeWrapper implements NodeWrapper { - public String closedLoopControlName; - - public TriggerNodeWrapper(String closedLoopControlName) { - this.closedLoopControlName = closedLoopControlName; - } - - @Override - public String toString() { - return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]"; - } - - @Override - public String getID() { - return closedLoopControlName; - } - - } - - private static class FinalResultNodeWrapper implements NodeWrapper { - - public FinalResult result; + for (Policy operPolicy : policy.getPolicies()) { + sum += operPolicy.getTimeout().intValue(); + } + if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) { + callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts."); + } + // + // For this version we can use a directed multigraph, in the future we may not be able to + // + DirectedGraph<NodeWrapper, LabeledEdge> graph = new DirectedMultigraph<>(new ClassBasedEdgeFactory<NodeWrapper, LabeledEdge>(LabeledEdge.class)); + // + // Check to see if the trigger Event is for OpenLoop, we do so by + // attempting to create a FinalResult object from it. If its a policy id, this should + // return null. + // + FinalResult triggerResult = FinalResult.toResult(policy.getControlLoop().getTrigger_policy()); + TriggerNodeWrapper triggerNode; + // + // Did this turn into a FinalResult object? + // + if (triggerResult != null) { + // + // Ensure they didn't use some other FinalResult code + // + if (triggerResult != FinalResult.FINAL_OPENLOOP) { + throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); + } + // + // They really shouldn't have any policies attached. + // + if ((policy.getPolicies() != null || policy.getPolicies().isEmpty())&& callback != null ) { + callback.onWarning("Open Loop policy contains policies. The policies will never be invoked."); + } + return; + // + } else { + // + // Ok, not a FinalResult object so let's assume that it is a Policy. Which it should be. + // + triggerNode = new TriggerNodeWrapper(policy.getControlLoop().getControlLoopName()); + } + // + // Add in the trigger node + // + graph.addVertex(triggerNode); + // + // Add in our Final Result nodes. All paths should end to these nodes. + // + FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS); + FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE); + FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT); + FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES); + FinalResultNodeWrapper finalFailureException = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION); + FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD); + graph.addVertex(finalSuccess); + graph.addVertex(finalFailure); + graph.addVertex(finalFailureTimeout); + graph.addVertex(finalFailureRetries); + graph.addVertex(finalFailureException); + graph.addVertex(finalFailureGuard); + // + // Work through the policies and add them in as nodes. + // + Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<>(); + for (Policy operPolicy : policy.getPolicies()) { + // + // Is it still ok to add? + // + if (!okToAdd(operPolicy, callback)) { + // + // Do not add it in + // + continue; + } + // + // Create wrapper policy node and save it into our map so we can + // easily retrieve it. + // + PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy); + mapNodes.put(operPolicy, node); + graph.addVertex(node); + // + // Is this the trigger policy? + // + if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) { + // + // Yes add an edge from our trigger event node to this policy + // + graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET"))); + } + } + // + // last sweep to connect remaining edges for policy results + // + for (Policy operPolicy : policy.getPolicies()) { + PolicyNodeWrapper node = mapNodes.get(operPolicy); + // + // Just ensure this has something + // + if (node == null) { + continue; + } + if (FinalResult.isResult(operPolicy.getSuccess(), FinalResult.FINAL_SUCCESS)) { + graph.addEdge(node, finalSuccess, new LabeledEdge(node, finalSuccess, new FinalResultEdgeWrapper(FinalResult.FINAL_SUCCESS))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getSuccess()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " success is connected to unknown policy " + operPolicy.getSuccess()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.SUCCESS))); + } + } + if (FinalResult.isResult(operPolicy.getFailure(), FinalResult.FINAL_FAILURE)) { + graph.addEdge(node, finalFailure, new LabeledEdge(node, finalFailure, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure is connected to unknown policy " + operPolicy.getFailure()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE))); + } + } + if (FinalResult.isResult(operPolicy.getFailure_timeout(), FinalResult.FINAL_FAILURE_TIMEOUT)) { + graph.addEdge(node, finalFailureTimeout, new LabeledEdge(node, finalFailureTimeout, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_timeout()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_timeout is connected to unknown policy " + operPolicy.getFailure_timeout()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_TIMEOUT))); + } + } + if (FinalResult.isResult(operPolicy.getFailure_retries(), FinalResult.FINAL_FAILURE_RETRIES)) { + graph.addEdge(node, finalFailureRetries, new LabeledEdge(node, finalFailureRetries, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_RETRIES))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_retries()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_retries is connected to unknown policy " + operPolicy.getFailure_retries()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_RETRIES))); + } + } + if (FinalResult.isResult(operPolicy.getFailure_exception(), FinalResult.FINAL_FAILURE_EXCEPTION)) { + graph.addEdge(node, finalFailureException, new LabeledEdge(node, finalFailureException, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_exception()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_exception is connected to unknown policy " + operPolicy.getFailure_exception()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_EXCEPTION))); + } + } + if (FinalResult.isResult(operPolicy.getFailure_guard(), FinalResult.FINAL_FAILURE_GUARD)) { + graph.addEdge(node, finalFailureGuard, new LabeledEdge(node, finalFailureGuard, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_GUARD))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_guard()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_guard is connected to unknown policy " + operPolicy.getFailure_guard()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_GUARD))); + } + } + } + // + // Now validate all the nodes/edges + // + for (NodeWrapper node : graph.vertexSet()) { + if (node instanceof TriggerNodeWrapper) { + LOGGER.info("Trigger Node " + node.toString()); + if (graph.inDegreeOf(node) > 0 ) { + // + // Really should NEVER get here unless someone messed up the code above. + // + throw new CompilerException("No inputs to event trigger"); + } + // + // Should always be 1, except in the future we may support multiple events + // + if (graph.outDegreeOf(node) > 1) { + throw new CompilerException("The event trigger should only go to ONE node"); + } + } else if (node instanceof FinalResultNodeWrapper) { + LOGGER.info("FinalResult Node " + node.toString()); + // + // FinalResult nodes should NEVER have an out edge + // + if (graph.outDegreeOf(node) > 0) { + throw new CompilerException("FinalResult nodes should never have any out edges."); + } + } else if (node instanceof PolicyNodeWrapper) { + LOGGER.info("Policy Node " + node.toString()); + // + // All Policy Nodes should have the 5 out degrees defined. + // + if (graph.outDegreeOf(node) != 6) { + throw new CompilerException("Policy node should ALWAYS have 6 out degrees."); + } + // + // All Policy Nodes should have at least 1 in degrees + // + if (graph.inDegreeOf(node) == 0 && callback != null) { + callback.onWarning("Policy " + node.getID() + " is not reachable."); + } + } + for (LabeledEdge edge : graph.outgoingEdgesOf(node)){ + LOGGER.info(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID()); + } + } + } + } + + private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) { + // + // Check the policy id and make sure its sane + // + boolean okToAdd = true; + if (operPolicy.getId() == null || operPolicy.getId().length() < 1) { + if (callback != null) { + callback.onError("Operational Policy has an bad ID"); + } + okToAdd = false; + } + // + // Check if they decided to make the ID a result object + // + if (PolicyResult.toResult(operPolicy.getId()) != null) { + if (callback != null) { + callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId()); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getId()) != null) { + if (callback != null) { + callback.onError("Policy id is set to a FinalResult " + operPolicy.getId()); + } + okToAdd = false; + } + // + // Check that the actor/recipe/target are valid + // + if (operPolicy.getActor() == null) { + if (callback != null) { + callback.onError("Policy actor is null"); + } + okToAdd = false; + } + // + // Construct a list for all valid actors + // + ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI"); + // + if (operPolicy.getActor() != null && (!actors.contains(operPolicy.getActor())) ) { + if (callback != null) { + callback.onError("Policy actor is invalid"); + } + okToAdd = false; + } + if (operPolicy.getRecipe() == null) { + if (callback != null) { + callback.onError("Policy recipe is null"); + } + okToAdd = false; + } + // + // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these) + // + ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>() + .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig")) + .put("AOTS", ImmutableList.of("checkMaintenanceWindow", "checkENodeBTicketHours", "checkEquipmentStatus", "checkEimStatus", "checkEquipmentMaintenance")) + .put("MSO", ImmutableList.of("VF Module Create")) + .put("SDNO", ImmutableList.of("health-diagnostic-type", "health-diagnostic", "health-diagnostic-history", "health-diagnostic-commands", "health-diagnostic-aes")) + .put("SDNR", ImmutableList.of("Restart", "Reboot")) + .build(); + // + if (operPolicy.getRecipe() != null && (!recipes.getOrDefault(operPolicy.getActor(), Collections.emptyList()).contains(operPolicy.getRecipe()))) { + if (callback != null) { + callback.onError("Policy recipe is invalid"); + } + okToAdd = false; + } + if (operPolicy.getTarget() == null) { + if (callback != null) { + callback.onError("Policy target is null"); + } + okToAdd = false; + } + if (operPolicy.getTarget() != null && operPolicy.getTarget().getType() != TargetType.VM && operPolicy.getTarget().getType() != TargetType.VFC && operPolicy.getTarget().getType() != TargetType.PNF) { + if (callback != null) { + callback.onError("Policy target is invalid"); + } + okToAdd = false; + } + // + // Check that policy results are connected to either default final * or another policy + // + if (FinalResult.toResult(operPolicy.getSuccess()) != null && operPolicy.getSuccess() != FinalResult.FINAL_SUCCESS.toString()) { + if (callback != null) { + callback.onError("Policy success is neither another policy nor FINAL_SUCCESS"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getFailure()) != null && operPolicy.getFailure() != FinalResult.FINAL_FAILURE.toString()) { + if (callback != null) { + callback.onError("Policy failure is neither another policy nor FINAL_FAILURE"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getFailure_retries()) != null && operPolicy.getFailure_retries() != FinalResult.FINAL_FAILURE_RETRIES.toString()) { + if (callback != null) { + callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null && operPolicy.getFailure_timeout() != FinalResult.FINAL_FAILURE_TIMEOUT.toString()) { + if (callback != null) { + callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getFailure_exception()) != null && operPolicy.getFailure_exception() != FinalResult.FINAL_FAILURE_EXCEPTION.toString()) { + if (callback != null) { + callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getFailure_guard()) != null && operPolicy.getFailure_guard() != FinalResult.FINAL_FAILURE_GUARD.toString()) { + if (callback != null) { + callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD"); + } + okToAdd = false; + } + return okToAdd; + } - public FinalResultNodeWrapper(FinalResult result) { - this.result = result; - } + private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) { + for (Entry<Policy, PolicyNodeWrapper> entry : mapNodes.entrySet()) { + if (entry.getKey().getId().equals(id)) { + return entry.getValue(); + } + } + return null; + } + + @FunctionalInterface + private interface NodeWrapper extends Serializable{ + public String getID(); + } + + private static class TriggerNodeWrapper implements NodeWrapper { + private static final long serialVersionUID = -187644087811478349L; + private String closedLoopControlName; + + public TriggerNodeWrapper(String closedLoopControlName) { + this.closedLoopControlName = closedLoopControlName; + } - @Override - public String toString() { - return "FinalResultNodeWrapper [result=" + result + "]"; - } + @Override + public String toString() { + return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]"; + } - @Override - public String getID() { - return result.toString(); - } - } - - private static class PolicyNodeWrapper implements NodeWrapper { + @Override + public String getID() { + return closedLoopControlName; + } + + } + + private static class FinalResultNodeWrapper implements NodeWrapper { + private static final long serialVersionUID = 8540008796302474613L; + private FinalResult result; - public Policy policy; - - public PolicyNodeWrapper(Policy operPolicy) { - this.policy = operPolicy; - } + public FinalResultNodeWrapper(FinalResult result) { + this.result = result; + } - @Override - public String toString() { - return "PolicyNodeWrapper [policy=" + policy + "]"; - } + @Override + public String toString() { + return "FinalResultNodeWrapper [result=" + result + "]"; + } - @Override - public String getID() { - return policy.id; - } - } - - private interface EdgeWrapper { - - public String getID(); - - } - - private static class TriggerEdgeWrapper implements EdgeWrapper { - - private String trigger; - - public TriggerEdgeWrapper(String trigger) { - this.trigger = trigger; - } + @Override + public String getID() { + return result.toString(); + } + } + + private static class PolicyNodeWrapper implements NodeWrapper { + private static final long serialVersionUID = 8170162175653823082L; + private Policy policy; + + public PolicyNodeWrapper(Policy operPolicy) { + this.policy = operPolicy; + } - @Override - public String getID() { - return trigger; - } + @Override + public String toString() { + return "PolicyNodeWrapper [policy=" + policy + "]"; + } - @Override - public String toString() { - return "TriggerEdgeWrapper [trigger=" + trigger + "]"; - } - - } - - private static class PolicyResultEdgeWrapper implements EdgeWrapper { - public PolicyResult policyResult; + @Override + public String getID() { + return policy.getId(); + } + } + + @FunctionalInterface + private interface EdgeWrapper extends Serializable{ + public String getID(); + + } + + private static class TriggerEdgeWrapper implements EdgeWrapper { + private static final long serialVersionUID = 2678151552623278863L; + private String trigger; + + public TriggerEdgeWrapper(String trigger) { + this.trigger = trigger; + } - public PolicyResultEdgeWrapper(PolicyResult policyResult) { - super(); - this.policyResult = policyResult; - } + @Override + public String getID() { + return trigger; + } - @Override - public String toString() { - return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]"; - } + @Override + public String toString() { + return "TriggerEdgeWrapper [trigger=" + trigger + "]"; + } + + } + + private static class PolicyResultEdgeWrapper implements EdgeWrapper { + private static final long serialVersionUID = 6078569477021558310L; + private PolicyResult policyResult; - @Override - public String getID() { - return policyResult.toString(); - } - - - } - - private static class FinalResultEdgeWrapper implements EdgeWrapper { + public PolicyResultEdgeWrapper(PolicyResult policyResult) { + super(); + this.policyResult = policyResult; + } - public FinalResult finalResult; - public FinalResultEdgeWrapper(FinalResult result) { - this.finalResult = result; - } + @Override + public String toString() { + return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]"; + } - @Override - public String toString() { - return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]"; - } - - @Override - public String getID() { - return finalResult.toString(); - } - } - - - private static class LabeledEdge extends DefaultEdge { + @Override + public String getID() { + return policyResult.toString(); + } + + + } + + private static class FinalResultEdgeWrapper implements EdgeWrapper { + private static final long serialVersionUID = -1486381946896779840L; + private FinalResult finalResult; + public FinalResultEdgeWrapper(FinalResult result) { + this.finalResult = result; + } - /** - * - */ - private static final long serialVersionUID = 579384429573385524L; - - private NodeWrapper from; - private NodeWrapper to; - private EdgeWrapper edge; - - public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) { - this.from = from; - this.to = to; - this.edge = edge; - } - - @SuppressWarnings("unused") - public NodeWrapper from() { - return from; - } - - @SuppressWarnings("unused") - public NodeWrapper to() { - return to; - } - - @SuppressWarnings("unused") - public EdgeWrapper edge() { - return edge; - } + @Override + public String toString() { + return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]"; + } + + @Override + public String getID() { + return finalResult.toString(); + } + } + + + private static class LabeledEdge extends DefaultEdge { + private static final long serialVersionUID = 579384429573385524L; + + private NodeWrapper from; + private NodeWrapper to; + private EdgeWrapper edge; + + public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) { + this.from = from; + this.to = to; + this.edge = edge; + } + + @SuppressWarnings("unused") + public NodeWrapper from() { + return from; + } + + @SuppressWarnings("unused") + public NodeWrapper to() { + return to; + } + + @SuppressWarnings("unused") + public EdgeWrapper edge() { + return edge; + } - @Override - public String toString() { - return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]"; - } - } + @Override + public String toString() { + return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]"; + } + } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java index 491e4c872..173e3e263 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java @@ -26,113 +26,108 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - import org.onap.policy.controlloop.compiler.CompilerException; import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback; import org.onap.policy.controlloop.policy.guard.Constraint; import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; public class ControlLoopGuardCompiler { - - public static ControlLoopGuard compile(ControlLoopGuard CLGuard, ControlLoopCompilerCallback callback) throws CompilerException { - // - // Ensure ControlLoopGuard has at least one guard policies - // - validateControlLoopGuard(CLGuard, callback); - // - // Ensure each guard policy has at least one constraints and all guard policies are unique - // - validateGuardPolicies(CLGuard.guards, callback); - // - // Ensure constraints for each guard policy are unique - // - validateConstraints(CLGuard.guards, callback); - - return CLGuard; - } - - public static ControlLoopGuard compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { - Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); - Object obj = yaml.load(yamlSpecification); - if (obj == null) { - throw new CompilerException("Could not parse yaml specification."); - } - if (! (obj instanceof ControlLoopGuard)) { - throw new CompilerException("Yaml could not parse specification into required ControlLoopGuard object"); - } - return ControlLoopGuardCompiler.compile((ControlLoopGuard) obj, callback); - } - - private static void validateControlLoopGuard(ControlLoopGuard CLGuard, ControlLoopCompilerCallback callback) throws CompilerException { - if (CLGuard == null) { - if (callback != null) { - callback.onError("ControlLoop Guard cannot be null"); - } - throw new CompilerException("ControlLoop Guard cannot be null"); - } - if (CLGuard.guard == null) { - if (callback != null) { - callback.onError("Guard version cannot be null"); - } - } - if (CLGuard.guards == null) { - if (callback != null) { - callback.onError("ControlLoop Guard should have at least one guard policies"); - } - } else if (CLGuard.guards.size() < 1) { - if (callback != null) { - callback.onError("ControlLoop Guard should have at least one guard policies"); - } - } - } - - private static void validateGuardPolicies(List<GuardPolicy> policies, ControlLoopCompilerCallback callback) throws CompilerException { - if (policies == null) { - if (callback != null) { - callback.onError("Guard policies should not be null"); - } - throw new CompilerException("Guard policies should not be null"); - } - // - // Ensure all guard policies are unique - // - Set<GuardPolicy> newSet = new HashSet<GuardPolicy>(policies); - if (newSet.size() != policies.size()) { - if (callback != null) { - callback.onWarning("There are duplicate guard policies"); - } - } - // - // Ensure each guard policy has at least one constraints - // - for (GuardPolicy policy : policies) { - if (policy.limit_constraints == null || policy.limit_constraints.size() < 1) { - if (callback != null) { - callback.onError("Guard policy " + policy.name + " does not have any limit constraint"); - } - throw new CompilerException("Guard policy " + policy.name + " does not have any limit constraint"); - } - } - } - - private static void validateConstraints(List<GuardPolicy> policies, ControlLoopCompilerCallback callback) throws CompilerException { - if (policies == null) { - if (callback != null) { - callback.onError("Guard policies should not be null"); - } - throw new CompilerException("Guard policies should not be null"); - } - for (GuardPolicy policy : policies) { - Set<Constraint> newSet = new HashSet<Constraint>(policy.limit_constraints); - if (newSet.size() != policy.limit_constraints.size()) { - if (callback != null) { - callback.onWarning("Guard policy " + policy.name + " has duplicate limit constraints"); - } - } - } - } - + + private ControlLoopGuardCompiler(){ + // Private Constructor + } + + public static ControlLoopGuard compile(ControlLoopGuard cLGuard, ControlLoopCompilerCallback callback) throws CompilerException { + // + // Ensure ControlLoopGuard has at least one guard policies + // + validateControlLoopGuard(cLGuard, callback); + // + // Ensure each guard policy has at least one constraints and all guard policies are unique + // + validateGuardPolicies(cLGuard.getGuards(), callback); + // + // Ensure constraints for each guard policy are unique + // + validateConstraints(cLGuard.getGuards(), callback); + + return cLGuard; + } + + public static ControlLoopGuard compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(yamlSpecification); + if (obj == null) { + throw new CompilerException("Could not parse yaml specification."); + } + if (! (obj instanceof ControlLoopGuard)) { + throw new CompilerException("Yaml could not parse specification into required ControlLoopGuard object"); + } + return ControlLoopGuardCompiler.compile((ControlLoopGuard) obj, callback); + } + + private static void validateControlLoopGuard(ControlLoopGuard cLGuard, ControlLoopCompilerCallback callback) throws CompilerException { + if (cLGuard == null) { + if (callback != null) { + callback.onError("ControlLoop Guard cannot be null"); + } + throw new CompilerException("ControlLoop Guard cannot be null"); + } + if (cLGuard.getGuard() == null && callback != null) { + callback.onError("Guard version cannot be null"); + } + if (cLGuard.getGuards() == null) { + if (callback != null) { + callback.onError("ControlLoop Guard should have at least one guard policies"); + } + } else if (cLGuard.getGuards().isEmpty() && callback != null) { + callback.onError("ControlLoop Guard should have at least one guard policies"); + } + } + + private static void validateGuardPolicies(List<GuardPolicy> policies, ControlLoopCompilerCallback callback) throws CompilerException { + if (policies == null) { + if (callback != null) { + callback.onError("Guard policies should not be null"); + } + throw new CompilerException("Guard policies should not be null"); + } + // + // Ensure all guard policies are unique + // + Set<GuardPolicy> newSet = new HashSet<>(policies); + if (newSet.size() != policies.size() && callback != null) { + callback.onWarning("There are duplicate guard policies"); + } + // + // Ensure each guard policy has at least one constraints + // + for (GuardPolicy policy : policies) { + if (policy.getLimit_constraints() == null || policy.getLimit_constraints().isEmpty()) { + if (callback != null) { + callback.onError("Guard policy " + policy.getName() + " does not have any limit constraint"); + } + throw new CompilerException("Guard policy " + policy.getName() + " does not have any limit constraint"); + } + } + } + + private static void validateConstraints(List<GuardPolicy> policies, ControlLoopCompilerCallback callback) throws CompilerException { + if (policies == null) { + if (callback != null) { + callback.onError("Guard policies should not be null"); + } + throw new CompilerException("Guard policies should not be null"); + } + for (GuardPolicy policy : policies) { + Set<Constraint> newSet = new HashSet<>(policy.getLimit_constraints()); + if (newSet.size() != policy.getLimit_constraints().size() && callback != null) { + callback.onWarning("Guard policy " + policy.getName() + " has duplicate limit constraints"); + } + } + } + } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java index 368424bfe..094e77891 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java @@ -21,119 +21,179 @@ package org.onap.policy.controlloop.policy; import java.util.LinkedList; +import java.util.List; import org.onap.policy.aai.PNF; import org.onap.policy.sdc.Resource; import org.onap.policy.sdc.Service; public class ControlLoop { - - public static String VERSION = "2.0.0"; - - public String controlLoopName; - public final String version = VERSION; - public LinkedList<Service> services; - public LinkedList<Resource> resources; - public PNF pnf; - public String trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); - public Integer timeout; - public Boolean abatement = false; - - public ControlLoop() { - - } - - public ControlLoop(ControlLoop controlLoop) { - this.controlLoopName = controlLoop.controlLoopName; - this.services = new LinkedList<Service>(); - if (controlLoop.services != null) { - for (Service service : controlLoop.services) { - this.services.add(service); - } - } - this.resources = new LinkedList<Resource>(); - if (controlLoop.resources != null) { - for (Resource resource: controlLoop.resources) { - this.resources.add(resource); - } - } - if (controlLoop.pnf != null) { - this.pnf = new PNF(controlLoop.pnf); - } - this.trigger_policy = controlLoop.trigger_policy; - this.timeout = controlLoop.timeout; - this.abatement = controlLoop.abatement; - } - @Override - public String toString() { - return "ControlLoop [controlLoopName=" + controlLoopName + ", version=" + version + ", services=" + services - + ", resources=" + resources + ", pnf=" + pnf + ", trigger_policy=" + trigger_policy + ", timeout=" - + timeout + ", abatement=" + abatement + "]"; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); - result = prime * result + ((pnf == null) ? 0 : pnf.hashCode()); - result = prime * result + ((resources == null) ? 0 : resources.hashCode()); - result = prime * result + ((services == null) ? 0 : services.hashCode()); - result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); - result = prime * result + ((trigger_policy == null) ? 0 : trigger_policy.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - result = prime * result + ((abatement == null) ? 0 : abatement.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ControlLoop other = (ControlLoop) obj; - if (controlLoopName == null) { - if (other.controlLoopName != null) - return false; - } else if (!controlLoopName.equals(other.controlLoopName)) - return false; - if (pnf == null) { - if (other.pnf != null) - return false; - } else if (!pnf.equals(other.pnf)) - return false; - if (resources == null) { - if (other.resources != null) - return false; - } else if (!resources.equals(other.resources)) - return false; - if (services == null) { - if (other.services != null) - return false; - } else if (!services.equals(other.services)) - return false; - if (timeout == null) { - if (other.timeout != null) - return false; - } else if (!timeout.equals(other.timeout)) - return false; - if (trigger_policy == null) { - if (other.trigger_policy != null) - return false; - } else if (!trigger_policy.equals(other.trigger_policy)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - if (abatement == null) { - if (other.abatement != null) - return false; - } else if (!abatement.equals(other.abatement)) - return false; - return true; - } - + + private static String VERSION = "2.0.0"; + + private String controlLoopName; + private String version = VERSION; + private List<Service> services; + private List<Resource> resources; + private PNF pnf; + private String trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + private Integer timeout; + private Boolean abatement = false; + + public ControlLoop() { + // Empty Constructor. + } + + public static String getVERSION(){ + return ControlLoop.VERSION; + } + + public String getControlLoopName() { + return controlLoopName; + } + + public void setControlLoopName(String controlLoopName) { + this.controlLoopName = controlLoopName; + } + + public List<Service> getServices() { + return services; + } + + public void setServices(List<Service> services) { + this.services = services; + } + + public List<Resource> getResources() { + return resources; + } + + public void setResources(List<Resource> resources) { + this.resources = resources; + } + + public String getTrigger_policy() { + return trigger_policy; + } + + public void setTrigger_policy(String trigger_policy) { + this.trigger_policy = trigger_policy; + } + + public Integer getTimeout() { + return timeout; + } + + public void setTimeout(Integer timeout) { + this.timeout = timeout; + } + + public Boolean getAbatement() { + return abatement; + } + + public void setAbatement(Boolean abatement) { + this.abatement = abatement; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version){ + this.version = version; + } + + public PNF getPnf() { + return pnf; + } + + public void setPnf(PNF pnf) { + this.pnf = pnf; + } + + public ControlLoop(ControlLoop controlLoop) { + this.controlLoopName = controlLoop.controlLoopName; + this.services = new LinkedList<>(); + if (controlLoop.services != null) { + for (Service service : controlLoop.services) { + this.services.add(service); + } + } + this.resources = new LinkedList<>(); + if (controlLoop.resources != null) { + for (Resource resource: controlLoop.resources) { + this.resources.add(resource); + } + } + this.trigger_policy = controlLoop.trigger_policy; + this.timeout = controlLoop.timeout; + this.abatement = controlLoop.abatement; + } + @Override + public String toString() { + return "ControlLoop [controlLoopName=" + controlLoopName + ", version=" + version + ", services=" + services + + ", resources=" + resources + ", trigger_policy=" + trigger_policy + ", timeout=" + + timeout + ", abatement=" + abatement + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); + result = prime * result + ((resources == null) ? 0 : resources.hashCode()); + result = prime * result + ((services == null) ? 0 : services.hashCode()); + result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); + result = prime * result + ((trigger_policy == null) ? 0 : trigger_policy.hashCode()); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + result = prime * result + ((abatement == null) ? 0 : abatement.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ControlLoop other = (ControlLoop) obj; + if (controlLoopName == null) { + if (other.controlLoopName != null) + return false; + } else if (!controlLoopName.equals(other.controlLoopName)) + return false; + if (resources == null) { + if (other.resources != null) + return false; + } else if (!resources.equals(other.resources)) + return false; + if (services == null) { + if (other.services != null) + return false; + } else if (!services.equals(other.services)) + return false; + if (timeout == null) { + if (other.timeout != null) + return false; + } else if (!timeout.equals(other.timeout)) + return false; + if (trigger_policy == null) { + if (other.trigger_policy != null) + return false; + } else if (!trigger_policy.equals(other.trigger_policy)) + return false; + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + if (abatement == null) { + if (other.abatement != null) + return false; + } else if (!abatement.equals(other.abatement)) + return false; + return true; + } + } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java index 013e242aa..e0c5839b1 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java @@ -20,48 +20,64 @@ package org.onap.policy.controlloop.policy; -import java.util.LinkedList; +import java.util.List; public class ControlLoopPolicy { - - public ControlLoop controlLoop; + + private ControlLoop controlLoop; - public LinkedList<Policy> policies; + private List<Policy> policies; - @Override - public String toString() { - return "ControlLoopPolicy [controlLoop=" + controlLoop + ", policies=" + policies + "]"; - } + public ControlLoop getControlLoop() { + return controlLoop; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((controlLoop == null) ? 0 : controlLoop.hashCode()); - result = prime * result + ((policies == null) ? 0 : policies.hashCode()); - return result; - } + public void setControlLoop(ControlLoop controlLoop) { + this.controlLoop = controlLoop; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ControlLoopPolicy other = (ControlLoopPolicy) obj; - if (controlLoop == null) { - if (other.controlLoop != null) - return false; - } else if (!controlLoop.equals(other.controlLoop)) - return false; - if (policies == null) { - if (other.policies != null) - return false; - } else if (!policies.equals(other.policies)) - return false; - return true; - } + public List<Policy> getPolicies() { + return policies; + } + + public void setPolicies(List<Policy> policies) { + this.policies = policies; + } + + @Override + public String toString() { + return "ControlLoopPolicy [controlLoop=" + controlLoop + ", policies=" + policies + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((controlLoop == null) ? 0 : controlLoop.hashCode()); + result = prime * result + ((policies == null) ? 0 : policies.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ControlLoopPolicy other = (ControlLoopPolicy) obj; + if (controlLoop == null) { + if (other.controlLoop != null) + return false; + } else if (!controlLoop.equals(other.controlLoop)) + return false; + if (policies == null) { + if (other.policies != null) + return false; + } else if (!policies.equals(other.policies)) + return false; + return true; + } } 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 f69e4b93c..8fa066109 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 @@ -21,73 +21,73 @@ package org.onap.policy.controlloop.policy; public enum FinalResult { - /** - * The Control Loop Policy successfully completed its Operations. - */ - FINAL_SUCCESS("Final_Success"), - /** - * The Control Loop Policy was an Open Loop and is finished. - */ - FINAL_OPENLOOP("Final_OpenLoop"), - /** - * The Control Loop Policy failed in its last Operation Policy. NOTE: Previous Operation Policies may have been successful. - */ - FINAL_FAILURE("Final_Failure"), - /** - * The Control Loop Policy failed because the overall timeout was met. - */ - FINAL_FAILURE_TIMEOUT("Final_Failure_Timeout"), - /** - * The Control Loop Policy failed because an Operation Policy met its retry limit. - */ - FINAL_FAILURE_RETRIES("Final_Failure_Retries"), - /** - * The Control Loop Policy failed due to an exception. - */ - FINAL_FAILURE_EXCEPTION("Final_Failure_Exception"), - /** - * The Control Loop Policy failed due to guard denied - */ - FINAL_FAILURE_GUARD("Final_Failure_Guard") - ; - - String result; - - private FinalResult(String result) { - this.result = result; - } - - public static FinalResult toResult(String result) { - if (result.equalsIgnoreCase(FINAL_SUCCESS.toString())) { - return FINAL_SUCCESS; - } - if (result.equalsIgnoreCase(FINAL_OPENLOOP.toString())) { - return FINAL_OPENLOOP; - } - if (result.equalsIgnoreCase(FINAL_FAILURE.toString())) { - return FINAL_FAILURE; - } - if (result.equalsIgnoreCase(FINAL_FAILURE_TIMEOUT.toString())) { - return FINAL_FAILURE_TIMEOUT; - } - if (result.equalsIgnoreCase(FINAL_FAILURE_RETRIES.toString())) { - return FINAL_FAILURE_RETRIES; - } - if (result.equalsIgnoreCase(FINAL_FAILURE_EXCEPTION.toString())) { - return FINAL_FAILURE_EXCEPTION; - } - if (result.equalsIgnoreCase(FINAL_FAILURE_GUARD.toString())) { - return FINAL_FAILURE_GUARD; - } - return null; - } - - public static boolean isResult(String result, FinalResult finalResult) { - FinalResult toResult = FinalResult.toResult(result); - if (toResult == null) { - return false; - } - return (toResult.equals(finalResult)); - } + /** + * The Control Loop Policy successfully completed its Operations. + */ + FINAL_SUCCESS("Final_Success"), + /** + * The Control Loop Policy was an Open Loop and is finished. + */ + FINAL_OPENLOOP("Final_OpenLoop"), + /** + * The Control Loop Policy failed in its last Operation Policy. NOTE: Previous Operation Policies may have been successful. + */ + FINAL_FAILURE("Final_Failure"), + /** + * The Control Loop Policy failed because the overall timeout was met. + */ + FINAL_FAILURE_TIMEOUT("Final_Failure_Timeout"), + /** + * The Control Loop Policy failed because an Operation Policy met its retry limit. + */ + FINAL_FAILURE_RETRIES("Final_Failure_Retries"), + /** + * The Control Loop Policy failed due to an exception. + */ + FINAL_FAILURE_EXCEPTION("Final_Failure_Exception"), + /** + * The Control Loop Policy failed due to guard denied + */ + FINAL_FAILURE_GUARD("Final_Failure_Guard") + ; + + String result; + + private FinalResult(String result) { + this.result = result; + } + + public static FinalResult toResult(String result) { + if (result.equalsIgnoreCase(FINAL_SUCCESS.toString())) { + return FINAL_SUCCESS; + } + if (result.equalsIgnoreCase(FINAL_OPENLOOP.toString())) { + return FINAL_OPENLOOP; + } + if (result.equalsIgnoreCase(FINAL_FAILURE.toString())) { + return FINAL_FAILURE; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_TIMEOUT.toString())) { + return FINAL_FAILURE_TIMEOUT; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_RETRIES.toString())) { + return FINAL_FAILURE_RETRIES; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_EXCEPTION.toString())) { + return FINAL_FAILURE_EXCEPTION; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_GUARD.toString())) { + return FINAL_FAILURE_GUARD; + } + return null; + } + + public static boolean isResult(String result, FinalResult finalResult) { + FinalResult toResult = FinalResult.toResult(result); + if (toResult == null) { + return false; + } + return toResult.equals(finalResult); + } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java index 4aaea12c9..4d0f03a06 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java @@ -24,61 +24,77 @@ import java.io.Serializable; public class OperationsAccumulateParams implements Serializable { - /** - * - */ - private static final long serialVersionUID = -3597358159130168247L; - - public String period; - public Integer limit; - - public OperationsAccumulateParams() { - - } - - public OperationsAccumulateParams(OperationsAccumulateParams ops) { - this.period = ops.period; - this.limit = ops.limit; - } - - public OperationsAccumulateParams(String period, Integer limit) { - this.period = period; - this.limit = limit; - } - - @Override - public String toString() { - return "OperationsAccumulateParams [period=" + period + ", limit=" + limit + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((period == null) ? 0 : period.hashCode()); - result = prime * result + ((limit == null) ? 0 : limit.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OperationsAccumulateParams other = (OperationsAccumulateParams) obj; - if (period == null) { - if (other.period != null) - return false; - } else if (!period.equals(other.period)) - return false; - if (limit == null) { - if (other.limit != null) - return false; - } else if (!limit.equals(other.limit)) - return false; - return true; - } + /** + * + */ + private static final long serialVersionUID = -3597358159130168247L; + + private String period; + private Integer limit; + + public OperationsAccumulateParams() { + // Does Nothing + } + + public OperationsAccumulateParams(OperationsAccumulateParams ops) { + this.period = ops.period; + this.limit = ops.limit; + } + + public OperationsAccumulateParams(String period, Integer limit) { + this.period = period; + this.limit = limit; + } + + public String getPeriod() { + return period; + } + + public void setPeriod(String period) { + this.period = period; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + @Override + public String toString() { + return "OperationsAccumulateParams [period=" + period + ", limit=" + limit + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((period == null) ? 0 : period.hashCode()); + result = prime * result + ((limit == null) ? 0 : limit.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OperationsAccumulateParams other = (OperationsAccumulateParams) obj; + if (period == null) { + if (other.period != null) + return false; + } else if (!period.equals(other.period)) + return false; + if (limit == null) { + if (other.limit != null) + return false; + } else if (!limit.equals(other.limit)) + return false; + return true; + } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java index fbc9558bd..03e3416b8 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java @@ -26,220 +26,328 @@ import java.util.UUID; public class Policy { - public String id = UUID.randomUUID().toString(); - public String name; - public String description; - public String actor; - public String recipe; - public Map<String, String> payload; - public Target target; - public OperationsAccumulateParams operationsAccumulateParams; - public Integer retry = 0; - public Integer timeout = 300; - public String success = FinalResult.FINAL_SUCCESS.toString(); - public String failure = FinalResult.FINAL_FAILURE.toString(); - public String failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); - public String failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); - public String failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); - public String failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); - - - public Policy() { - - } - - public Policy(String id) { - this.id = id; - } - - public Policy(String name, String actor, String recipe, Map<String, String> payload, Target target) { - this.name = name; - this.actor = actor; - this.recipe = recipe; - this.target = target; - if (payload != null) { -// this.payload = new LinkedList<Map<String, String>>(); - this.payload = Collections.unmodifiableMap(payload); - } - } - - public Policy(String name, String actor, String recipe, Map<String, String> payload, Target target, Integer retries, Integer timeout) { - this(name, actor, recipe, payload, target); - this.retry = retries; - this.timeout = timeout; - } - - public Policy(String id, String name, String description, String actor, Map<String, String> payload, Target target, String recipe, Integer retries, Integer timeout) { - this(name, actor, recipe, payload, target, retries, timeout); - this.id = id; - this.description = description; - } - - public Policy(Policy policy) { - this.id = policy.id; - this.name = policy.name; - this.description = policy.description; - this.actor = policy.actor; - this.recipe = policy.recipe; - if (policy.payload != null) { -// this.payload = new LinkedList<Map<String, String>>(); -// this.payload.addAll(policy.payload); - this.payload = Collections.unmodifiableMap(policy.payload); - } - this.target = policy.target; - this.operationsAccumulateParams = policy.operationsAccumulateParams; - this.retry = policy.retry; - this.timeout = policy.timeout; - this.success = policy.success; - this.failure = policy.failure; - this.failure_exception = policy.failure_exception; - this.failure_guard = policy.failure_guard; - this.failure_retries = policy.failure_retries; - this.failure_timeout = policy.failure_timeout; - } - - public boolean isValid() { - try { - if (id == null) { - throw new NullPointerException(); - } - if (name == null) { - throw new NullPointerException(); - } - if (actor == null) { - throw new NullPointerException(); - } - if (recipe == null) { - throw new NullPointerException(); - } - if (target == null) { - throw new NullPointerException(); - } - } catch (Exception e) { - return false; - } - - return true; - } - - @Override - public String toString() { - return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe=" - + recipe + ", payload=" + payload + ", target=" + target + ", operationsAccumulateParams=" + operationsAccumulateParams + ", retry=" + retry + ", timeout=" + timeout - + ", success=" + success + ", failure=" + failure + ", failure_retries=" + failure_retries - + ", failure_timeout=" + failure_timeout + ", failure_exception=" + failure_exception + ", failure_guard=" + failure_guard + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((actor == null) ? 0 : actor.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((failure == null) ? 0 : failure.hashCode()); - result = prime * result + ((failure_exception == null) ? 0 : failure_exception.hashCode()); - result = prime * result + ((failure_guard == null) ? 0 : failure_guard.hashCode()); - result = prime * result + ((failure_retries == null) ? 0 : failure_retries.hashCode()); - result = prime * result + ((failure_timeout == null) ? 0 : failure_timeout.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((payload == null) ? 0 : payload.hashCode()); - result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); - result = prime * result + ((retry == null) ? 0 : retry.hashCode()); - result = prime * result + ((success == null) ? 0 : success.hashCode()); - result = prime * result + ((target == null) ? 0 : target.hashCode()); - result = prime * result + ((operationsAccumulateParams == null) ? 0 : operationsAccumulateParams.hashCode()); - result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Policy other = (Policy) obj; - if (actor != other.actor) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (failure == null) { - if (other.failure != null) - return false; - } else if (!failure.equals(other.failure)) - return false; - if (failure_exception == null) { - if (other.failure_exception != null) - return false; - } else if (!failure_exception.equals(other.failure_exception)) - return false; - if (failure_guard == null) { - if (other.failure_guard != null) - return false; - } else if (!failure_guard.equals(other.failure_guard)) - return false; - if (failure_retries == null) { - if (other.failure_retries != null) - return false; - } else if (!failure_retries.equals(other.failure_retries)) - return false; - if (failure_timeout == null) { - if (other.failure_timeout != null) - return false; - } else if (!failure_timeout.equals(other.failure_timeout)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (payload == null) { - if (other.payload != null) - return false; - } else if (!payload.equals(other.payload)) - return false; - if (recipe == null) { - if (other.recipe != null) - return false; - } else if (!recipe.equals(other.recipe)) - return false; - if (retry == null) { - if (other.retry != null) - return false; - } else if (!retry.equals(other.retry)) - return false; - if (success == null) { - if (other.success != null) - return false; - } else if (!success.equals(other.success)) - return false; - if (operationsAccumulateParams == null) { - if (other.operationsAccumulateParams != null) - return false; - } else if (!operationsAccumulateParams.equals(other.operationsAccumulateParams)) - return false; - if (target == null) { - if (other.target != null) - return false; - } else if (!target.equals(other.target)) - return false; - if (timeout == null) { - if (other.timeout != null) - return false; - } else if (!timeout.equals(other.timeout)) - return false; - return true; - } - + private String id = UUID.randomUUID().toString(); + private String name; + private String description; + private String actor; + private String recipe; + private Map<String, String> payload; + private Target target; + private OperationsAccumulateParams operationsAccumulateParams; + private Integer retry = 0; + private Integer timeout = 300; + private String success = FinalResult.FINAL_SUCCESS.toString(); + private String failure = FinalResult.FINAL_FAILURE.toString(); + private String failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + private String failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + private String failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + private String failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + + + public Policy() { + //Does Nothing Empty Constructor + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getActor() { + return actor; + } + + public void setActor(String actor) { + this.actor = actor; + } + + public String getRecipe() { + return recipe; + } + + public void setRecipe(String recipe) { + this.recipe = recipe; + } + + public Map<String, String> getPayload() { + return payload; + } + + public void setPayload(Map<String, String> payload) { + this.payload = payload; + } + + public Target getTarget() { + return target; + } + + public void setTarget(Target target) { + this.target = target; + } + + public OperationsAccumulateParams getOperationsAccumulateParams() { + return operationsAccumulateParams; + } + + public void setOperationsAccumulateParams(OperationsAccumulateParams operationsAccumulateParams) { + this.operationsAccumulateParams = operationsAccumulateParams; + } + + public Integer getRetry() { + return retry; + } + + public void setRetry(Integer retry) { + this.retry = retry; + } + + public Integer getTimeout() { + return timeout; + } + + public void setTimeout(Integer timeout) { + this.timeout = timeout; + } + + public String getSuccess() { + return success; + } + + public void setSuccess(String success) { + this.success = success; + } + + public String getFailure() { + return failure; + } + + public void setFailure(String failure) { + this.failure = failure; + } + + public String getFailure_retries() { + return failure_retries; + } + + public void setFailure_retries(String failure_retries) { + this.failure_retries = failure_retries; + } + + public String getFailure_timeout() { + return failure_timeout; + } + + public void setFailure_timeout(String failure_timeout) { + this.failure_timeout = failure_timeout; + } + + public String getFailure_exception() { + return failure_exception; + } + + public void setFailure_exception(String failure_exception) { + this.failure_exception = failure_exception; + } + + public String getFailure_guard() { + return failure_guard; + } + + public void setFailure_guard(String failure_guard) { + this.failure_guard = failure_guard; + } + + public Policy(String id) { + this.id = id; + } + + public Policy(String name, String actor, String recipe, Map<String, String> payload, Target target) { + this.name = name; + this.actor = actor; + this.recipe = recipe; + this.target = target; + if (payload != null) { + this.payload = Collections.unmodifiableMap(payload); + } + } + + public Policy(String name, String actor, String recipe, Map<String, String> payload, Target target, Integer retries, Integer timeout) { + this(name, actor, recipe, payload, target); + this.retry = retries; + this.timeout = timeout; + } + + public Policy(String id, String name, String description, String actor, Map<String, String> payload, Target target, String recipe, Integer retries, Integer timeout) { + this(name, actor, recipe, payload, target, retries, timeout); + this.id = id; + this.description = description; + } + + public Policy(Policy policy) { + this.id = policy.id; + this.name = policy.name; + this.description = policy.description; + this.actor = policy.actor; + this.recipe = policy.recipe; + if (policy.payload != null) { + this.payload = Collections.unmodifiableMap(policy.payload); + } + this.target = policy.target; + this.operationsAccumulateParams = policy.operationsAccumulateParams; + this.retry = policy.retry; + this.timeout = policy.timeout; + this.success = policy.success; + this.failure = policy.failure; + this.failure_exception = policy.failure_exception; + this.failure_guard = policy.failure_guard; + this.failure_retries = policy.failure_retries; + this.failure_timeout = policy.failure_timeout; + } + + public boolean isValid() { + if(id==null || name==null || actor==null|| recipe==null || target==null){ + return false; + } + return true; + } + + @Override + public String toString() { + return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe=" + + recipe + ", payload=" + payload + ", target=" + target + ", operationsAccumulateParams=" + operationsAccumulateParams + ", retry=" + retry + ", timeout=" + timeout + + ", success=" + success + ", failure=" + failure + ", failure_retries=" + failure_retries + + ", failure_timeout=" + failure_timeout + ", failure_exception=" + failure_exception + ", failure_guard=" + failure_guard + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actor == null) ? 0 : actor.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((failure == null) ? 0 : failure.hashCode()); + result = prime * result + ((failure_exception == null) ? 0 : failure_exception.hashCode()); + result = prime * result + ((failure_guard == null) ? 0 : failure_guard.hashCode()); + result = prime * result + ((failure_retries == null) ? 0 : failure_retries.hashCode()); + result = prime * result + ((failure_timeout == null) ? 0 : failure_timeout.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((payload == null) ? 0 : payload.hashCode()); + result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); + result = prime * result + ((retry == null) ? 0 : retry.hashCode()); + result = prime * result + ((success == null) ? 0 : success.hashCode()); + result = prime * result + ((target == null) ? 0 : target.hashCode()); + result = prime * result + ((operationsAccumulateParams == null) ? 0 : operationsAccumulateParams.hashCode()); + result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Policy other = (Policy) obj; + if (actor != other.actor) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (failure == null) { + if (other.failure != null) + return false; + } else if (!failure.equals(other.failure)) + return false; + if (failure_exception == null) { + if (other.failure_exception != null) + return false; + } else if (!failure_exception.equals(other.failure_exception)) + return false; + if (failure_guard == null) { + if (other.failure_guard != null) + return false; + } else if (!failure_guard.equals(other.failure_guard)) + return false; + if (failure_retries == null) { + if (other.failure_retries != null) + return false; + } else if (!failure_retries.equals(other.failure_retries)) + return false; + if (failure_timeout == null) { + if (other.failure_timeout != null) + return false; + } else if (!failure_timeout.equals(other.failure_timeout)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (payload == null) { + if (other.payload != null) + return false; + } else if (!payload.equals(other.payload)) + return false; + if (recipe == null) { + if (other.recipe != null) + return false; + } else if (!recipe.equals(other.recipe)) + return false; + if (retry == null) { + if (other.retry != null) + return false; + } else if (!retry.equals(other.retry)) + return false; + if (success == null) { + if (other.success != null) + return false; + } else if (!success.equals(other.success)) + return false; + if (operationsAccumulateParams == null) { + if (other.operationsAccumulateParams != null) + return false; + } else if (!operationsAccumulateParams.equals(other.operationsAccumulateParams)) + return false; + if (target == null) { + if (other.target != null) + return false; + } else if (!target.equals(other.target)) + return false; + if (timeout == null) { + if (other.timeout != null) + return false; + } else if (!timeout.equals(other.timeout)) + return false; + return true; + } + } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java index 0a504339f..574e14225 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java @@ -21,62 +21,63 @@ package org.onap.policy.controlloop.policy; public enum PolicyResult { - /** - * Operation was successful. - */ - SUCCESS("Success"), - /** - * Operation failed. - */ - FAILURE("Failure"), - /** - * Operation failed due to maximum retries being met. - */ - FAILURE_RETRIES("Failure_Retries"), - /** - * Operation failed due to timeout occurring. - */ - FAILURE_TIMEOUT("Failure_Timeout"), - /** - * Operation failed due to an exception. - */ - FAILURE_EXCEPTION("Failure_Exception"), - /** - * Operation failed since Guard did not permit. - */ - FAILURE_GUARD("Failure_Guard") - ; - - private String result; - - private PolicyResult(String result) { - this.result = result; - } - - public String toString() { - return this.result; - } - - public static PolicyResult toResult(String result) { - if (result.equalsIgnoreCase(SUCCESS.toString())) { - return SUCCESS; - } - if (result.equalsIgnoreCase(FAILURE.toString())) { - return FAILURE; - } - if (result.equalsIgnoreCase(FAILURE_RETRIES.toString())) { - return FAILURE_RETRIES; - } - if (result.equalsIgnoreCase(FAILURE_TIMEOUT.toString())) { - return FAILURE_TIMEOUT; - } - if (result.equalsIgnoreCase(FAILURE_EXCEPTION.toString())) { - return FAILURE_EXCEPTION; - } - if (result.equalsIgnoreCase(FAILURE_GUARD.toString())) { - return FAILURE_GUARD; - } - return null; - } + /** + * Operation was successful. + */ + SUCCESS("Success"), + /** + * Operation failed. + */ + FAILURE("Failure"), + /** + * Operation failed due to maximum retries being met. + */ + FAILURE_RETRIES("Failure_Retries"), + /** + * Operation failed due to timeout occurring. + */ + FAILURE_TIMEOUT("Failure_Timeout"), + /** + * Operation failed due to an exception. + */ + FAILURE_EXCEPTION("Failure_Exception"), + /** + * Operation failed since Guard did not permit. + */ + FAILURE_GUARD("Failure_Guard") + ; + + private String result; + + private PolicyResult(String result) { + this.result = result; + } + + @Override + public String toString() { + return this.result; + } + + public static PolicyResult toResult(String result) { + if (result.equalsIgnoreCase(SUCCESS.toString())) { + return SUCCESS; + } + if (result.equalsIgnoreCase(FAILURE.toString())) { + return FAILURE; + } + if (result.equalsIgnoreCase(FAILURE_RETRIES.toString())) { + return FAILURE_RETRIES; + } + if (result.equalsIgnoreCase(FAILURE_TIMEOUT.toString())) { + return FAILURE_TIMEOUT; + } + if (result.equalsIgnoreCase(FAILURE_EXCEPTION.toString())) { + return FAILURE_EXCEPTION; + } + if (result.equalsIgnoreCase(FAILURE_GUARD.toString())) { + return FAILURE_GUARD; + } + return null; + } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java index ba05e9b69..bc5b934b2 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java @@ -24,68 +24,84 @@ import java.io.Serializable; public class Target implements Serializable { - /** - * - */ - private static final long serialVersionUID = 2180988443264988319L; - - public String resourceID; - public TargetType type; + /** + * + */ + private static final long serialVersionUID = 2180988443264988319L; + + private String resourceID; + private TargetType type; - public Target() { - - } - - public Target(TargetType type) { - this.type = type; - } - - public Target(String resourceID) { - this.resourceID = resourceID; - } - - public Target(TargetType type, String resourceID) { - this.type = type; - this.resourceID = resourceID; - } - - public Target(Target target) { - this.type = target.type; - this.resourceID = target.resourceID; - } - - @Override - public String toString() { - return "Target [type=" + type + ", resourceID=" + resourceID + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + ((resourceID == null) ? 0 : resourceID.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Target other = (Target) obj; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - if (resourceID == null) { - if (other.resourceID != null) - return false; - } else if (!resourceID.equals(other.resourceID)) - return false; - return true; - } + public Target() { + //Does Nothing Empty Constructor + } + + public String getResourceID() { + return resourceID; + } + + public void setResourceID(String resourceID) { + this.resourceID = resourceID; + } + + public TargetType getType() { + return type; + } + + public void setType(TargetType type) { + this.type = type; + } + + public Target(TargetType type) { + this.type = type; + } + + public Target(String resourceID) { + this.resourceID = resourceID; + } + + public Target(TargetType type, String resourceID) { + this.type = type; + this.resourceID = resourceID; + } + + public Target(Target target) { + this.type = target.type; + this.resourceID = target.resourceID; + } + + @Override + public String toString() { + return "Target [type=" + type + ", resourceID=" + resourceID + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((type == null) ? 0 : type.hashCode()); + result = prime * result + ((resourceID == null) ? 0 : resourceID.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Target other = (Target) obj; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + if (resourceID == null) { + if (other.resourceID != null) + return false; + } else if (!resourceID.equals(other.resourceID)) + return false; + return true; + } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java index 30ee323bf..abf851a75 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java @@ -21,19 +21,20 @@ package org.onap.policy.controlloop.policy; public enum TargetType { - VM("VM"), - PNF("PNF"), - VFC("VFC") - ; - - private String targetType; - - private TargetType(String targetType) { - this.targetType = targetType; - } - - public String toString() { - return this.targetType; - } + VM("VM"), + PNF("PNF"), + VFC("VFC") + ; + + private String target; + + private TargetType(String targetType) { + this.target = targetType; + } + + @Override + public String toString() { + return this.target; + } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java index 1947c53fc..b40e8858e 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java @@ -33,283 +33,274 @@ import org.onap.policy.sdc.Resource; import org.onap.policy.sdc.Service; public interface ControlLoopPolicyBuilder { - - /** - * Adds one or more services to the ControlLoop - * - * - * @param service - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException; - - /** - * @param services - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException; - - /** - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder removeAllServices() throws BuilderException; - - /** - * Adds one or more resources to the ControlLoop - * - * - * @param resource - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException; - - /** - * @param resources - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException; - - /** - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder removeAllResources() throws BuilderException; - - /** - * @param pnf - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder setPNF(PNF pnf) throws BuilderException; - - /** - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder removePNF() throws BuilderException; - - /** - * @param abatement - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException; - - - /** - * Sets the overall timeout value for the Control Loop. If any operational policies have retries and timeouts, - * then this overall timeout value should exceed all those values. - * - * @param timeout - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder setTimeout(Integer timeout) throws BuilderException; - - /** - * Scans the operational policies and calculate an minimum overall timeout for the Control Loop. - * - * - * @return Integer - */ - public Integer calculateTimeout(); - - /** - * Sets the initial trigger policy when a DCAE Closed Loop Event arrives in the ONAP Policy Platform. - * - * - * @param name - * @param description - * @param actor - * @param target - * @param recipe - * @param retries - * @param timeout - * @return Policy - * @throws BuilderException - */ - public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout) throws BuilderException; - - /** - * - * Changes the trigger policy to point to another existing Policy. - * - * - * @param id - * @return ControlLoop - * @throws BuilderException - */ - public ControlLoop setTriggerPolicy(String id) throws BuilderException; - - /** - * @return - */ - public boolean isOpenLoop(); - - /** - * @return - * @throws BuilderException - */ - public Policy getTriggerPolicy() throws BuilderException; - - /** - * Simply returns a copy of the ControlLoop information. - * - * - * @return ControlLoop - */ - public ControlLoop getControlLoop(); - - /** - * Creates a policy that is chained to the result of another Policy. - * - * - * @param name - * @param description - * @param actor - * @param target - * @param recipe - * @param retries - * @param timeout - * @param policyID - * @param results - * @return - * @throws BuilderException - */ - public Policy setPolicyForPolicyResult(String name, String description, String actor, - Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException; - - - /** - * Sets the policy result(s) to an existing Operational Policy. - * - * - * @param policyResultID - * @param policyID - * @param results - * @return - * @throws BuilderException - */ - public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) throws BuilderException; - - /** - * Removes an Operational Policy. Be mindful that if any other Operational Policies have results that point to this policy, any - * policies that have results pointing to this policy will have their result reset to the appropriate default FINAL_* result. - * - * - * @param policyID - * @return - * @throws BuilderException - */ - public boolean removePolicy(String policyID) throws BuilderException; - - /** - * Resets a policy's results to defualt FINAL_* codes. - * - * - * @return Policy - * @throws BuilderException - Policy does not exist - */ - public Policy resetPolicyResults(String policyID) throws BuilderException; - - /** - * Removes all existing Operational Policies and reverts back to an Open Loop. - * - * @return - */ - public ControlLoopPolicyBuilder removeAllPolicies(); - - /** - * Adds an operationsAccumulateParams to an existing operational policy - * - * @return Policy - * @throws BuilderException - Policy does not exist - */ - public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException; - - /** - * This will compile and build the YAML specification for the Control Loop Policy. Please iterate the Results object for details. - * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the - * YAML. - * - * @return Results - */ - public Results buildSpecification(); - - /** - * The Factory is used to build a ControlLoopPolicyBuilder implementation. - * - * @author pameladragosh - * - */ - public static class Factory { - - /** - * Builds a basic Control Loop with an overall timeout. Use this method if you wish to create an OpenLoop, or if you - * want to interactively build a Closed Loop. - * - * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. - * @param timeout - Overall timeout for the Closed Loop to execute. - * @return ControlLoopPolicyBuilder object - * @throws BuilderException - */ - public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout) throws BuilderException { - - ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout); - - return builder; - } - - /** - * Build a Control Loop for a resource and services associated with the resource. - * - * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. - * @param timeout - Overall timeout for the Closed Loop to execute. - * @param resource - Resource this closed loop is for. Should come from ASDC, but if not available use resourceName to distinguish. - * @param services - Zero or more services associated with this resource. Should come from ASDC, but if not available use serviceName to distinguish. - * @return ControlLoopPolicyBuilder object - * @throws BuilderException - */ - public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { - - ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, resource, services); - - return builder; - } - - /** - * @param controlLoopName - * @param timeout - * @param service - * @param resources - * @return - * @throws BuilderException - */ - public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, Service service, Resource... resources) throws BuilderException { - - ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, service, resources); - - return builder; - } - - /** - * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. - * @param timeout - Overall timeout for the Closed Loop to execute. - * @param pnf - Physical Network Function. Should come from AIC, but if not available use well-known name to distinguish. Eg. eNodeB - * @return ControlLoopPolicyBuilder object - * @throws BuilderException - */ - public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, PNF pnf) throws BuilderException { - - ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, pnf); - - return builder; - } - } + + /** + * Adds one or more services to the ControlLoop + * + * + * @param service + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException; + + /** + * @param services + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException; + + /** + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeAllServices() throws BuilderException; + + /** + * Adds one or more resources to the ControlLoop + * + * + * @param resource + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException; + + /** + * @param resources + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException; + + /** + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeAllResources() throws BuilderException; + + /** + * @param pnf + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder setPNF(PNF pnf) throws BuilderException; + + /** + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removePNF() throws BuilderException; + + /** + * @param abatement + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException; + + + /** + * Sets the overall timeout value for the Control Loop. If any operational policies have retries and timeouts, + * then this overall timeout value should exceed all those values. + * + * @param timeout + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder setTimeout(Integer timeout) throws BuilderException; + + /** + * Scans the operational policies and calculate an minimum overall timeout for the Control Loop. + * + * + * @return Integer + */ + public Integer calculateTimeout(); + + /** + * Sets the initial trigger policy when a DCAE Closed Loop Event arrives in the ONAP Policy Platform. + * + * + * @param name + * @param description + * @param actor + * @param target + * @param recipe + * @param retries + * @param timeout + * @return Policy + * @throws BuilderException + */ + public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout) throws BuilderException; + + /** + * + * Changes the trigger policy to point to another existing Policy. + * + * + * @param id + * @return ControlLoop + * @throws BuilderException + */ + public ControlLoop setTriggerPolicy(String id) throws BuilderException; + + /** + * @return + */ + public boolean isOpenLoop(); + + /** + * @return + * @throws BuilderException + */ + public Policy getTriggerPolicy() throws BuilderException; + + /** + * Simply returns a copy of the ControlLoop information. + * + * + * @return ControlLoop + */ + public ControlLoop getControlLoop(); + + /** + * Creates a policy that is chained to the result of another Policy. + * + * + * @param name + * @param description + * @param actor + * @param target + * @param recipe + * @param retries + * @param timeout + * @param policyID + * @param results + * @return + * @throws BuilderException + */ + public Policy setPolicyForPolicyResult(String name, String description, String actor, + Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException; + + + /** + * Sets the policy result(s) to an existing Operational Policy. + * + * + * @param policyResultID + * @param policyID + * @param results + * @return + * @throws BuilderException + */ + public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) throws BuilderException; + + /** + * Removes an Operational Policy. Be mindful that if any other Operational Policies have results that point to this policy, any + * policies that have results pointing to this policy will have their result reset to the appropriate default FINAL_* result. + * + * + * @param policyID + * @return + * @throws BuilderException + */ + public boolean removePolicy(String policyID) throws BuilderException; + + /** + * Resets a policy's results to defualt FINAL_* codes. + * + * + * @return Policy + * @throws BuilderException - Policy does not exist + */ + public Policy resetPolicyResults(String policyID) throws BuilderException; + + /** + * Removes all existing Operational Policies and reverts back to an Open Loop. + * + * @return + */ + public ControlLoopPolicyBuilder removeAllPolicies(); + + /** + * Adds an operationsAccumulateParams to an existing operational policy + * + * @return Policy + * @throws BuilderException - Policy does not exist + */ + public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException; + + /** + * This will compile and build the YAML specification for the Control Loop Policy. Please iterate the Results object for details. + * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the + * YAML. + * + * @return Results + */ + public Results buildSpecification(); + + /** + * The Factory is used to build a ControlLoopPolicyBuilder implementation. + * + * @author pameladragosh + * + */ + public static class Factory { + private Factory(){ + // Private Constructor. + } + + /** + * Builds a basic Control Loop with an overall timeout. Use this method if you wish to create an OpenLoop, or if you + * want to interactively build a Closed Loop. + * + * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. + * @param timeout - Overall timeout for the Closed Loop to execute. + * @return ControlLoopPolicyBuilder object + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout) throws BuilderException { + return new ControlLoopPolicyBuilderImpl(controlLoopName, timeout); + } + + /** + * Build a Control Loop for a resource and services associated with the resource. + * + * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. + * @param timeout - Overall timeout for the Closed Loop to execute. + * @param resource - Resource this closed loop is for. Should come from ASDC, but if not available use resourceName to distinguish. + * @param services - Zero or more services associated with this resource. Should come from ASDC, but if not available use serviceName to distinguish. + * @return ControlLoopPolicyBuilder object + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { + return new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, resource, services); + } + + /** + * @param controlLoopName + * @param timeout + * @param service + * @param resources + * @return + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, Service service, Resource... resources) throws BuilderException { + return new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, service, resources); + } + + /** + * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. + * @param timeout - Overall timeout for the Closed Loop to execute. + * @param pnf - Physical Network Function. Should come from AIC, but if not available use well-known name to distinguish. Eg. eNodeB + * @return ControlLoopPolicyBuilder object + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, PNF pnf) throws BuilderException { + return new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, pnf); + } + } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java index 131d7d766..18c80eed3 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java @@ -24,10 +24,6 @@ import java.util.LinkedList; import java.util.Map; import java.util.UUID; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.DumperOptions.FlowStyle; -import org.yaml.snakeyaml.Yaml; - import org.onap.policy.aai.PNF; import org.onap.policy.controlloop.compiler.CompilerException; import org.onap.policy.controlloop.compiler.ControlLoopCompiler; @@ -45,348 +41,355 @@ import org.onap.policy.controlloop.policy.builder.MessageLevel; import org.onap.policy.controlloop.policy.builder.Results; import org.onap.policy.sdc.Resource; import org.onap.policy.sdc.Service; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { + private static Logger logger = LoggerFactory.getLogger(ControlLoopPolicyBuilderImpl.class.getName()); + private ControlLoopPolicy policy; + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) throws BuilderException { + policy = new ControlLoopPolicy(); + ControlLoop controlLoop = new ControlLoop(); + controlLoop.setControlLoopName(controlLoopName); + controlLoop.setTimeout(timeout); + policy.setControlLoop(controlLoop); + } + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { + this(controlLoopName, timeout); + this.addResource(resource); + this.addService(services); + } + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, PNF pnf) throws BuilderException { + this(controlLoopName, timeout); + this.setPNF(pnf); + } + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Service service, Resource[] resources) throws BuilderException { + this(controlLoopName, timeout); + this.addService(service); + this.addResource(resources); + } + + @Override + public ControlLoopPolicyBuilder removePNF() throws BuilderException { + policy.getControlLoop().setPnf(null); + return this; + } - private ControlLoopPolicy policy; - - public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) throws BuilderException { - policy = new ControlLoopPolicy(); - policy.controlLoop = new ControlLoop(); - policy.controlLoop.controlLoopName = controlLoopName; - policy.controlLoop.timeout = timeout; - } - - public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { - this(controlLoopName, timeout); - this.addResource(resource); - this.addService(services); - } - - public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, PNF pnf) throws BuilderException { - this(controlLoopName, timeout); - this.setPNF(pnf); - } - - public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Service service, Resource[] resources) throws BuilderException { - this(controlLoopName, timeout); - this.addService(service); - this.addResource(resources); - } - - @Override - public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException { - if (services == null) { - throw new BuilderException("Service must not be null"); - } - for (Service service : services) { - if (service.serviceUUID == null) { - if (service.serviceName == null || service.serviceName.length() < 1) { - throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); - } - } - if (policy.controlLoop.services == null) { - policy.controlLoop.services = new LinkedList<Service>(); - } - policy.controlLoop.services.add(service); - } - return this; - } - - @Override - public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException { - if (services == null) { + @Override + public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException { + if (services == null) { throw new BuilderException("Service must not be null"); } - if (policy.controlLoop.services == null) { + for (Service service : services) { + if (service.getServiceUUID() == null) { + if (service.getServiceName() == null || service.getServiceName().length() < 1) { + throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); + } + if(policy.getControlLoop().getServices()==null){ + policy.getControlLoop().setServices(new LinkedList<>()); + } + policy.getControlLoop().getServices().add(service); + } + } + return this; + } + + @Override + public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException { + if (services == null) { + throw new BuilderException("Service must not be null"); + } + if (policy.getControlLoop().getServices() == null) { throw new BuilderException("No existing services to remove"); } for (Service service : services) { - if (service.serviceUUID == null) { - if (service.serviceName == null || service.serviceName.length() < 1) { + if (service.getServiceUUID() == null) { + if (service.getServiceName() == null || service.getServiceName().length() < 1) { throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); } } - boolean removed = policy.controlLoop.services.remove(service); + boolean removed = policy.getControlLoop().getServices().remove(service); if (!removed) { - throw new BuilderException("Unknown service " + service.serviceName); + throw new BuilderException("Unknown service " + service.getServiceName()); } } return this; - } + } - @Override - public ControlLoopPolicyBuilder removeAllServices() throws BuilderException { - policy.controlLoop.services.clear(); + @Override + public ControlLoopPolicyBuilder removeAllServices() throws BuilderException { + policy.getControlLoop().getServices().clear(); return this; - } - - - @Override - public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException { - if (resources == null) { - throw new BuilderException("resources must not be null"); - } - for (Resource resource : resources) { - if (resource.resourceUUID == null) { - if (resource.resourceName == null || resource.resourceName.length() <= 0) { - throw new BuilderException("Invalid resource - need either resourceUUID or resourceName"); - } - } - if (policy.controlLoop.resources == null) { - policy.controlLoop.resources = new LinkedList<Resource>(); - } - policy.controlLoop.resources.add(resource); - } - return this; - } + } - @Override - public ControlLoopPolicyBuilder setPNF(PNF pnf) throws BuilderException { - if (pnf == null) { - throw new BuilderException("PNF must not be null"); - } - if (pnf.PNFName == null) { - if (pnf.PNFType == null) { - throw new BuilderException("Invalid PNF - need either pnfName or pnfType"); - } - } - policy.controlLoop.pnf = pnf; - return this; - } - - @Override - public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException{ - if (abatement == null) { - throw new BuilderException("abatement must not be null"); - } - policy.controlLoop.abatement = abatement; - return this; - } - - @Override - public ControlLoopPolicyBuilder setTimeout(Integer timeout) { - policy.controlLoop.timeout = timeout; - return this; - } - - @Override - public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, - Map<String, String> payload, Integer retries, Integer timeout) throws BuilderException { - - Policy trigger = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); - - policy.controlLoop.trigger_policy = trigger.id; - - this.addNewPolicy(trigger); - // - // Return a copy of the policy - // - return new Policy(trigger); - } + + @Override + public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException { + if (resources == null) { + throw new BuilderException("resources must not be null"); + } + for (Resource resource : resources) { + if (resource.getResourceUUID() == null) { + if (resource.getResourceName() == null || resource.getResourceName().length() <= 0) { + throw new BuilderException("Invalid resource - need either resourceUUID or resourceName"); + } + } + if(policy.getControlLoop().getResources()==null){ + policy.getControlLoop().setResources(new LinkedList<>()); + } + policy.getControlLoop().getResources().add(resource); + } + return this; + } + + @Override + public ControlLoopPolicyBuilder setPNF(PNF pnf) throws BuilderException { + if (pnf == null) { + throw new BuilderException("PNF must not be null"); + } + if (pnf.PNFName == null) { + if (pnf.PNFType == null) { + throw new BuilderException("Invalid PNF - need either pnfName or pnfType"); + } + } + policy.getControlLoop().setPnf(pnf); + return this; + } + + @Override + public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException{ + if (abatement == null) { + throw new BuilderException("abatement must not be null"); + } + policy.getControlLoop().setAbatement(abatement); + return this; + } + + @Override + public ControlLoopPolicyBuilder setTimeout(Integer timeout) { + policy.getControlLoop().setTimeout(timeout); + return this; + } + + @Override + public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, + Map<String, String> payload, Integer retries, Integer timeout) throws BuilderException { + + Policy trigger = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); + + policy.getControlLoop().setTrigger_policy(trigger.getId()); + + this.addNewPolicy(trigger); + // + // Return a copy of the policy + // + return new Policy(trigger); + } - @Override - public Policy setPolicyForPolicyResult(String name, String description, String actor, - Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException { - // - // Find the existing policy - // - Policy existingPolicy = this.findPolicy(policyID); - if (existingPolicy == null) { - throw new BuilderException("Unknown policy " + policyID); - } - // - // Create the new Policy - // - Policy newPolicy = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); - // - // Connect the results - // - for (PolicyResult result : results) { - switch (result) { - case FAILURE: - existingPolicy.failure = newPolicy.id; - break; - case FAILURE_EXCEPTION: - existingPolicy.failure_exception = newPolicy.id; - break; - case FAILURE_RETRIES: - existingPolicy.failure_retries = newPolicy.id; - break; - case FAILURE_TIMEOUT: - existingPolicy.failure_timeout = newPolicy.id; - break; - case FAILURE_GUARD: - existingPolicy.failure_guard = newPolicy.id; - break; - case SUCCESS: - existingPolicy.success = newPolicy.id; - break; - default: - throw new BuilderException("Invalid PolicyResult " + result); - } - } - // - // Add it to our list - // - this.policy.policies.add(newPolicy); - // - // Return a policy to them - // - return new Policy(newPolicy); - } - - private class BuilderCompilerCallback implements ControlLoopCompilerCallback { + @Override + public Policy setPolicyForPolicyResult(String name, String description, String actor, + Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException { + // + // Find the existing policy + // + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // Create the new Policy + // + Policy newPolicy = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); + // + // Connect the results + // + for (PolicyResult result : results) { + switch (result) { + case FAILURE: + existingPolicy.setFailure(newPolicy.getId()); + break; + case FAILURE_EXCEPTION: + existingPolicy.setFailure_exception(newPolicy.getId()); + break; + case FAILURE_RETRIES: + existingPolicy.setFailure_retries(newPolicy.getId()); + break; + case FAILURE_TIMEOUT: + existingPolicy.setFailure_timeout(newPolicy.getId()); + break; + case FAILURE_GUARD: + existingPolicy.setFailure_guard(newPolicy.getId()); + break; + case SUCCESS: + existingPolicy.setSuccess(newPolicy.getId()); + break; + default: + throw new BuilderException("Invalid PolicyResult " + result); + } + } + // + // Add it to our list + // + this.policy.getPolicies().add(newPolicy); + // + // Return a policy to them + // + return new Policy(newPolicy); + } + + private class BuilderCompilerCallback implements ControlLoopCompilerCallback { - public ResultsImpl results = new ResultsImpl(); - - @Override - public boolean onWarning(String message) { - results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); - return false; - } + private ResultsImpl results = new ResultsImpl(); + + @Override + public boolean onWarning(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); + return false; + } - @Override - public boolean onError(String message) { - results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); - return false; - } - } + @Override + public boolean onError(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); + return false; + } + } - @Override - public Results buildSpecification() { - // - // Dump the specification - // - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - options.setPrettyFlow(true); - Yaml yaml = new Yaml(options); - String dumpedYaml = yaml.dump(policy); - // - // This is our callback class for our compiler - // - BuilderCompilerCallback callback = new BuilderCompilerCallback(); - // - // Compile it - // - try { - ControlLoopCompiler.compile(policy, callback); - } catch (CompilerException e) { - callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); - } - // - // Save the spec - // - callback.results.setSpecification(dumpedYaml); - return callback.results; - } + @Override + public Results buildSpecification() { + // + // Dump the specification + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + Yaml yaml = new Yaml(options); + String dumpedYaml = yaml.dump(policy); + // + // This is our callback class for our compiler + // + BuilderCompilerCallback callback = new BuilderCompilerCallback(); + // + // Compile it + // + try { + ControlLoopCompiler.compile(policy, callback); + } catch (CompilerException e) { + logger.error(e.getMessage() + e); + callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); + } + // + // Save the spec + // + callback.results.setSpecification(dumpedYaml); + return callback.results; + } - private void addNewPolicy(Policy policy) { - if (this.policy.policies == null) { - this.policy.policies = new LinkedList<Policy>(); - } - this.policy.policies.add(policy); - } - - private Policy findPolicy(String id) { - for (Policy policy : this.policy.policies) { - if (policy.id.equals(id)) { - return policy; - } - } - return null; - } + private void addNewPolicy(Policy policy) { + if (this.policy.getPolicies() == null) { + this.policy.setPolicies(new LinkedList<>()); + } + this.policy.getPolicies().add(policy); + } + + private Policy findPolicy(String id) { + for (Policy policy : this.policy.getPolicies()) { + if (policy.getId().equals(id)) { + return policy; + } + } + return null; + } - @Override - public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException { - if (resources == null) { + @Override + public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException { + if (resources == null) { throw new BuilderException("Resource must not be null"); } - if (policy.controlLoop.resources == null) { + if (policy.getControlLoop().getResources() == null) { throw new BuilderException("No existing resources to remove"); } for (Resource resource : resources) { - if (resource.resourceUUID == null) { - if (resource.resourceName == null || resource.resourceName.length() < 1) { + if (resource.getResourceUUID() == null) { + if (resource.getResourceName() == null || resource.getResourceName().length() < 1) { throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName"); } } - boolean removed = policy.controlLoop.resources.remove(resource); + boolean removed = policy.getControlLoop().getResources().remove(resource); if (!removed) { - throw new BuilderException("Unknown resource " + resource.resourceName); + throw new BuilderException("Unknown resource " + resource.getResourceName()); } } return this; } - @Override - public ControlLoopPolicyBuilder removeAllResources() throws BuilderException { - policy.controlLoop.resources.clear(); + @Override + public ControlLoopPolicyBuilder removeAllResources() throws BuilderException { + policy.getControlLoop().getResources().clear(); return this; } - @Override - public ControlLoopPolicyBuilder removePNF() throws BuilderException { - policy.controlLoop.pnf = null; - return this; - } - - @Override - public Integer calculateTimeout() { - int sum = 0; - for (Policy policy : this.policy.policies) { - sum += policy.timeout.intValue(); + @Override + public Integer calculateTimeout() { + int sum = 0; + for (Policy policy : this.policy.getPolicies()) { + sum += policy.getTimeout().intValue(); } return new Integer(sum); - } + } - @Override - public ControlLoop setTriggerPolicy(String id) throws BuilderException { - if (id == null) { + @Override + public ControlLoop setTriggerPolicy(String id) throws BuilderException { + if (id == null) { throw new BuilderException("Id must not be null"); } - Policy trigger = this.findPolicy(id); + Policy trigger = this.findPolicy(id); if (trigger == null) { throw new BuilderException("Unknown policy " + id); } else { - this.policy.controlLoop.trigger_policy = id; + this.policy.getControlLoop().setTrigger_policy(id); } - return new ControlLoop(this.policy.controlLoop); + return new ControlLoop(this.policy.getControlLoop()); } - @Override - public boolean isOpenLoop() { - if (this.policy.controlLoop.trigger_policy.equals(FinalResult.FINAL_OPENLOOP.toString())) { + @Override + public boolean isOpenLoop() { + if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) { return true; - } + } else { return false; } - } + } - @Override - public Policy getTriggerPolicy() throws BuilderException { - if (this.policy.controlLoop.trigger_policy.equals(FinalResult.FINAL_OPENLOOP.toString())) { + @Override + public Policy getTriggerPolicy() throws BuilderException { + if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) { return null; } else { - Policy trigger = new Policy(this.findPolicy(this.policy.controlLoop.trigger_policy)); + Policy trigger = new Policy(this.findPolicy(this.policy.getControlLoop().getTrigger_policy())); return trigger; } } - @Override - public ControlLoop getControlLoop() { - ControlLoop loop = new ControlLoop(this.policy.controlLoop); - return loop; - } + @Override + public ControlLoop getControlLoop() { + ControlLoop loop = new ControlLoop(this.policy.getControlLoop()); + return loop; + } - @Override - public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) - throws BuilderException { - // + @Override + public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) + throws BuilderException { + // // Find the existing policy // Policy existingPolicy = this.findPolicy(policyID); @@ -402,78 +405,78 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { for (PolicyResult result : results) { switch (result) { case FAILURE: - existingPolicy.failure = policyResultID; + existingPolicy.setFailure(policyResultID); break; case FAILURE_EXCEPTION: - existingPolicy.failure_exception = policyResultID; + existingPolicy.setFailure_exception(policyResultID); break; case FAILURE_RETRIES: - existingPolicy.failure_retries = policyResultID; - break; + existingPolicy.setFailure_retries(policyResultID); + break; case FAILURE_TIMEOUT: - existingPolicy.failure_timeout = policyResultID; - break; + existingPolicy.setFailure_timeout(policyResultID); + break; case FAILURE_GUARD: - existingPolicy.failure_guard = policyResultID; - break; + existingPolicy.setFailure_guard(policyResultID); + break; case SUCCESS: - existingPolicy.success = policyResultID; - break; + existingPolicy.setSuccess(policyResultID); + break; default: - throw new BuilderException("Invalid PolicyResult " + result); + throw new BuilderException("Invalid PolicyResult " + result); } } return new Policy(this.findPolicy(policyResultID)); - } + } - @Override - public boolean removePolicy(String policyID) throws BuilderException { - Policy existingPolicy = this.findPolicy(policyID); + @Override + public boolean removePolicy(String policyID) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); if (existingPolicy == null) { throw new BuilderException("Unknown policy " + policyID); } // // Check if the policy to remove is trigger_policy // - if (this.policy.controlLoop.trigger_policy.equals(policyID)) { - this.policy.controlLoop.trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + if (this.policy.getControlLoop().getTrigger_policy().equals(policyID)) { + this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); } else { // // Update policies // - for (Policy policy : this.policy.policies) { - int index = this.policy.policies.indexOf(policy); - if (policy.success.equals(policyID)) { - policy.success = FinalResult.FINAL_SUCCESS.toString(); + for (Policy policy : this.policy.getPolicies()) { + int index = this.policy.getPolicies().indexOf(policy); + if (policy.getSuccess().equals(policyID)) { + policy.setSuccess(FinalResult.FINAL_SUCCESS.toString()); } - if (policy.failure.equals(policyID)) { - policy.failure = FinalResult.FINAL_FAILURE.toString(); + if (policy.getFailure().equals(policyID)) { + policy.setFailure(FinalResult.FINAL_FAILURE.toString()); } - if (policy.failure_retries.equals(policyID)) { - policy.failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + if (policy.getFailure_retries().equals(policyID)) { + policy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString()); } - if (policy.failure_timeout.equals(policyID)) { - policy.failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + if (policy.getFailure_timeout().equals(policyID)) { + policy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString()); } - if (policy.failure_exception.equals(policyID)) { - policy.failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + if (policy.getFailure_exception().equals(policyID)) { + policy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString()); } - if (policy.failure_guard.equals(policyID)) { - policy.failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + if (policy.getFailure_guard().equals(policyID)) { + policy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString()); } - this.policy.policies.set(index, policy); + this.policy.getPolicies().set(index, policy); } } // // remove the policy // - boolean removed = this.policy.policies.remove(existingPolicy); + boolean removed = this.policy.getPolicies().remove(existingPolicy); return removed; - } + } - @Override - public Policy resetPolicyResults(String policyID) throws BuilderException { + @Override + public Policy resetPolicyResults(String policyID) throws BuilderException { Policy existingPolicy = this.findPolicy(policyID); if (existingPolicy == null) { throw new BuilderException("Unknown policy " + policyID); @@ -481,39 +484,39 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { // // reset policy results // - existingPolicy.success = FinalResult.FINAL_SUCCESS.toString(); - existingPolicy.failure = FinalResult.FINAL_FAILURE.toString(); - existingPolicy.failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); - existingPolicy.failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); - existingPolicy.failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); - existingPolicy.failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + existingPolicy.setSuccess(FinalResult.FINAL_SUCCESS.toString()); + existingPolicy.setFailure(FinalResult.FINAL_FAILURE.toString()); + existingPolicy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString()); + existingPolicy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString()); + existingPolicy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString()); + existingPolicy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString()); return new Policy(existingPolicy); - } + } - @Override - public ControlLoopPolicyBuilder removeAllPolicies() { - // + @Override + public ControlLoopPolicyBuilder removeAllPolicies() { + // // Remove all existing operational policies // - this.policy.policies.clear(); + this.policy.getPolicies().clear(); // // Revert controlLoop back to an open loop // - this.policy.controlLoop.trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); return this; - } - - @Override - public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException { - Policy existingPolicy = this.findPolicy(policyID); + } + + @Override + public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); if (existingPolicy == null) { throw new BuilderException("Unknown policy " + policyID); } // // Add operationsAccumulateParams to existingPolicy // - existingPolicy.operationsAccumulateParams = operationsAccumulateParams; + existingPolicy.setOperationsAccumulateParams(operationsAccumulateParams); return new Policy(existingPolicy); - } + } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java index e13318089..a9c632290 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java @@ -1,144 +1,172 @@ -/*- - * ============LICENSE_START======================================================= - * policy-yaml - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -public class Constraint { - - public Integer freq_limit_per_target; - public Map<String, String> time_window; - public Map<String, String> active_time_range; - - public LinkedList<String> blacklist; - - public Constraint() { - - } - - public Constraint(Integer freq_limit_per_target, Map<String, String> time_window) { - this.freq_limit_per_target = freq_limit_per_target; - if (time_window != null) { - this.time_window = Collections.unmodifiableMap(time_window); - } - } - - public Constraint(List<String> blacklist) { - this.blacklist = new LinkedList<String>(blacklist); - - } - - public Constraint(Integer freq_limit_per_target, Map<String, String> time_window, List<String> blacklist) { - this.freq_limit_per_target = freq_limit_per_target; - this.time_window = Collections.unmodifiableMap(time_window); - this.blacklist = new LinkedList<String>(blacklist); - } - - public Constraint(Integer freq_limit_per_target, Map<String, String> time_window, Map<String, String> active_time_range, List<String> blacklist) { - this(freq_limit_per_target, time_window); - if (active_time_range != null) { - this.active_time_range = Collections.unmodifiableMap(active_time_range); - } - this.blacklist = new LinkedList<String>(blacklist); - } - - public Constraint(Integer freq_limit_per_target, Map<String, String> time_window, Map<String, String> active_time_range) { - this(freq_limit_per_target, time_window); - if (active_time_range != null) { - this.active_time_range = Collections.unmodifiableMap(active_time_range); - } - } - - public Constraint(Constraint constraint) { - this.freq_limit_per_target = constraint.freq_limit_per_target; - this.time_window = constraint.time_window; - if (constraint.active_time_range != null) { - this.active_time_range = Collections.unmodifiableMap(constraint.active_time_range); - } - this.blacklist = new LinkedList<String>(constraint.blacklist); - } - - public boolean isValid() { - //System.out.println("freq_limit_per_target: " + freq_limit_per_target + " time_window" + time_window ); - try { - if (freq_limit_per_target == null && time_window != null) { - throw new NullPointerException(); - } - if (time_window == null && freq_limit_per_target != null) { - throw new NullPointerException(); - } - } catch (Exception e) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Constraint [freq_limit_per_target=" + freq_limit_per_target + ", time_window=" + time_window + ", active_time_range=" + active_time_range + ", blacklist=" + blacklist + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((freq_limit_per_target == null) ? 0 : freq_limit_per_target.hashCode()); - result = prime * result + ((time_window == null) ? 0 : time_window.hashCode()); - result = prime * result + ((active_time_range == null) ? 0 : active_time_range.hashCode()); - result = prime * result + ((blacklist == null) ? 0 : blacklist.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Constraint other = (Constraint) obj; - if (freq_limit_per_target == null) { - if (other.freq_limit_per_target != null) - return false; - } else if (!freq_limit_per_target.equals(other.freq_limit_per_target)) - return false; - if (time_window == null) { - if (other.time_window != null) - return false; - } else if (!time_window.equals(other.time_window)) - return false; - if (active_time_range == null) { - if (other.active_time_range != null) - return false; - } else if (!active_time_range.equals(other.active_time_range)) - return false; - if (blacklist == null) { - if (other.blacklist != null) - return false; - } else if (!blacklist.equals(other.blacklist)) - return false; - return true; - } -} +/*-
+ * ============LICENSE_START=======================================================
+ * policy-yaml
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard;
+
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+public class Constraint {
+
+ private Integer freq_limit_per_target;
+ private Map<String,String> time_window;
+ private Map<String, String> active_time_range;
+
+ private List<String> blacklist;
+
+ public Constraint() {
+ // Do Nothing empty constructor.
+ }
+
+ public Integer getFreq_limit_per_target() {
+ return freq_limit_per_target;
+ }
+
+
+ public void setFreq_limit_per_target(Integer freq_limit_per_target) {
+ this.freq_limit_per_target = freq_limit_per_target;
+ }
+
+
+ public Map<String, String> getTime_window() {
+ return time_window;
+ }
+
+
+ public void setTime_window(Map<String, String> time_window) {
+ this.time_window = time_window;
+ }
+
+
+ public Map<String, String> getActive_time_range() {
+ return active_time_range;
+ }
+
+
+ public void setActive_time_range(Map<String, String> active_time_range) {
+ this.active_time_range = active_time_range;
+ }
+
+
+ public List<String> getBlacklist() {
+ return blacklist;
+ }
+
+ public void setBlacklist(List<String> blacklist) {
+ this.blacklist = blacklist;
+ }
+
+ public Constraint(Integer freq_limit_per_target, Map<String, String> time_window) {
+ this.freq_limit_per_target = freq_limit_per_target;
+ if(time_window!=null){
+ this.time_window = Collections.unmodifiableMap(time_window);
+ }
+ }
+
+ public Constraint(List<String> blacklist) {
+ this.blacklist = new LinkedList<>(blacklist);
+ }
+
+ public Constraint(Integer freq_limit_per_target, Map<String, String> time_window, List<String> blacklist) {
+ this.freq_limit_per_target = freq_limit_per_target;
+ this.time_window = Collections.unmodifiableMap(time_window);
+ this.blacklist = new LinkedList<>(blacklist);
+ }
+
+ public Constraint(Integer freq_limit_per_target, Map<String, String> time_window, Map<String, String> active_time_range) {
+ this(freq_limit_per_target, time_window);
+ if (active_time_range != null) {
+ this.active_time_range = Collections.unmodifiableMap(active_time_range);
+ }
+ }
+
+ public Constraint(Integer freq_limit_per_target, Map<String, String> time_window, Map<String, String> active_time_range, List<String> blacklist) {
+ this(freq_limit_per_target, time_window);
+ if (active_time_range != null) {
+ this.active_time_range = Collections.unmodifiableMap(active_time_range);
+ }
+ if(blacklist!=null){
+ this.blacklist = new LinkedList<>(blacklist);
+ }
+ }
+
+ public Constraint(Constraint constraint) {
+ this.freq_limit_per_target = constraint.freq_limit_per_target;
+ this.time_window = constraint.time_window;
+ if (constraint.active_time_range != null) {
+ this.active_time_range = Collections.unmodifiableMap(constraint.active_time_range);
+ }
+ this.blacklist = new LinkedList<>(constraint.blacklist);
+ }
+
+ public boolean isValid() {
+ return ((freq_limit_per_target == null && time_window != null)|| (time_window == null && freq_limit_per_target != null))? false : true;
+ }
+
+ @Override
+ public String toString() {
+ return "Constraint [freq_limit_per_target=" + freq_limit_per_target + ", time_window=" + time_window + ", active_time_range=" + active_time_range + ", blacklist=" + blacklist + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((freq_limit_per_target == null) ? 0 : freq_limit_per_target.hashCode());
+ result = prime * result + ((time_window == null) ? 0 : time_window.hashCode());
+ result = prime * result + ((active_time_range == null) ? 0 : active_time_range.hashCode());
+ result = prime * result + ((blacklist == null) ? 0 : blacklist.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Constraint other = (Constraint) obj;
+ if (freq_limit_per_target == null) {
+ if (other.freq_limit_per_target != null)
+ return false;
+ } else if (!freq_limit_per_target.equals(other.freq_limit_per_target))
+ return false;
+ if (time_window == null) {
+ if (other.time_window != null)
+ return false;
+ } else if (!time_window.equals(other.time_window))
+ return false;
+ if (active_time_range == null) {
+ if (other.active_time_range != null)
+ return false;
+ } else if (!active_time_range.equals(other.active_time_range))
+ return false;
+ if (blacklist == null) {
+ if (other.blacklist != null)
+ return false;
+ } else if (!blacklist.equals(other.blacklist))
+ return false;
+ return true;
+ }
+}
diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java index 34dc20191..7c90801ec 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java @@ -1,77 +1,93 @@ -/*- - * ============LICENSE_START======================================================= - * policy-yaml - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard; - -import java.util.LinkedList; - -public class ControlLoopGuard { - - public Guard guard; - - public LinkedList<GuardPolicy> guards; - - public ControlLoopGuard() { - - } - - public ControlLoopGuard(ControlLoopGuard CLGuard) { - this.guard = new Guard(); - this.guards = new LinkedList<GuardPolicy>(CLGuard.guards); - } - - @Override - public String toString() { - return "Guard [guard=" + guard + ", GuardPolicies=" + guards + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((guard == null) ? 0 : guard.hashCode()); - result = prime * result + ((guards == null) ? 0 : guards.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ControlLoopGuard other = (ControlLoopGuard) obj; - if (guard == null) { - if (other.guard != null) - return false; - } else if (!guard.equals(other.guard)) - return false; - if (guards == null) { - if (other.guards != null) - return false; - } else if (!guards.equals(other.guards)) - return false; - return true; - } - - -} +/*-
+ * ============LICENSE_START=======================================================
+ * policy-yaml
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard;
+
+import java.util.LinkedList;
+
+public class ControlLoopGuard {
+
+ private Guard guard;
+
+ private LinkedList<GuardPolicy> guards;
+
+ public ControlLoopGuard() {
+ //DO Nothing Empty Constructor
+ }
+
+ public Guard getGuard() {
+ return guard;
+ }
+
+ public void setGuard(Guard guard) {
+ this.guard = guard;
+ }
+
+ public LinkedList<GuardPolicy> getGuards() {
+ return guards;
+ }
+
+ public void setGuards(LinkedList<GuardPolicy> guards) {
+ this.guards = guards;
+ }
+
+ public ControlLoopGuard(ControlLoopGuard cLGuard) {
+ this.guard = new Guard();
+ this.guards = new LinkedList<>(cLGuard.guards);
+ }
+
+ @Override
+ public String toString() {
+ return "Guard [guard=" + guard + ", GuardPolicies=" + guards + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((guard == null) ? 0 : guard.hashCode());
+ result = prime * result + ((guards == null) ? 0 : guards.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ ControlLoopGuard other = (ControlLoopGuard) obj;
+ if (guard == null) {
+ if (other.guard != null)
+ return false;
+ } else if (!guard.equals(other.guard))
+ return false;
+ if (guards == null) {
+ if (other.guards != null)
+ return false;
+ } else if (!guards.equals(other.guards))
+ return false;
+ return true;
+ }
+
+
+}
diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java index 3c09b3201..dedc9a076 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java @@ -1,60 +1,68 @@ -/*- - * ============LICENSE_START======================================================= - * policy-yaml - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard; - -public class Guard { - - public static String VERSION = "2.0.0"; - - public final String version = VERSION; - - public Guard() { - - } - - @Override - public String toString() { - return "Guard [version=" + version + "]"; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Guard other = (Guard) obj; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } -} +/*-
+ * ============LICENSE_START=======================================================
+ * policy-yaml
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard;
+
+public class Guard {
+
+ private static final String DEFAULTVERSION = "2.0.0";
+
+ private String version = DEFAULTVERSION;
+
+ public Guard() {
+ //DO Nothing empty Constructor.
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ @Override
+ public String toString() {
+ return "Guard [version=" + version + "]";
+ }
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((version == null) ? 0 : version.hashCode());
+ return result;
+ }
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Guard other = (Guard) obj;
+ if (version == null) {
+ if (other.version != null)
+ return false;
+ } else if (!version.equals(other.version))
+ return false;
+ return true;
+ }
+}
diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java index f0267b3ad..97d3d6faf 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java @@ -1,160 +1,182 @@ -/*- - * ============LICENSE_START======================================================= - * policy-yaml - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.UUID; - -public class GuardPolicy { - - public String id = UUID.randomUUID().toString(); - public String name; - public String description; - public MatchParameters match_parameters; - public LinkedList<Constraint> limit_constraints; - - -public GuardPolicy() { - - } - - public GuardPolicy(String id) { - this.id = id; - } - - public GuardPolicy(String name, MatchParameters match_parameters) { - this.name = name; - System.out.println("match_parameters: " + match_parameters); - this.match_parameters = new MatchParameters(match_parameters); - } - - public GuardPolicy(String id, String name, String description, MatchParameters match_parameters) { - this(name, match_parameters); - this.id = id; - this.description = description; - } - - public GuardPolicy(String name, MatchParameters match_parameters, List<Constraint> limit_constraints) { - this(name, match_parameters); - if (limit_constraints != null) { - this.limit_constraints = (LinkedList<Constraint>) Collections.unmodifiableList(limit_constraints); - } - } - - public GuardPolicy(String name, String description, MatchParameters match_parameters, List<Constraint> limit_constraints) { - this(name, match_parameters, limit_constraints); - this.description = description; - } - - public GuardPolicy(String id, String name, String description, MatchParameters match_parameters, List<Constraint> limit_constraints) { - this(name, description, match_parameters, limit_constraints); - this.id = id; - } - - - - - - - public GuardPolicy(GuardPolicy policy) { - this.id = policy.id; - this.name = policy.name; - this.description = policy.description; - this.match_parameters = new MatchParameters(policy.match_parameters); - if (policy.limit_constraints != null) { - this.limit_constraints = (LinkedList<Constraint>) Collections.unmodifiableList(policy.limit_constraints); - } - } - - public boolean isValid() { - try { - if (id == null) { - throw new NullPointerException(); - } - if (name == null) { - throw new NullPointerException(); - } - - } catch (Exception e) { - return false; - } - return true; - } - - @Override - public String toString() { - return "GuardPolicy [id=" + id + ", name=" + name + ", description=" + description + ", match_parameters=" - + match_parameters + ", limit_constraints=" + limit_constraints + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((limit_constraints == null) ? 0 : limit_constraints.hashCode()); - result = prime * result + ((match_parameters == null) ? 0 : match_parameters.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - GuardPolicy other = (GuardPolicy) obj; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (limit_constraints == null) { - if (other.limit_constraints != null) - return false; - } else if (!limit_constraints.equals(other.limit_constraints)) - return false; - if (match_parameters == null) { - if (other.match_parameters != null) - return false; - } else if (!match_parameters.equals(other.match_parameters)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - -} +/*-
+ * ============LICENSE_START=======================================================
+ * policy-yaml
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard;
+
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.UUID;
+
+public class GuardPolicy {
+
+ private String id = UUID.randomUUID().toString();
+ private String name;
+ private String description;
+ private MatchParameters match_parameters;
+ private LinkedList<Constraint> limit_constraints;
+
+ public GuardPolicy() {
+ //Do Nothing Empty Constructor.
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public MatchParameters getMatch_parameters() {
+ return match_parameters;
+ }
+
+ public void setMatch_parameters(MatchParameters match_parameters) {
+ this.match_parameters = match_parameters;
+ }
+
+ public LinkedList<Constraint> getLimit_constraints() {
+ return limit_constraints;
+ }
+
+ public void setLimit_constraints(LinkedList<Constraint> limit_constraints) {
+ this.limit_constraints = limit_constraints;
+ }
+
+ public GuardPolicy(String id) {
+ this.id = id;
+ }
+
+ public GuardPolicy(String name, MatchParameters matchParameters) {
+ this.name = name;
+ this.match_parameters = matchParameters;
+ }
+
+ public GuardPolicy(String id, String name, String description, MatchParameters matchParameters) {
+ this(name, matchParameters);
+ this.id = id;
+ this.description = description;
+ }
+
+ public GuardPolicy(String name, MatchParameters matchParameters, List<Constraint> limitConstraints) {
+ this(name, matchParameters);
+ if (limit_constraints != null) {
+ this.limit_constraints = (LinkedList<Constraint>) Collections.unmodifiableList(limitConstraints);
+ }
+ }
+
+ public GuardPolicy(String name, String description, MatchParameters matchParameters, List<Constraint> limitConstraints) {
+ this(name, matchParameters, limitConstraints);
+ this.description = description;
+ }
+
+ public GuardPolicy(String id, String name, String description, MatchParameters matchParameters, List<Constraint> limitConstraints) {
+ this(name, description, matchParameters, limitConstraints);
+ this.id = id;
+ }
+
+ public GuardPolicy(GuardPolicy policy) {
+ this.id = policy.id;
+ this.name = policy.name;
+ this.description = policy.description;
+ this.match_parameters = new MatchParameters(policy.match_parameters);
+ if (policy.limit_constraints != null) {
+ this.limit_constraints = (LinkedList<Constraint>) Collections.unmodifiableList(policy.limit_constraints);
+ }
+ }
+
+ public boolean isValid() {
+ return (id==null || name ==null)? false : true;
+ }
+
+ @Override
+ public String toString() {
+ return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", match_parameters="
+ +match_parameters + ", limitConstraints=" + limit_constraints + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((description == null) ? 0 : description.hashCode());
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((limit_constraints == null) ? 0 : limit_constraints.hashCode());
+ result = prime * result + ((match_parameters == null) ? 0 : match_parameters.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ GuardPolicy other = (GuardPolicy) obj;
+ if (description == null) {
+ if (other.description != null)
+ return false;
+ } else if (!description.equals(other.description))
+ return false;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ if (limit_constraints == null) {
+ if (other.limit_constraints != null)
+ return false;
+ } else if (!limit_constraints.equals(other.limit_constraints))
+ return false;
+ if (match_parameters==null){
+ if(other.match_parameters !=null)
+ return false;
+ } else if(!match_parameters.equals(other.match_parameters))
+ return false;
+ return true;
+ }
+
+
+}
diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java index c96ecf710..fbfad741f 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java @@ -1,138 +1,144 @@ -/*- - * ============LICENSE_START======================================================= - * policy-yaml - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard; - -import java.util.LinkedList; - - -public class MatchParameters { - - //public ControlLoopParameter controlLoop; - public String controlLoopName; - public String actor; - public String recipe; - public LinkedList<String> targets; - - - public MatchParameters() { - - } - - public MatchParameters(String actor, String recipe) { - this.actor = actor; - this.recipe = recipe; - } - - public MatchParameters(String actor, String recipe, LinkedList<String> targets) { - this(actor, recipe); - if (targets != null) { - this.targets = new LinkedList<String>(targets); - } - } - - - public MatchParameters(String controlLoopName, String actor, String recipe, LinkedList<String> targets) { - this(actor, recipe, targets); - this.controlLoopName = controlLoopName; - } - - - - - - public MatchParameters(MatchParameters matchParameters) { - - this.controlLoopName = matchParameters.controlLoopName; - this.actor = matchParameters.actor; - this.recipe = matchParameters.recipe; - if (matchParameters.targets != null) { - //this.targets = (LinkedList<String>) Collections.unmodifiableList(matchParameters.targets); - this.targets = new LinkedList<String>(matchParameters.targets); - } - } - - /* - public boolean isValid() { - try { - if (actor == null) { - throw new NullPointerException(); - } - if (recipe == null) { - throw new NullPointerException(); - } - } catch (Exception e) { - return false; - } - return true; - } - */ - - @Override - public String toString() { - return "MatchParameters [controlLoopName=" + controlLoopName + ", actor=" + actor + ", recipe=" + recipe - + ", targets=" + targets + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((actor == null) ? 0 : actor.hashCode()); - result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); - result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); - result = prime * result + ((targets == null) ? 0 : targets.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - MatchParameters other = (MatchParameters) obj; - if (actor == null) { - if (other.actor != null) - return false; - } else if (!actor.equals(other.actor)) - return false; - if (controlLoopName == null) { - if (other.controlLoopName != null) - return false; - } else if (!controlLoopName.equals(other.controlLoopName)) - return false; - if (recipe == null) { - if (other.recipe != null) - return false; - } else if (!recipe.equals(other.recipe)) - return false; - if (targets == null) { - if (other.targets != null) - return false; - } else if (!targets.equals(other.targets)) - return false; - return true; - } - - -} +/*-
+ * ============LICENSE_START=======================================================
+ * policy-yaml
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard;
+
+import java.util.LinkedList;
+import java.util.List;
+
+
+public class MatchParameters {
+ private String controlLoopName;
+ private String actor;
+ private String recipe;
+ private List<String> targets;
+
+ public MatchParameters() {
+ // Do Nothing Empty Constructor.
+ }
+
+ public String getControlLoopName() {
+ return controlLoopName;
+ }
+
+ public void setControlLoopName(String controlLoopName) {
+ this.controlLoopName = controlLoopName;
+ }
+
+ public String getActor() {
+ return actor;
+ }
+
+ public void setActor(String actor) {
+ this.actor = actor;
+ }
+
+ public String getRecipe() {
+ return recipe;
+ }
+
+ public void setRecipe(String recipe) {
+ this.recipe = recipe;
+ }
+
+ public List<String> getTargets() {
+ return targets;
+ }
+
+ public void setTargets(List<String> targets) {
+ this.targets = targets;
+ }
+
+ public MatchParameters(String actor, String recipe) {
+ this.actor = actor;
+ this.recipe = recipe;
+ }
+
+ public MatchParameters(String actor, String recipe, List<String> targets) {
+ this(actor, recipe);
+ if (targets != null) {
+ this.targets = new LinkedList<>(targets);
+ }
+ }
+
+ public MatchParameters(String controlLoopName, String actor, String recipe, List<String> targets) {
+ this(actor, recipe, targets);
+ this.controlLoopName = controlLoopName;
+ }
+
+ public MatchParameters(MatchParameters matchParameters) {
+
+ this.controlLoopName = matchParameters.controlLoopName;
+ this.actor = matchParameters.actor;
+ this.recipe = matchParameters.recipe;
+ if (matchParameters.targets != null) {
+ this.targets = new LinkedList<>(matchParameters.targets);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "MatchParameters [controlLoopName=" + controlLoopName + ", actor=" + actor + ", recipe=" + recipe
+ + ", targets=" + targets + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((actor == null) ? 0 : actor.hashCode());
+ result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode());
+ result = prime * result + ((recipe == null) ? 0 : recipe.hashCode());
+ result = prime * result + ((targets == null) ? 0 : targets.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ MatchParameters other = (MatchParameters) obj;
+ if (actor == null) {
+ if (other.actor != null)
+ return false;
+ } else if (!actor.equals(other.actor))
+ return false;
+ if (controlLoopName == null) {
+ if (other.controlLoopName != null)
+ return false;
+ } else if (!controlLoopName.equals(other.controlLoopName))
+ return false;
+ if (recipe == null) {
+ if (other.recipe != null)
+ return false;
+ } else if (!recipe.equals(other.recipe))
+ return false;
+ if (targets == null) {
+ if (other.targets != null)
+ return false;
+ } else if (!targets.equals(other.targets))
+ return false;
+ return true;
+ }
+}
diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java new file mode 100644 index 000000000..8691a0fb7 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard.builder; + +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.Results; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.Guard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.onap.policy.controlloop.policy.guard.builder.impl.ControlLoopGuardBuilderImpl; + +public interface ControlLoopGuardBuilder { + + /** + * Adds one or more guard policies to the Control Loop Guard + * + * + * @param policies + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException; + + /** + * Removes one or more guard policies from the Control Loop Guard + * + * + * @param policies + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException; + + /** + * Removes all guard policies from the Control Loop Guard + * + * + * @param + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException; + + /** + * Adds one or more time limit constraints to the guard policy + * + * + * @param id (guard policy id) + * @param constraints + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException; + + /** + * Removes one or more time limit constraints from the guard policy + * + * + * @param id (guard policy id) + * @param constraints + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException; + + /** + * Removes all time limit constraints from the guard policy + * + * + * @param id (guard policy id) + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException; + + /** + * Simply return a copy of control loop guard + * + * @return ControlLoopGuard + */ + public ControlLoopGuard getControlLoopGuard(); + + /** + * This will compile and build the YAML specification for the Control Loop Guard. Please iterate the Results object for details. + * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the + * YAML. + * + * @return Results + */ + public Results buildSpecification(); + + /** + * The Factory is used to build a ControlLoopGuardBuilder implementation. + * + */ + public static class Factory { + + private Factory(){ + //Do Nothing Private Constructor. + } + /** + * @param guard + * @return ControlLoopGuardBuilder object + * @throws BuilderException + */ + public static ControlLoopGuardBuilder buildControlLoopGuard (Guard guard) throws BuilderException { + + return new ControlLoopGuardBuilderImpl(guard); + + } + } +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java index 0086342e7..4c25a7ef9 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java @@ -1,236 +1,245 @@ -/*- - * ============LICENSE_START======================================================= - * policy-yaml - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard.builder.impl; - -import java.util.LinkedList; - -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.DumperOptions.FlowStyle; - -import org.onap.policy.controlloop.compiler.CompilerException; -import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback; -import org.onap.policy.controlloop.guard.compiler.ControlLoopGuardCompiler; -import org.onap.policy.controlloop.policy.builder.BuilderException; -import org.onap.policy.controlloop.policy.builder.MessageLevel; -import org.onap.policy.controlloop.policy.builder.Results; -import org.onap.policy.controlloop.policy.builder.impl.MessageImpl; -import org.onap.policy.controlloop.policy.builder.impl.ResultsImpl; -import org.onap.policy.controlloop.policy.guard.Constraint; -import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; -import org.onap.policy.controlloop.policy.guard.Guard; -import org.onap.policy.controlloop.policy.guard.GuardPolicy; -import org.onap.policy.controlloop.poligy.guard.builder.ControlLoopGuardBuilder; - -public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { - - private ControlLoopGuard CLGuard; - - public ControlLoopGuardBuilderImpl(Guard guard) { - CLGuard = new ControlLoopGuard(); - CLGuard.guard = guard; - } - - @Override - public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException { - if (policies == null) { - throw new BuilderException("GuardPolicy must not be null"); - } - for (GuardPolicy policy : policies) { - if (!policy.isValid()) { - throw new BuilderException("Invalid guard policy - some required fields are missing"); - } - if (CLGuard.guards == null) { - CLGuard.guards = new LinkedList<GuardPolicy>(); - } - CLGuard.guards.add(policy); - } - return this; - } - - @Override - public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException { - if (policies == null) { - throw new BuilderException("GuardPolicy must not be null"); - } - if (CLGuard.guards == null) { - throw new BuilderException("No existing guard policies to remove"); - } - for (GuardPolicy policy : policies) { - if (!policy.isValid()) { - throw new BuilderException("Invalid guard policy - some required fields are missing"); - } - boolean removed = CLGuard.guards.remove(policy); - if (!removed) { - throw new BuilderException("Unknown guard policy: " + policy.name); - } - } - return this; - } - - @Override - public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException { - CLGuard.guards.clear(); - return this; - } - - @Override - public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException { - if (id == null) { - throw new BuilderException("The id of target guard policy must not be null"); - } - if (constraints == null) { - throw new BuilderException("Constraint much not be null"); - } - boolean exist = false; - for (GuardPolicy policy: CLGuard.guards) { - // - // We could have only one guard policy matching the id - // - if (policy.id.equals(id)) { - exist = true; - for (Constraint cons: constraints) { - if (!cons.isValid()) { - throw new BuilderException("Invalid guard constraint - some required fields are missing"); - } - if (policy.limit_constraints == null) { - policy.limit_constraints = new LinkedList<Constraint>(); - } - policy.limit_constraints.add(cons); - } - break; - } - } - if (exist == false) { - throw new BuilderException("No existing guard policy matching the id: " + id); - } - return this; - } - - @Override - public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException { - if (id == null) { - throw new BuilderException("The id of target guard policy must not be null"); - } - if (constraints == null) { - throw new BuilderException("Constraint much not be null"); - } - boolean exist = false; - for (GuardPolicy policy: CLGuard.guards) { - // - // We could have only one guard policy matching the id - // - if (policy.id.equals(id)) { - exist = true; - for (Constraint cons: constraints) { - if (!cons.isValid()) { - throw new BuilderException("Invalid guard constraint - some required fields are missing"); - } - boolean removed = policy.limit_constraints.remove(cons); - if (!removed) { - throw new BuilderException("Unknown guard constraint: " + cons); - } - } - break; - } - } - if (exist == false) { - throw new BuilderException("No existing guard policy matching the id: " + id); - } - return this; - } - - @Override - public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException { - if (CLGuard.guards == null || CLGuard.guards.isEmpty()) { - throw new BuilderException("No guard policies exist"); - } - if (id == null) { - throw new BuilderException("The id of target guard policy must not be null"); - } - boolean exist = false; - for (GuardPolicy policy: CLGuard.guards) { - if (policy.id.equals(id)) { - exist = true; - policy.limit_constraints.clear(); - } - } - if (exist == false) { - throw new BuilderException("No existing guard policy matching the id: " + id); - } - return this; - } - - - private class BuilderCompilerCallback implements ControlLoopCompilerCallback { - - public ResultsImpl results = new ResultsImpl(); - - @Override - public boolean onWarning(String message) { - results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); - return false; - } - - @Override - public boolean onError(String message) { - results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); - return false; - } - } - - @Override - public ControlLoopGuard getControlLoopGuard() { - ControlLoopGuard guard = new ControlLoopGuard(this.CLGuard); - return guard; - } - - - @Override - public Results buildSpecification() { - // - // Dump the specification - // - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - options.setPrettyFlow(true); - Yaml yaml = new Yaml(options); - String dumpedYaml = yaml.dump(CLGuard); - // - // This is our callback class for our compiler - // - BuilderCompilerCallback callback = new BuilderCompilerCallback(); - // - // Compile it - // - try { - ControlLoopGuardCompiler.compile(CLGuard, callback); - } catch (CompilerException e) { - callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); - } - // - // Save the spec - // - callback.results.setSpecification(dumpedYaml); - return callback.results; - } - -} +/*-
+ * ============LICENSE_START=======================================================
+ * policy-yaml
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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.policy.guard.builder.impl;
+
+import java.util.LinkedList;
+
+import org.onap.policy.controlloop.compiler.CompilerException;
+import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback;
+import org.onap.policy.controlloop.guard.compiler.ControlLoopGuardCompiler;
+import org.onap.policy.controlloop.policy.builder.BuilderException;
+import org.onap.policy.controlloop.policy.builder.MessageLevel;
+import org.onap.policy.controlloop.policy.builder.Results;
+import org.onap.policy.controlloop.policy.builder.impl.MessageImpl;
+import org.onap.policy.controlloop.policy.builder.impl.ResultsImpl;
+import org.onap.policy.controlloop.policy.guard.Constraint;
+import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
+import org.onap.policy.controlloop.policy.guard.Guard;
+import org.onap.policy.controlloop.policy.guard.GuardPolicy;
+import org.onap.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.yaml.snakeyaml.DumperOptions;
+import org.yaml.snakeyaml.DumperOptions.FlowStyle;
+import org.yaml.snakeyaml.Yaml;
+
+public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder {
+ private static Logger logger = LoggerFactory.getLogger(ControlLoopGuardBuilderImpl.class.getName());
+ private ControlLoopGuard cLGuard;
+
+ public ControlLoopGuardBuilderImpl(Guard guard) {
+ cLGuard = new ControlLoopGuard();
+ cLGuard.setGuard(guard);
+ }
+
+ @Override
+ public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException {
+ if (policies == null) {
+ throw new BuilderException("GuardPolicy must not be null");
+ }
+ for (GuardPolicy policy : policies) {
+ if (!policy.isValid()) {
+ throw new BuilderException("Invalid guard policy - some required fields are missing");
+ }
+ if (cLGuard.getGuards() == null) {
+ cLGuard.setGuards(new LinkedList<>());
+ }
+ cLGuard.getGuards().add(policy);
+ }
+ return this;
+ }
+
+ @Override
+ public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException {
+ if (policies == null) {
+ throw new BuilderException("GuardPolicy must not be null");
+ }
+ if (cLGuard.getGuards() == null) {
+ throw new BuilderException("No existing guard policies to remove");
+ }
+ for (GuardPolicy policy : policies) {
+ if (!policy.isValid()) {
+ throw new BuilderException("Invalid guard policy - some required fields are missing");
+ }
+ boolean removed = cLGuard.getGuards().remove(policy);
+ if (!removed) {
+ throw new BuilderException("Unknown guard policy: " + policy.getName());
+ }
+ }
+ return this;
+ }
+
+ @Override
+ public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException {
+ cLGuard.getGuards().clear();
+ return this;
+ }
+
+ @Override
+ public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException {
+ if (id == null) {
+ throw new BuilderException("The id of target guard policy must not be null");
+ }
+ if (constraints == null) {
+ throw new BuilderException("Constraint much not be null");
+ }
+ if (!addLimitConstraints(id,constraints)) {
+ throw new BuilderException("No existing guard policy matching the id: " + id);
+ }
+ return this;
+ }
+
+ private boolean addLimitConstraints(String id, Constraint... constraints) throws BuilderException {
+ boolean exist = false;
+ for (GuardPolicy policy: cLGuard.getGuards()) {
+ //
+ // We could have only one guard policy matching the id
+ //
+ if (policy.getId().equals(id)) {
+ exist = true;
+ for (Constraint cons: constraints) {
+ if (!cons.isValid()) {
+ throw new BuilderException("Invalid guard constraint - some required fields are missing");
+ }
+ if (policy.getLimit_constraints() == null) {
+ policy.setLimit_constraints(new LinkedList<>());
+ }
+ policy.getLimit_constraints().add(cons);
+ }
+ break;
+ }
+ }
+ return exist;
+ }
+
+ @Override
+ public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException {
+ if (id == null) {
+ throw new BuilderException("The id of target guard policy must not be null");
+ }
+ if (constraints == null) {
+ throw new BuilderException("Constraint much not be null");
+ }
+ if (!removeConstraints(id, constraints)) {
+ throw new BuilderException("No existing guard policy matching the id: " + id);
+ }
+ return this;
+ }
+
+ private boolean removeConstraints(String id, Constraint... constraints) throws BuilderException {
+ boolean exist = false;
+ for (GuardPolicy policy: cLGuard.getGuards()) {
+ //
+ // We could have only one guard policy matching the id
+ //
+ if (policy.getId().equals(id)) {
+ exist = true;
+ for (Constraint cons: constraints) {
+ if (!cons.isValid()) {
+ throw new BuilderException("Invalid guard constraint - some required fields are missing");
+ }
+ boolean removed = policy.getLimit_constraints().remove(cons);
+ if (!removed) {
+ throw new BuilderException("Unknown guard constraint: " + cons);
+ }
+ }
+ break;
+ }
+ }
+ return exist;
+ }
+
+ @Override
+ public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException {
+ if (cLGuard.getGuards() == null || cLGuard.getGuards().isEmpty()) {
+ throw new BuilderException("No guard policies exist");
+ }
+ if (id == null) {
+ throw new BuilderException("The id of target guard policy must not be null");
+ }
+ boolean exist = false;
+ for (GuardPolicy policy: cLGuard.getGuards()) {
+ if (policy.getId().equals(id)) {
+ exist = true;
+ policy.getLimit_constraints().clear();
+ }
+ }
+ if (!exist) {
+ throw new BuilderException("No existing guard policy matching the id: " + id);
+ }
+ return this;
+ }
+
+
+ private class BuilderCompilerCallback implements ControlLoopCompilerCallback {
+
+ private ResultsImpl results = new ResultsImpl();
+
+ @Override
+ public boolean onWarning(String message) {
+ results.addMessage(new MessageImpl(message, MessageLevel.WARNING));
+ return false;
+ }
+
+ @Override
+ public boolean onError(String message) {
+ results.addMessage(new MessageImpl(message, MessageLevel.ERROR));
+ return false;
+ }
+ }
+
+ @Override
+ public ControlLoopGuard getControlLoopGuard() {
+ return new ControlLoopGuard(this.cLGuard);
+ }
+
+
+ @Override
+ public Results buildSpecification() {
+ //
+ // Dump the specification
+ //
+ DumperOptions options = new DumperOptions();
+ options.setDefaultFlowStyle(FlowStyle.BLOCK);
+ options.setPrettyFlow(true);
+ Yaml yaml = new Yaml(options);
+ String dumpedYaml = yaml.dump(cLGuard);
+ //
+ // This is our callback class for our compiler
+ //
+ BuilderCompilerCallback callback = new BuilderCompilerCallback();
+ //
+ // Compile it
+ //
+ try {
+ ControlLoopGuardCompiler.compile(cLGuard, callback);
+ } catch (CompilerException e) {
+ logger.error(e.getMessage() + e);
+ callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION));
+ }
+ //
+ // Save the spec
+ //
+ callback.results.setSpecification(dumpedYaml);
+ return callback.results;
+ }
+
+}
diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/poligy/guard/builder/ControlLoopGuardBuilder.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/poligy/guard/builder/ControlLoopGuardBuilder.java deleted file mode 100644 index e948b5238..000000000 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/poligy/guard/builder/ControlLoopGuardBuilder.java +++ /dev/null @@ -1,129 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-yaml - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. 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.poligy.guard.builder; - -import org.onap.policy.controlloop.policy.builder.BuilderException; -import org.onap.policy.controlloop.policy.builder.Results; -import org.onap.policy.controlloop.policy.guard.Constraint; -import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; -import org.onap.policy.controlloop.policy.guard.Guard; -import org.onap.policy.controlloop.policy.guard.GuardPolicy; -import org.onap.policy.controlloop.policy.guard.builder.impl.ControlLoopGuardBuilderImpl; - -public interface ControlLoopGuardBuilder { - - /** - * Adds one or more guard policies to the Control Loop Guard - * - * - * @param policies - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException; - - /** - * Removes one or more guard policies from the Control Loop Guard - * - * - * @param policies - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException; - - /** - * Removes all guard policies from the Control Loop Guard - * - * - * @param - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException; - - /** - * Adds one or more time limit constraints to the guard policy - * - * - * @param id (guard policy id) - * @param constraints - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException; - - /** - * Removes one or more time limit constraints from the guard policy - * - * - * @param id (guard policy id) - * @param constraints - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException; - - /** - * Removes all time limit constraints from the guard policy - * - * - * @param id (guard policy id) - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException; - - /** - * Simply return a copy of control loop guard - * - * @return ControlLoopGuard - */ - public ControlLoopGuard getControlLoopGuard(); - - /** - * This will compile and build the YAML specification for the Control Loop Guard. Please iterate the Results object for details. - * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the - * YAML. - * - * @return Results - */ - public Results buildSpecification(); - - /** - * The Factory is used to build a ControlLoopGuardBuilder implementation. - * - */ - public static class Factory { - - /** - * @param guard - * @return ControlLoopGuardBuilder object - * @throws BuilderException - */ - public static ControlLoopGuardBuilder buildControlLoopGuard (Guard guard) throws BuilderException { - - ControlLoopGuardBuilder builder = new ControlLoopGuardBuilderImpl(guard); - - return builder; - } - } -} diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java index 90d498a8d..f1681247d 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java @@ -33,12 +33,6 @@ import java.io.InputStream; import java.util.UUID; import org.junit.Test; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; -import org.yaml.snakeyaml.error.YAMLException; - -import org.onap.policy.aai.PNF; -import org.onap.policy.aai.PNFType; import org.onap.policy.controlloop.policy.builder.BuilderException; import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder; import org.onap.policy.controlloop.policy.builder.Message; @@ -47,85 +41,74 @@ import org.onap.policy.controlloop.policy.builder.Results; import org.onap.policy.sdc.Resource; import org.onap.policy.sdc.ResourceType; import org.onap.policy.sdc.Service; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.error.YAMLException; public class ControlLoopPolicyBuilderTest { - - @Test - public void testControlLoop() { + + @Test + public void testControlLoop() { try { - // - // Create a builder for our policy - // - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); - // - // Test add services - // - Service Ser1 = new Service("Ser1"); - Service Ser2 = new Service("Ser2"); - Service Ser3 = new Service("Ser3"); - builder = builder.addService(Ser1, Ser2, Ser3); - assertTrue(builder.getControlLoop().services.size() == 3); - // - // Test remove services - // - builder = builder.removeService(Ser1); - assertTrue(builder.getControlLoop().services.size() == 2); - builder = builder.removeAllServices(); - assertTrue(builder.getControlLoop().services.size() == 0); - // - // Test add resources - // - Resource Resrc1 = new Resource("Resrc1", ResourceType.VF); - Resource Resrc2 = new Resource("Resrc1", ResourceType.VF); - Resource Resrc3 = new Resource("Resrc1", ResourceType.VF); - builder = builder.addResource(Resrc1, Resrc2, Resrc3); - assertTrue(builder.getControlLoop().resources.size() == 3); - // - // Test remove resources - // - builder = builder.removeResource(Resrc1); - assertTrue(builder.getControlLoop().resources.size() == 2); - builder = builder.removeAllResources(); - assertTrue(builder.getControlLoop().resources.size() == 0); - // - // Test set pnf - // - PNF pnf = new PNF(); - pnf.PNFName = UUID.randomUUID().toString(); - pnf.PNFType = PNFType.ENODEB; - assertTrue(builder.getControlLoop().pnf == null); - builder = builder.setPNF(pnf); - assertTrue(builder.getControlLoop().pnf != null); - // - // Test remove pnf - // - builder = builder.removePNF(); - assertTrue(builder.getControlLoop().pnf == null); + // + // Create a builder for our policy + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + // + // Test add services + // + Service vSCP = new Service("vSCP"); + Service vUSP = new Service("vUSP"); + Service vTrinity = new Service("Trinity"); + builder = builder.addService(vSCP, vUSP, vTrinity); + assertTrue(builder.getControlLoop().getServices().size() == 3); + // + // Test remove services + // + builder = builder.removeService(vSCP); + assertTrue(builder.getControlLoop().getServices().size() == 2); + builder = builder.removeAllServices(); + assertTrue(builder.getControlLoop().getServices().size() == 0); + // + // Test add resources + // + Resource vCTS = new Resource("vCTS", ResourceType.VF); + Resource vCOM = new Resource("vCTS", ResourceType.VF); + Resource vRAR = new Resource("vCTS", ResourceType.VF); + builder = builder.addResource(vCTS, vCOM, vRAR); + assertTrue(builder.getControlLoop().getResources().size() == 3); + // + // Test remove resources + // + builder = builder.removeResource(vCTS); + assertTrue(builder.getControlLoop().getResources().size() == 2); + builder = builder.removeAllResources(); + assertTrue(builder.getControlLoop().getResources().size() == 0); // // Test set abatement // - assertFalse(builder.getControlLoop().abatement); + assertFalse(builder.getControlLoop().getAbatement()); builder = builder.setAbatement(true); - assertTrue(builder.getControlLoop().abatement); - } catch (BuilderException e) { - fail(e.getMessage()); - } - } - - @Test - public void testTimeout() { + assertTrue(builder.getControlLoop().getAbatement()); + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void testTimeout() { try { // // Create a builder for our policy // - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); // // Test setTimeout // - assertTrue(builder.getControlLoop().timeout == 2400); + assertTrue(builder.getControlLoop().getTimeout() == 2400); builder = builder.setTimeout(800); - assertTrue(builder.getControlLoop().timeout == 800); + assertTrue(builder.getControlLoop().getTimeout() == 800); // // Test calculateTimeout // @@ -139,7 +122,7 @@ public class ControlLoopPolicyBuilderTest { 2, 300); @SuppressWarnings("unused") - Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult( + Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult( "Rebuild VM", "If the restart fails, rebuild it", "APPC", @@ -148,7 +131,7 @@ public class ControlLoopPolicyBuilderTest { null, 1, 600, - trigger.id, + trigger.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT); @@ -157,11 +140,11 @@ public class ControlLoopPolicyBuilderTest { } catch (BuilderException e) { fail(e.getMessage()); } - } - - @Test - public void testTriggerPolicyMethods() { - try { + } + + @Test + public void testTriggerPolicyMethods() { + try { ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); // // Test isOpenLoop @@ -180,12 +163,12 @@ public class ControlLoopPolicyBuilderTest { 2, 300); assertTrue(builder.isOpenLoop() == false); - assertTrue(builder.getControlLoop().trigger_policy.equals(triggerPolicy1.id)); + assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId())); // // Set trigger policy to a new policy // @SuppressWarnings("unused") - Policy triggerPolicy2 = builder.setTriggerPolicy( + Policy triggerPolicy2 = builder.setTriggerPolicy( "Rebuild the VM", "Upon getting the trigger event, rebuild the VM", "APPC", @@ -198,8 +181,8 @@ public class ControlLoopPolicyBuilderTest { // Test set trigger policy to another existing policy // @SuppressWarnings("unused") - ControlLoop cl = builder.setTriggerPolicy(triggerPolicy1.id); - assertTrue(builder.getControlLoop().trigger_policy.equals(triggerPolicy1.id)); + ControlLoop cl = builder.setTriggerPolicy(triggerPolicy1.getId()); + assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId())); // // Test get trigger policy // @@ -209,11 +192,11 @@ public class ControlLoopPolicyBuilderTest { fail(e.getMessage()); } } - - @Test - public void testAddRemovePolicies() { - try { - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + + @Test + public void testAddRemovePolicies() { + try { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); Policy triggerPolicy = builder.setTriggerPolicy( "Restart the VM", "Upon getting the trigger event, restart the VM", @@ -235,25 +218,25 @@ public class ControlLoopPolicyBuilderTest { null, 1, 600, - triggerPolicy.id, + triggerPolicy.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT, PolicyResult.FAILURE_GUARD); // - assertTrue(builder.getTriggerPolicy().failure.equals(onRestartFailurePolicy1.id)); - assertTrue(builder.getTriggerPolicy().failure_retries.equals(onRestartFailurePolicy1.id)); - assertTrue(builder.getTriggerPolicy().failure_timeout.equals(onRestartFailurePolicy1.id)); - assertTrue(builder.getTriggerPolicy().failure_guard.equals(onRestartFailurePolicy1.id)); + assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy1.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy1.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy1.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy1.getId())); // // Test remove policy // - boolean removed = builder.removePolicy(onRestartFailurePolicy1.id); + boolean removed = builder.removePolicy(onRestartFailurePolicy1.getId()); assertTrue(removed); - assertTrue(builder.getTriggerPolicy().failure.equals(FinalResult.FINAL_FAILURE.toString())); - assertTrue(builder.getTriggerPolicy().failure_retries.equals(FinalResult.FINAL_FAILURE_RETRIES.toString())); - assertTrue(builder.getTriggerPolicy().failure_timeout.equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())); - assertTrue(builder.getTriggerPolicy().failure_guard.equals(FinalResult.FINAL_FAILURE_GUARD.toString())); + assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())); + assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())); // // Create another policy and chain it to the results of trigger policy // @@ -266,45 +249,45 @@ public class ControlLoopPolicyBuilderTest { null, 2, 600, - triggerPolicy.id, + triggerPolicy.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT); // // Test reset policy results // - triggerPolicy = builder.resetPolicyResults(triggerPolicy.id); - assertTrue(builder.getTriggerPolicy().failure.equals(FinalResult.FINAL_FAILURE.toString())); - assertTrue(builder.getTriggerPolicy().failure_retries.equals(FinalResult.FINAL_FAILURE_RETRIES.toString())); - assertTrue(builder.getTriggerPolicy().failure_timeout.equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())); + triggerPolicy = builder.resetPolicyResults(triggerPolicy.getId()); + assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())); // // Test set the policy results to an existing operational policy // onRestartFailurePolicy2 = builder.setPolicyForPolicyResult( - onRestartFailurePolicy2.id, - triggerPolicy.id, + onRestartFailurePolicy2.getId(), + triggerPolicy.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT); - assertTrue(builder.getTriggerPolicy().failure.equals(onRestartFailurePolicy2.id)); - assertTrue(builder.getTriggerPolicy().failure_retries.equals(onRestartFailurePolicy2.id)); - assertTrue(builder.getTriggerPolicy().failure_timeout.equals(onRestartFailurePolicy2.id)); + assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy2.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy2.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy2.getId())); // // Test remove all existing operational policies // builder = builder.removeAllPolicies(); - assertTrue(builder.getControlLoop().trigger_policy.equals(FinalResult.FINAL_OPENLOOP.toString())); + assertTrue(builder.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())); // } catch (BuilderException e) { fail(e.getMessage()); } } - @Test - public void testAddOperationsAccumulateParams() { - try { - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + @Test + public void testAddOperationsAccumulateParams() { + try { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); Policy triggerPolicy = builder.setTriggerPolicy( "Restart the eNodeB", "Upon getting the trigger event, restart the eNodeB", @@ -317,28 +300,28 @@ public class ControlLoopPolicyBuilderTest { // // Add the operationsAccumulateParams // - triggerPolicy = builder.addOperationsAccumulateParams(triggerPolicy.id, new OperationsAccumulateParams("15m", 5)); - assertNotNull(builder.getTriggerPolicy().operationsAccumulateParams); - assertTrue(builder.getTriggerPolicy().operationsAccumulateParams.period.equals("15m")); - assertTrue(builder.getTriggerPolicy().operationsAccumulateParams.limit == 5); + triggerPolicy = builder.addOperationsAccumulateParams(triggerPolicy.getId(), new OperationsAccumulateParams("15m", 5)); + assertNotNull(builder.getTriggerPolicy().getOperationsAccumulateParams()); + assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getPeriod().equals("15m")); + assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getLimit() == 5); // - } catch (BuilderException e) { + } catch (BuilderException e) { fail(e.getMessage()); } - } - - - @Test - public void testBuildSpecification() { - try { - // - // Create the builder - // - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 800); - // - // Set the first invalid trigger policy - // - Policy policy1 = builder.setTriggerPolicy( + } + + + @Test + public void testBuildSpecification() { + try { + // + // Create the builder + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 800); + // + // Set the first invalid trigger policy + // + Policy policy1 = builder.setTriggerPolicy( "Restart the VM", "Upon getting the trigger event, restart the VM", null, @@ -347,39 +330,39 @@ public class ControlLoopPolicyBuilderTest { null, 2, 300); - Results results = builder.buildSpecification(); - // - // Check that ERRORs are in results for invalid policy arguments - // - boolean invalid_actor = false; - boolean invalid_recipe = false; - boolean invalid_target = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("Policy actor is null") && m.getLevel() == MessageLevel.ERROR) { - invalid_actor = true; - } - if (m.getMessage().equals("Policy recipe is invalid") && m.getLevel() == MessageLevel.ERROR) { - invalid_recipe = true; - } - if (m.getMessage().equals("Policy target is null") && m.getLevel() == MessageLevel.ERROR) { - invalid_target = true; - } - } - // - assertTrue(invalid_actor); - assertTrue(invalid_recipe); - assertTrue(invalid_target); - // - // Remove the invalid policy - // - //@SuppressWarnings("unused") - boolean removed = builder.removePolicy(policy1.id); - assertTrue(removed); - assertTrue(builder.getTriggerPolicy() == null); - // - // Set a valid trigger policy - // - policy1 = builder.setTriggerPolicy( + Results results = builder.buildSpecification(); + // + // Check that ERRORs are in results for invalid policy arguments + // + boolean invalid_actor = false; + boolean invalid_recipe = false; + boolean invalid_target = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Policy actor is null") && m.getLevel() == MessageLevel.ERROR) { + invalid_actor = true; + } + if (m.getMessage().equals("Policy recipe is invalid") && m.getLevel() == MessageLevel.ERROR) { + invalid_recipe = true; + } + if (m.getMessage().equals("Policy target is null") && m.getLevel() == MessageLevel.ERROR) { + invalid_target = true; + } + } + // + assertTrue(invalid_actor); + assertTrue(invalid_recipe); + assertTrue(invalid_target); + // + // Remove the invalid policy + // + //@SuppressWarnings("unused") + boolean removed = builder.removePolicy(policy1.getId()); + assertTrue(removed); + assertTrue(builder.getTriggerPolicy() == null); + // + // Set a valid trigger policy + // + policy1 = builder.setTriggerPolicy( "Rebuild VM", "If the restart fails, rebuild it.", "APPC", @@ -388,11 +371,11 @@ public class ControlLoopPolicyBuilderTest { null, 1, 600); - // - // Set a second valid trigger policy - // - Policy policy2 = builder.setTriggerPolicy( - "Restart the VM", + // + // Set a second valid trigger policy + // + Policy policy2 = builder.setTriggerPolicy( + "Restart the VM", "Upon getting the trigger event, restart the VM", "APPC", new Target(TargetType.VM), @@ -400,141 +383,141 @@ public class ControlLoopPolicyBuilderTest { null, 2, 300); - // - // Now, we have policy1 unreachable - // - results = builder.buildSpecification(); - boolean unreachable = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("Policy " + policy1.id + " is not reachable.") && m.getLevel() == MessageLevel.WARNING) { - unreachable = true; - break; - } - } - assertTrue(unreachable); - // - // Set policy1 for the failure results of policy2 - // - policy1 = builder.setPolicyForPolicyResult( - policy1.id, - policy2.id, - PolicyResult.FAILURE, + // + // Now, we have policy1 unreachable + // + results = builder.buildSpecification(); + boolean unreachable = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Policy " + policy1.getId() + " is not reachable.") && m.getLevel() == MessageLevel.WARNING) { + unreachable = true; + break; + } + } + assertTrue(unreachable); + // + // Set policy1 for the failure results of policy2 + // + policy1 = builder.setPolicyForPolicyResult( + policy1.getId(), + policy2.getId(), + PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT); - results = builder.buildSpecification(); - boolean invalid_timeout = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("controlLoop overall timeout is less than the sum of operational policy timeouts.") && m.getLevel() == MessageLevel.ERROR) { - invalid_timeout = true; - break; - } - } - assertTrue(invalid_timeout); - // - // Remove policy2 (revert controlLoop back to open loop) - // - removed = builder.removePolicy(policy2.id); - // - // ControlLoop is open loop now, but it still has policies (policy1) - // - results = builder.buildSpecification(); - unreachable = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("Open Loop policy contains policies. The policies will never be invoked.") && m.getLevel() == MessageLevel.WARNING) { - unreachable = true; - break; - } - } - assertTrue(unreachable); - // - } catch (BuilderException e) { + results = builder.buildSpecification(); + boolean invalid_timeout = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("controlLoop overall timeout is less than the sum of operational policy timeouts.") && m.getLevel() == MessageLevel.ERROR) { + invalid_timeout = true; + break; + } + } + assertTrue(invalid_timeout); + // + // Remove policy2 (revert controlLoop back to open loop) + // + removed = builder.removePolicy(policy2.getId()); + // + // ControlLoop is open loop now, but it still has policies (policy1) + // + results = builder.buildSpecification(); + unreachable = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Open Loop policy contains policies. The policies will never be invoked.") && m.getLevel() == MessageLevel.WARNING) { + unreachable = true; + break; + } + } + assertTrue(unreachable); + // + } catch (BuilderException e) { fail(e.getMessage()); } - } - - - @Test - public void test() { - this.test("src/test/resources/v1.0.0/policy_Test.yaml"); - } - - @Test - public void testEvilYaml() { - try (InputStream is = new FileInputStream(new File("src/test/resources/v1.0.0/test_evil.yaml"))) { - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - yaml.load(is); - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } catch (YAMLException e) { - // - // Should have this - // - } - } - - public void test(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - Object obj = yaml.load(is); - assertNotNull(obj); - assertTrue(obj instanceof ControlLoopPolicy); - ControlLoopPolicy policyTobuild = (ControlLoopPolicy) obj; - // - // Now we're going to try to use the builder to build this. - // - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop( - policyTobuild.controlLoop.controlLoopName, - policyTobuild.controlLoop.timeout); - // - // Add services - // - if (policyTobuild.controlLoop.services != null) { - builder = builder.addService(policyTobuild.controlLoop.services.toArray(new Service[policyTobuild.controlLoop.services.size()])); - } - // - // Add resources - // - if (policyTobuild.controlLoop.resources != null) { - builder = builder.addResource(policyTobuild.controlLoop.resources.toArray(new Resource[policyTobuild.controlLoop.resources.size()])); - } - // - // Set pnf - // - if (policyTobuild.controlLoop.pnf != null) { - builder = builder.setPNF(policyTobuild.controlLoop.pnf); - } - // - // Add the policies and be sure to set the trigger policy - // - if (policyTobuild.policies != null) { - for (Policy policy : policyTobuild.policies) { - if (policy.id == policyTobuild.controlLoop.trigger_policy) { - builder.setTriggerPolicy(policy.name, policy.description, policy.actor, policy.target, policy.recipe, null, policy.retry, policy.timeout); - } - } - } - - // Question : how to change policy ID and results by using builder ?? - - @SuppressWarnings("unused") - Results results = builder.buildSpecification(); - - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } catch (BuilderException e) { - fail(e.getLocalizedMessage()); - } - - } + } + + + @Test + public void test() { + this.test("src/test/resources/v1.0.0/policy_Test.yaml"); + } + + @Test + public void testEvilYaml() { + try (InputStream is = new FileInputStream(new File("src/test/resources/v1.0.0/test_evil.yaml"))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + yaml.load(is); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } catch (YAMLException e) { + // + // Should have this + // + } + } + + public void test(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(is); + assertNotNull(obj); + assertTrue(obj instanceof ControlLoopPolicy); + ControlLoopPolicy policyTobuild = (ControlLoopPolicy) obj; + // + // Now we're going to try to use the builder to build this. + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop( + policyTobuild.getControlLoop().getControlLoopName(), + policyTobuild.getControlLoop().getTimeout()); + // + // Add services + // + if (policyTobuild.getControlLoop().getServices() != null) { + builder = builder.addService(policyTobuild.getControlLoop().getServices().toArray(new Service[policyTobuild.getControlLoop().getServices().size()])); + } + // + // Add resources + // + if (policyTobuild.getControlLoop().getResources() != null) { + builder = builder.addResource(policyTobuild.getControlLoop().getResources().toArray(new Resource[policyTobuild.getControlLoop().getResources().size()])); + } + // + // Set pnf + // + if (policyTobuild.getControlLoop().getPnf() != null) { + builder = builder.setPNF(policyTobuild.getControlLoop().getPnf()); + } + // + // Add the policies and be sure to set the trigger policy + // + if (policyTobuild.getPolicies() != null) { + for (Policy policy : policyTobuild.getPolicies()) { + if (policy.getId() == policyTobuild.getControlLoop().getTrigger_policy()) { + builder.setTriggerPolicy(policy.getName(), policy.getDescription(), policy.getActor(), policy.getTarget(), policy.getRecipe(), null, policy.getRetry(), policy.getTimeout()); + } + } + } + + // Question : how to change policy ID and results by using builder ?? + + @SuppressWarnings("unused") + Results results = builder.buildSpecification(); + + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } catch (BuilderException e) { + fail(e.getLocalizedMessage()); + } + + } } diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java index 9cc1bbd6a..da81db394 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java @@ -20,10 +20,6 @@ package org.onap.policy.controlloop.policy.guard; -import org.junit.Test; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -38,167 +34,170 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import org.junit.Test; import org.onap.policy.controlloop.policy.builder.BuilderException; import org.onap.policy.controlloop.policy.builder.Message; import org.onap.policy.controlloop.policy.builder.MessageLevel; import org.onap.policy.controlloop.policy.builder.Results; -import org.onap.policy.controlloop.poligy.guard.builder.ControlLoopGuardBuilder; +import org.onap.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; public class ControlLoopGuardBuilderTest { - - @Test - public void testControlLoopGuard() { - try { - // - // Create a builder - // - ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); - // - // Assert there is no guard policies yet - // - Results results = builder.buildSpecification(); - boolean no_guard_policies = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("ControlLoop Guard should have at least one guard policies") && m.getLevel() == MessageLevel.ERROR) { - no_guard_policies = true; - break; - } - } - assertTrue(no_guard_policies); - // - // Add a guard policy without limit constraint - // - String clname = "CL_vUSP123"; - LinkedList<String> targets = new LinkedList<String>(); - targets.add("s1"); - targets.add("s2"); - targets.add("s3"); - MatchParameters matchParameters = new MatchParameters(clname, "APPC", "Restart", targets); - GuardPolicy policy1 = new GuardPolicy("id123", "guardpolicy1", "description aaa", matchParameters); - builder = builder.addGuardPolicy(policy1); - // - // Assert there is no limit constraint associated with the only guard policy - // - results = builder.buildSpecification(); - boolean no_constraint = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("Guard policy guardpolicy1 does not have any limit constraint") && m.getLevel() == MessageLevel.ERROR) { - no_constraint = true; - break; - } - } - assertTrue(no_constraint); - // - // Add a constraint to policy1 - // - Map<String, String> active_time_range = new HashMap<String, String>(); - active_time_range.put("start", "00:00:00-05:00"); - active_time_range.put("end", "23:59:59-05:00"); - List<String> blacklist = new LinkedList<String>(); - blacklist.add("eNodeB_common_id1"); - blacklist.add("eNodeB_common_id2"); - Map<String, String> time_window = new HashMap<String, String>(); - time_window.put("value", "10"); - time_window.put("units", "minute"); - Constraint cons = new Constraint(5, time_window, active_time_range, blacklist); - builder = builder.addLimitConstraint(policy1.id, cons); - // - // Add a duplicate constraint to policy1 - // - builder = builder.addLimitConstraint(policy1.id, cons); - // - // Assert there are duplicate constraints associated with the only guard policy - // - results = builder.buildSpecification(); - boolean duplicate_constraint = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("Guard policy guardpolicy1 has duplicate limit constraints") && m.getLevel() == MessageLevel.WARNING) { - duplicate_constraint = true; - break; - } - } - assertTrue(duplicate_constraint); - // - // Remove the duplicate constraint - // - builder = builder.removeLimitConstraint(policy1.id, cons); - // - // Add a duplicate guard policy - // - builder = builder.addGuardPolicy(policy1); - builder = builder.addLimitConstraint(policy1.id, cons); - // - // Assert there are duplicate guard policies - // - results = builder.buildSpecification(); - boolean duplicate_guard_policy = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("There are duplicate guard policies") && m.getLevel() == MessageLevel.WARNING) { - duplicate_guard_policy = true; - break; - } - } - assertTrue(duplicate_guard_policy); - // - // Remove the duplicate guard policy - // - builder = builder.removeGuardPolicy(policy1); - // - // Assert there are no Error/Warning message - // - results = builder.buildSpecification(); - assertTrue(results.getMessages().size() == 1); - // - } catch (BuilderException e) { - fail(e.getMessage()); - } - } - - @Test - public void test1() { - this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml"); - } - - @Test - public void test2() { - this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml"); - } - - public void test(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); - Object obj = yaml.load(is); - assertNotNull(obj); - assertTrue(obj instanceof ControlLoopGuard); - ControlLoopGuard guardTobuild = (ControlLoopGuard) obj; - // - // Now we're going to try to use the builder to build this. - // - ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(guardTobuild.guard); - // - // Add guard policy - // - if (guardTobuild.guards != null) { - builder = builder.addGuardPolicy(guardTobuild.guards.toArray(new GuardPolicy[guardTobuild.guards.size()])); - } - // - // Build the specification - // - Results results = builder.buildSpecification(); - // - // Print out the specification - // - System.out.println(results.getSpecification()); - // - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } catch (BuilderException e) { - fail(e.getLocalizedMessage()); - } - } + + @Test + public void testControlLoopGuard() { + try { + // + // Create a builder + // + ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); + // + // Assert there is no guard policies yet + // + Results results = builder.buildSpecification(); + boolean no_guard_policies = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("ControlLoop Guard should have at least one guard policies") && m.getLevel() == MessageLevel.ERROR) { + no_guard_policies = true; + break; + } + } + assertTrue(no_guard_policies); + // + // Add a guard policy without limit constraint + // + String clname = "CL_vUSP123"; + LinkedList<String> targets = new LinkedList<String>(); + targets.add("s1"); + targets.add("s2"); + targets.add("s3"); + MatchParameters matchParameters = new MatchParameters(clname, "APPC", "Restart", targets); + GuardPolicy policy1 = new GuardPolicy("id123", "guardpolicy1", "description aaa", matchParameters); + builder = builder.addGuardPolicy(policy1); + // + // Assert there is no limit constraint associated with the only guard policy + // + results = builder.buildSpecification(); + boolean no_constraint = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Guard policy guardpolicy1 does not have any limit constraint") && m.getLevel() == MessageLevel.ERROR) { + no_constraint = true; + break; + } + } + assertTrue(no_constraint); + // + // Add a constraint to policy1 + // + Map<String, String> active_time_range = new HashMap<String, String>(); + active_time_range.put("start", "00:00:00-05:00"); + active_time_range.put("end", "23:59:59-05:00"); + List<String> blacklist = new LinkedList<String>(); + blacklist.add("eNodeB_common_id1"); + blacklist.add("eNodeB_common_id2"); + Map<String, String> time_window = new HashMap<String, String>(); + time_window.put("value", "10"); + time_window.put("units", "minute"); + Constraint cons = new Constraint(5, time_window, active_time_range, blacklist); + builder = builder.addLimitConstraint(policy1.getId(), cons); + // + // Add a duplicate constraint to policy1 + // + builder = builder.addLimitConstraint(policy1.getId(), cons); + // + // Assert there are duplicate constraints associated with the only guard policy + // + results = builder.buildSpecification(); + boolean duplicate_constraint = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Guard policy guardpolicy1 has duplicate limit constraints") && m.getLevel() == MessageLevel.WARNING) { + duplicate_constraint = true; + break; + } + } + assertTrue(duplicate_constraint); + // + // Remove the duplicate constraint + // + builder = builder.removeLimitConstraint(policy1.getId(), cons); + // + // Add a duplicate guard policy + // + builder = builder.addGuardPolicy(policy1); + builder = builder.addLimitConstraint(policy1.getId(), cons); + // + // Assert there are duplicate guard policies + // + results = builder.buildSpecification(); + boolean duplicate_guard_policy = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("There are duplicate guard policies") && m.getLevel() == MessageLevel.WARNING) { + duplicate_guard_policy = true; + break; + } + } + assertTrue(duplicate_guard_policy); + // + // Remove the duplicate guard policy + // + builder = builder.removeGuardPolicy(policy1); + // + // Assert there are no Error/Warning message + // + results = builder.buildSpecification(); + assertTrue(results.getMessages().size() == 1); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void test1() { + this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml"); + } + + @Test + public void test2() { + this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml"); + } + + public void test(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(is); + assertNotNull(obj); + assertTrue(obj instanceof ControlLoopGuard); + ControlLoopGuard guardTobuild = (ControlLoopGuard) obj; + // + // Now we're going to try to use the builder to build this. + // + ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(guardTobuild.getGuard()); + // + // Add guard policy + // + if (guardTobuild.getGuards() != null) { + builder = builder.addGuardPolicy(guardTobuild.getGuards().toArray(new GuardPolicy[guardTobuild.getGuards().size()])); + } + // + // Build the specification + // + Results results = builder.buildSpecification(); + // + // Print out the specification + // + System.out.println(results.getSpecification()); + // + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } catch (BuilderException e) { + fail(e.getLocalizedMessage()); + } + } } diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_vService.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_vService.yaml index d679e0773..fc4763460 100644 --- a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_vService.yaml +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_vService.yaml @@ -1,121 +1,121 @@ -controlLoop: - version: 2.0.0 - controlLoopName: ControlLoop-GENERIC-64cdc9fa-6601-4989-9de7-8f47134aa043 - # - # Example of how someone can fine-grain this - # policy for a specific service and/or resources - # contained within the service. - # - services: - - serviceName: vFooService - - resources: - - resourceName: vVNF1 - resourceType: VFC - - resourceName: vVNF2 - resourceType: VFC - - resourceName: vVNF3 - resourceType: VFC - - resourceName: vVNF4 - resourceType: VFC - - trigger_policy: unique-policy-id-1-restart - timeout: 1200 - # - # Example of case where an abatement isn't possible - # from DCAE to Policy. So Policy should NOT expect - # - abatement: false - -policies: - - - id: unique-policy-id-1-restart - name: Restart Policy - description: - actor: APPC - recipe: Restart - target: - type: VM - retry: 2 - timeout: 300 - success: unique-policy-id-1-healthdiagnostic - 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 - failure_guard: unique-policy-id-2-rebuild - - - - id: unique-policy-id-2-rebuild - name: Rebuild Policy - description: - actor: APPC - recipe: Rebuild - target: - type: VM - retry: 0 - timeout: 600 - success: unique-policy-id-2-healthdiagnostic - 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 - failure_guard: unique-policy-id-3-migrate - - - id: unique-policy-id-3-migrate - name: Migrate Policy - description: - actor: APPC - recipe: Migrate - target: - type: VM - retry: 0 - timeout: 600 - success: final_success - failure: final_failure - failure_timeout: final_failure_timeout - failure_retries: final_failure_retries - failure_exception: final_failure_exception - failure_guard: final_failure_guard - - - id: unique-policy-id-1-healthdiagnostic - name: Do A Health Diagnostic - description: - actor: APPC - recipe: health-diagnostic - # Example of a payload - payload: - health-diagnostic-code: HC01234 - health-diagnostic-code-parameters: "{\"Junk\":\"--version\",\"Junk2\":\"--help\"}" - target: - type: VM - retry: 0 - timeout: 600 - 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 - failure_guard: unique-policy-id-2-rebuild - - - - id: unique-policy-id-2-healthdiagnostic - name: Do Health Diagnostic - description: - actor: APPC - recipe: health-diagnostic - payload: - health-diagnostic-code: HC01234 - health-diagnostic-code-parameters: "{\"Junk\":\"--version\",\"Junk2\":\"--help\"}" - target: - type: VM - retry: 0 - timeout: 600 - success: final_success - failure: final_failure - failure_timeout: final_failure_timeout - failure_retries: final_failure_retries - failure_exception: final_failure_exception - failure_guard: final_failure_guard - - +controlLoop:
+ version: 2.0.0
+ controlLoopName: ControlLoop-GENERIC-64cdc9fa-6601-4989-9de7-8f47134aa043
+ #
+ # Example of how someone can fine-grain this
+ # policy for a specific service and/or resources
+ # contained within the service.
+ #
+ services:
+ - serviceName: vFooService
+
+ resources:
+ - resourceName: vVNF1
+ resourceType: VFC
+ - resourceName: vVNF2
+ resourceType: VFC
+ - resourceName: vVNF3
+ resourceType: VFC
+ - resourceName: vVNF4
+ resourceType: VFC
+
+ trigger_policy: unique-policy-id-1-restart
+ timeout: 1200
+ #
+ # Example of case where an abatement isn't possible
+ # from DCAE to Policy. So Policy should NOT expect
+ #
+ abatement: false
+
+policies:
+
+ - id: unique-policy-id-1-restart
+ name: Restart Policy
+ description:
+ actor: APPC
+ recipe: Restart
+ target:
+ type: VM
+ retry: 2
+ timeout: 300
+ success: unique-policy-id-1-healthdiagnostic
+ 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
+ failure_guard: unique-policy-id-2-rebuild
+
+
+ - id: unique-policy-id-2-rebuild
+ name: Rebuild Policy
+ description:
+ actor: APPC
+ recipe: Rebuild
+ target:
+ type: VM
+ retry: 0
+ timeout: 600
+ success: unique-policy-id-2-healthdiagnostic
+ 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
+ failure_guard: unique-policy-id-3-migrate
+
+ - id: unique-policy-id-3-migrate
+ name: Migrate Policy
+ description:
+ actor: APPC
+ recipe: Migrate
+ target:
+ type: VM
+ retry: 0
+ timeout: 600
+ success: final_success
+ failure: final_failure
+ failure_timeout: final_failure_timeout
+ failure_retries: final_failure_retries
+ failure_exception: final_failure_exception
+ failure_guard: final_failure_guard
+
+ - id: unique-policy-id-1-healthdiagnostic
+ name: Do A Health Diagnostic
+ description:
+ actor: APPC
+ recipe: health-diagnostic
+ # Example of a payload
+ payload:
+ health-diagnostic-code: HC01234
+ health-diagnostic-code-parameters: "{\"Junk\":\"--version\",\"Junk2\":\"--help\"}"
+ target:
+ type: VM
+ retry: 0
+ timeout: 600
+ 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
+ failure_guard: unique-policy-id-2-rebuild
+
+
+ - id: unique-policy-id-2-healthdiagnostic
+ name: Do Health Diagnostic
+ description:
+ actor: APPC
+ recipe: health-diagnostic
+ payload:
+ health-diagnostic-code: HC01234
+ health-diagnostic-code-parameters: "{\"Junk\":\"--version\",\"Junk2\":\"--help\"}"
+ target:
+ type: VM
+ retry: 0
+ timeout: 600
+ success: final_success
+ failure: final_failure
+ failure_timeout: final_failure_timeout
+ failure_retries: final_failure_retries
+ failure_exception: final_failure_exception
+ failure_guard: final_failure_guard
+
+
|