diff options
author | ning.xi <ning.xi@est.tech> | 2019-04-04 02:55:50 +0000 |
---|---|---|
committer | Pamela Dragosh <pdragosh@research.att.com> | 2019-04-05 15:34:01 +0000 |
commit | 0b860c87dc3bcc9058cde521f3fbda6f0aad2ec4 (patch) | |
tree | 42503b4d62575e770d9236a32dbdb53b477acf16 /models-interactions/model-yaml/src/main/java/org | |
parent | 38cc81922273039d2d32979123bb83a15c49debf (diff) |
remove dependency of drool-application/yaml in actors
Issue-ID: POLICY-1264
Change-Id: Ie89749cf25d6880fd2884eb6935f36f046114b23
Signed-off-by: ning.xi <ning.xi@est.tech>
Diffstat (limited to 'models-interactions/model-yaml/src/main/java/org')
28 files changed, 4425 insertions, 0 deletions
diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/CompilerException.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/CompilerException.java new file mode 100644 index 000000000..e064750a4 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/CompilerException.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.compiler; + +public class CompilerException extends Exception { + + private static final long serialVersionUID = -7262217239867898601L; + + public CompilerException() { + } + + public CompilerException(String message) { + super(message); + } + + public CompilerException(Throwable cause) { + super(cause); + } + + public CompilerException(String message, Throwable cause) { + super(message, cause); + } + + public CompilerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java new file mode 100644 index 000000000..91b5266cc --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java @@ -0,0 +1,739 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.compiler; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +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.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; + + +public class ControlLoopCompiler implements Serializable { + private static final String OPERATION_POLICY = "Operation Policy "; + private static final long serialVersionUID = 1L; + private static final Logger LOGGER = LoggerFactory.getLogger(ControlLoopCompiler.class.getName()); + + /** + * Compiles the policy from an object. + */ + 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; + } + + /** + * Compiles the policy from an input stream. + * + * @param yamlSpecification the yaml input stream + * @param callback method to callback during compilation + * @return Control Loop object + * @throws CompilerException throws any compile exception found + */ + 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.getCompilerVersion())) && 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"); + } + if (policy.getPolicies() == null) { + callback.onWarning("controlLoop is an open loop."); + } else { + // + // 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) { + validateOpenLoopPolicy(policy, triggerResult, callback); + return; + // + } else { + validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(policy, callback); + 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 = addPoliciesAsNodes(policy, graph, triggerNode, callback); + // + // 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; + } + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getSuccess(), finalSuccess, + PolicyResult.SUCCESS, node); + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure(), finalFailure, + PolicyResult.FAILURE, node); + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_timeout(), finalFailureTimeout, + PolicyResult.FAILURE_TIMEOUT, node); + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_retries(), finalFailureRetries, + PolicyResult.FAILURE_RETRIES, node); + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_exception(), finalFailureException, + PolicyResult.FAILURE_EXCEPTION, node); + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_guard(), finalFailureGuard, + PolicyResult.FAILURE_GUARD, node); + } + validateNodesAndEdges(graph, callback); + } + } + + private static void validateOpenLoopPolicy(ControlLoopPolicy policy, FinalResult triggerResult, + ControlLoopCompilerCallback callback) throws CompilerException { + // + // 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."); + } + } + + private static void validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(ControlLoopPolicy policy, + ControlLoopCompilerCallback callback) throws CompilerException { + int sum = 0; + boolean triggerPolicyFound = false; + for (Policy operPolicy : policy.getPolicies()) { + sum += operPolicy.getTimeout().intValue(); + if (policy.getControlLoop().getTrigger_policy().equals(operPolicy.getId())) { + triggerPolicyFound = true; + } + } + if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) { + callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts."); + } + + if (!triggerPolicyFound) { + throw new CompilerException("Unexpected value for trigger_policy, should only be " + + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); + } + } + + private static Map<Policy, PolicyNodeWrapper> addPoliciesAsNodes(ControlLoopPolicy policy, + DirectedGraph<NodeWrapper, LabeledEdge> graph, TriggerNodeWrapper triggerNode, + ControlLoopCompilerCallback callback) { + 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"))); + } + } + return mapNodes; + } + + private static void addEdge(DirectedGraph<NodeWrapper, LabeledEdge> graph, Map<Policy, PolicyNodeWrapper> mapNodes, + String policyId, String connectedPolicy, + FinalResultNodeWrapper finalResultNodeWrapper, + PolicyResult policyResult, NodeWrapper node) throws CompilerException { + FinalResult finalResult = FinalResult.toResult(finalResultNodeWrapper.getId()); + if (FinalResult.isResult(connectedPolicy, finalResult)) { + graph.addEdge(node, finalResultNodeWrapper, new LabeledEdge(node, finalResultNodeWrapper, + new FinalResultEdgeWrapper(finalResult))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, connectedPolicy); + if (toNode == null) { + throw new CompilerException(OPERATION_POLICY + policyId + " is connected to unknown policy " + + connectedPolicy); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(policyResult))); + } + } + } + + private static void validateNodesAndEdges(DirectedGraph<NodeWrapper, LabeledEdge> graph, + ControlLoopCompilerCallback callback) throws CompilerException { + for (NodeWrapper node : graph.vertexSet()) { + if (node instanceof TriggerNodeWrapper) { + validateTriggerNodeWrapper(graph, node); + } else if (node instanceof FinalResultNodeWrapper) { + validateFinalResultNodeWrapper(graph, node); + } else if (node instanceof PolicyNodeWrapper) { + validatePolicyNodeWrapper(graph, node, callback); + } + for (LabeledEdge edge : graph.outgoingEdgesOf(node)) { + LOGGER.info("{} invokes {} upon {}", edge.from.getId(), edge.to.getId(), edge.edge.getId()); + } + } + } + + private static void validateTriggerNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph, + NodeWrapper node) throws CompilerException { + if (LOGGER.isDebugEnabled()) { + LOGGER.info("Trigger Node {}", node); + } + 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"); + } + } + + private static void validateFinalResultNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph, + NodeWrapper node) throws CompilerException { + if (LOGGER.isDebugEnabled()) { + LOGGER.info("FinalResult Node {}", node); + } + // + // FinalResult nodes should NEVER have an out edge + // + if (graph.outDegreeOf(node) > 0) { + throw new CompilerException("FinalResult nodes should never have any out edges."); + } + } + + private static void validatePolicyNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph, + NodeWrapper node, ControlLoopCompilerCallback callback) throws CompilerException { + if (LOGGER.isDebugEnabled()) { + LOGGER.info("Policy Node {}", node); + } + // + // 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."); + } + } + + private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = isPolicyIdOk(operPolicy, callback); + if (! isActorOk(operPolicy, callback)) { + isOk = false; + } + if (! isRecipeOk(operPolicy, callback)) { + isOk = false; + } + if (! isTargetOk(operPolicy, callback) ) { + isOk = false; + } + if (! arePolicyResultsOk(operPolicy, callback) ) { + isOk = false; + } + return isOk; + } + + private static boolean isPolicyIdOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (operPolicy.getId() == null || operPolicy.getId().length() < 1) { + if (callback != null) { + callback.onError("Operational Policy has an bad ID"); + } + isOk = false; + } else { + // + // 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()); + } + isOk = false; + } + if (FinalResult.toResult(operPolicy.getId()) != null) { + if (callback != null) { + callback.onError("Policy id is set to a FinalResult " + operPolicy.getId()); + } + isOk = false; + } + } + return isOk; + } + + private static boolean isActorOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (operPolicy.getActor() == null) { + if (callback != null) { + callback.onError("Policy actor is null"); + } + isOk = false; + } + // + // Construct a list for all valid actors + // + ImmutableList<String> actors = ImmutableList.of("APPC", "SDNC", "SDNR", "SO", "VFC"); + // + if (operPolicy.getActor() != null && (!actors.contains(operPolicy.getActor())) ) { + if (callback != null) { + callback.onError("Policy actor is invalid"); + } + isOk = false; + } + return isOk; + } + + private static boolean isRecipeOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (operPolicy.getRecipe() == null) { + if (callback != null) { + callback.onError("Policy recipe is null"); + } + isOk = 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("SDNC", ImmutableList.of("Reroute")) + .put("SDNR", ImmutableList.of("ModifyConfig")) + .put("SO", ImmutableList.of("VF Module Create", "VF Module Delete")) + .put("VFC", ImmutableList.of("Restart")) + .build(); + // + if (operPolicy.getRecipe() != null + && (!recipes.getOrDefault(operPolicy.getActor(), + Collections.emptyList()).contains(operPolicy.getRecipe()))) { + if (callback != null) { + callback.onError("Policy recipe is invalid"); + } + isOk = false; + } + return isOk; + } + + private static boolean isTargetOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (operPolicy.getTarget() == null) { + if (callback != null) { + callback.onError("Policy target is null"); + } + isOk = 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"); + } + isOk = false; + } + return isOk; + } + + private static boolean arePolicyResultsOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + // + // Check that policy results are connected to either default final * or another policy + // + boolean isOk = isSuccessPolicyResultOk(operPolicy, callback); + if (! isFailurePolicyResultOk(operPolicy, callback) ) { + isOk = false; + } + if (! isFailureRetriesPolicyResultOk(operPolicy, callback) ) { + isOk = false; + } + if (! isFailureTimeoutPolicyResultOk(operPolicy, callback) ) { + isOk = false; + } + if (! isFailureExceptionPolicyResultOk(operPolicy, callback) ) { + isOk = false; + } + if (! isFailureGuardPolicyResultOk(operPolicy, callback) ) { + isOk = false; + } + return isOk; + } + + private static boolean isSuccessPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getSuccess()) != null + && !operPolicy.getSuccess().equals(FinalResult.FINAL_SUCCESS.toString())) { + if (callback != null) { + callback.onError("Policy success is neither another policy nor FINAL_SUCCESS"); + } + isOk = false; + } + return isOk; + } + + private static boolean isFailurePolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getFailure()) != null + && !operPolicy.getFailure().equals(FinalResult.FINAL_FAILURE.toString())) { + if (callback != null) { + callback.onError("Policy failure is neither another policy nor FINAL_FAILURE"); + } + isOk = false; + } + return isOk; + } + + private static boolean isFailureRetriesPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getFailure_retries()) != null + && !operPolicy.getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())) { + if (callback != null) { + callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES"); + } + isOk = false; + } + return isOk; + } + + private static boolean isFailureTimeoutPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null + && !operPolicy.getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())) { + if (callback != null) { + callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT"); + } + isOk = false; + } + return isOk; + } + + private static boolean isFailureExceptionPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getFailure_exception()) != null + && !operPolicy.getFailure_exception().equals(FinalResult.FINAL_FAILURE_EXCEPTION.toString())) { + if (callback != null) { + callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION"); + } + isOk = false; + } + return isOk; + } + + private static boolean isFailureGuardPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getFailure_guard()) != null + && !operPolicy.getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())) { + if (callback != null) { + callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD"); + } + isOk = false; + } + return isOk; + } + + 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 "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]"; + } + + @Override + public String getId() { + return closedLoopControlName; + } + + } + + private static class FinalResultNodeWrapper implements NodeWrapper { + private static final long serialVersionUID = 8540008796302474613L; + private FinalResult result; + + public FinalResultNodeWrapper(FinalResult result) { + this.result = result; + } + + @Override + public String toString() { + return "FinalResultNodeWrapper [result=" + result + "]"; + } + + @Override + public String getId() { + return result.toString(); + } + } + + private static class PolicyNodeWrapper implements NodeWrapper { + private static final long serialVersionUID = 8170162175653823082L; + private transient Policy policy; + + public PolicyNodeWrapper(Policy operPolicy) { + this.policy = operPolicy; + } + + @Override + public String toString() { + return "PolicyNodeWrapper [policy=" + policy + "]"; + } + + @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; + } + + @Override + public String getId() { + return trigger; + } + + @Override + public String toString() { + return "TriggerEdgeWrapper [trigger=" + trigger + "]"; + } + + } + + private static class PolicyResultEdgeWrapper implements EdgeWrapper { + private static final long serialVersionUID = 6078569477021558310L; + private PolicyResult policyResult; + + public PolicyResultEdgeWrapper(PolicyResult policyResult) { + super(); + this.policyResult = policyResult; + } + + @Override + public String toString() { + return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]"; + } + + @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; + } + + @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 + "]"; + } + } + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerCallback.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerCallback.java new file mode 100644 index 000000000..e59ce3460 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerCallback.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.compiler; + +public interface ControlLoopCompilerCallback { + + public boolean onWarning(String message); + + public boolean onError(String message); + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java new file mode 100644 index 000000000..435963a9e --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.guard.compiler; + +import java.io.InputStream; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +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 { + + private static final String GUARD_POLICIES_SHOULD_NOT_BE_NULL = "Guard policies should not be null"; + private static final String GUARD_POLICY = "Guard policy "; + + private ControlLoopGuardCompiler(){ + // Private Constructor + } + + /** + * Compile the control loop guard. + * + * @param clGuard the guard + * @param callback callback routine + * @return the guard object + * @throws CompilerException compilation exception + */ + 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; + } + + /** + * Compile the control loop guard. + * + * @param yamlSpecification yaml specification as a stream + * @param callback callback method + * @return guard object + * @throws CompilerException throws compile exception + */ + 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/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java new file mode 100644 index 000000000..fc3d82326 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +import java.io.Serializable; +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 implements Serializable { + private static final long serialVersionUID = 1L; + + private static final String COMPILER_VERSION = "2.0.0"; + + private String controlLoopName; + private String version = COMPILER_VERSION; + private List<Service> services; + private List<Resource> resources; + private Pnf pnf; + private String triggerPolicy = FinalResult.FINAL_OPENLOOP.toString(); + private Integer timeout; + private Boolean abatement = false; + + public ControlLoop() { + // Empty Constructor. + } + + /** + * Constructor. + * + * @param controlLoop copy object + */ + 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.triggerPolicy = controlLoop.triggerPolicy; + this.timeout = controlLoop.timeout; + this.abatement = controlLoop.abatement; + } + + public static String getCompilerVersion() { + return ControlLoop.COMPILER_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 triggerPolicy; + } + + public void setTrigger_policy(String triggerPolicy) { + this.triggerPolicy = triggerPolicy; + } + + 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; + } + + @Override + public String toString() { + return "ControlLoop [controlLoopName=" + controlLoopName + ", version=" + version + ", services=" + services + + ", resources=" + resources + ", trigger_policy=" + triggerPolicy + ", 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 + ((triggerPolicy == null) ? 0 : triggerPolicy.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; + return equalsMayBeNull(controlLoopName, other.controlLoopName) && equalsMayBeNull(resources, other.resources) + && equalsMayBeNull(services, other.services) && equalsMayBeNull(timeout, other.timeout) + && equalsMayBeNull(triggerPolicy, other.triggerPolicy) && equalsMayBeNull(version, other.version) + && equalsMayBeNull(abatement, other.abatement); + } + + private boolean equalsMayBeNull(final Object obj1, final Object obj2) { + if (obj1 == null) { + return obj2 == null; + } + return obj1.equals(obj2); + } + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java new file mode 100644 index 000000000..e90182d58 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +import java.io.Serializable; +import java.util.List; + +public class ControlLoopPolicy implements Serializable { + private static final long serialVersionUID = 1L; + + private ControlLoop controlLoop; + + private List<Policy> policies; + + public ControlLoop getControlLoop() { + return controlLoop; + } + + public void setControlLoop(ControlLoop controlLoop) { + this.controlLoop = controlLoop; + } + + 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/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java new file mode 100644 index 000000000..bd49484bd --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +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; + } + + /** + * Converts to a result object. + * + * @param result input string + * @return result object + */ + 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; + } + + /** + * Check if the result really is a result. + * + * @param result string + * @param finalResult result object + * @return true if a result + */ + 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/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java new file mode 100644 index 000000000..07312db07 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +import java.io.Serializable; + +public class OperationsAccumulateParams implements Serializable { + + 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/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java new file mode 100644 index 000000000..af50eaa00 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java @@ -0,0 +1,337 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +import java.io.Serializable; +import java.util.Collections; +import java.util.Map; +import java.util.UUID; + +public class Policy implements Serializable { + private static final long serialVersionUID = 1L; + + 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 failureRetries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + private String failureTimeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + private String failureException = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + private String failureGuard = FinalResult.FINAL_FAILURE_GUARD.toString(); + + + public Policy() { + //Does Nothing Empty Constructor + } + + public Policy(String id) { + this.id = id; + } + + /** + * Constructor. + * + * @param name name + * @param actor actor + * @param recipe recipe + * @param payload payload + * @param target target + */ + 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); + } + } + + /** + * Constructor. + * + * @param name name + * @param actor actor + * @param recipe recipe + * @param payload payload + * @param target target + * @param retries retries + * @param timeout timeout + */ + 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; + } + + /** + * Constructor. + * + * @param policyParam provide parameter object + */ + public Policy(PolicyParam policyParam) { + this(policyParam.getName(), policyParam.getActor(), policyParam.getRecipe(), policyParam.getPayload(), + policyParam.getTarget(), policyParam.getRetries(), policyParam.getTimeout()); + this.id = policyParam.getId(); + this.description = policyParam.getDescription(); + } + + /** + * Constructor. + * + * @param policy copy object + */ + 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.failureException = policy.failureException; + this.failureGuard = policy.failureGuard; + this.failureRetries = policy.failureRetries; + this.failureTimeout = policy.failureTimeout; + } + + 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 failureRetries; + } + + public void setFailure_retries(String failureRetries) { + this.failureRetries = failureRetries; + } + + public String getFailure_timeout() { + return failureTimeout; + } + + public void setFailure_timeout(String failureTimeout) { + this.failureTimeout = failureTimeout; + } + + public String getFailure_exception() { + return failureException; + } + + public void setFailure_exception(String failureException) { + this.failureException = failureException; + } + + public String getFailure_guard() { + return failureGuard; + } + + public void setFailure_guard(String failureGuard) { + this.failureGuard = failureGuard; + } + + public boolean isValid() { + return id != null && name != null && actor != null && recipe != null && target != null; + } + + @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=" + failureRetries + + ", failure_timeout=" + failureTimeout + ", failure_exception=" + failureException + + ", failure_guard=" + failureGuard + "]"; + } + + @Override + public int hashCode() { + int result = 1; + result = addHashCodeForField(result, actor); + result = addHashCodeForField(result, description); + result = addHashCodeForField(result, failure); + result = addHashCodeForField(result, failureException); + result = addHashCodeForField(result, failureGuard); + result = addHashCodeForField(result, failureRetries); + result = addHashCodeForField(result, failureTimeout); + result = addHashCodeForField(result, id); + result = addHashCodeForField(result, name); + result = addHashCodeForField(result, payload); + result = addHashCodeForField(result, recipe); + result = addHashCodeForField(result, retry); + result = addHashCodeForField(result, success); + result = addHashCodeForField(result, target); + result = addHashCodeForField(result, operationsAccumulateParams); + result = addHashCodeForField(result, timeout); + return result; + } + + private int addHashCodeForField(int hashCode, Object field) { + final int prime = 31; + return prime * hashCode + ((field == null) ? 0 : field.hashCode()); + } + + @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; + return equalsMayBeNull(actor, other.actor) + && equalsMayBeNull(description, other.description) + && equalsMayBeNull(failure, other.failure) + && equalsMayBeNull(failureException, other.failureException) + && equalsMayBeNull(failureGuard, other.failureGuard) + && equalsMayBeNull(failureRetries, other.failureRetries) + && equalsMayBeNull(id, other.id) + && equalsMayBeNull(name, other.name) + && equalsMayBeNull(payload, other.payload) + && equalsMayBeNull(recipe, other.recipe) + && equalsMayBeNull(retry, other.retry) + && equalsMayBeNull(success, other.success) + && equalsMayBeNull(operationsAccumulateParams, other.operationsAccumulateParams) + && equalsMayBeNull(target, other.target) + && equalsMayBeNull(timeout, other.timeout); + } + + private boolean equalsMayBeNull(final Object obj1, final Object obj2) { + if ( obj1 == null ) { + return obj2 == null; + } + return obj1.equals(obj2); + } +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyParam.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyParam.java new file mode 100644 index 000000000..ab4e7f895 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyParam.java @@ -0,0 +1,133 @@ +/* + * ============LICENSE_START======================================================= + * policy-endpoints + * ================================================================================ + * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +import java.util.Map; + +public class PolicyParam { + private String id; + private String name; + private String description; + private String actor; + private Map<String, String> payload; + private Target target; + private String recipe; + private Integer retries; + private Integer timeout; + + public static PolicyParamBuilder builder() { + return new PolicyParamBuilder(); + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public String getActor() { + return actor; + } + + public Map<String, String> getPayload() { + return payload; + } + + public Target getTarget() { + return target; + } + + public String getRecipe() { + return recipe; + } + + public Integer getRetries() { + return retries; + } + + public Integer getTimeout() { + return timeout; + } + + public static class PolicyParamBuilder { + + PolicyParam policyParm = new PolicyParam(); + + private PolicyParamBuilder() { + } + + public PolicyParam build() { + return policyParm; + } + + public PolicyParamBuilder id(String id) { + policyParm.id = id; + return this; + } + + public PolicyParamBuilder name(String name) { + policyParm.name = name; + return this; + } + + public PolicyParamBuilder description(String description) { + policyParm.description = description; + return this; + } + + public PolicyParamBuilder actor(String actor) { + policyParm.actor = actor; + return this; + } + + public PolicyParamBuilder payload(Map<String, String> payload) { + policyParm.payload = payload; + return this; + } + + public PolicyParamBuilder target(Target target) { + policyParm.target = target; + return this; + } + + public PolicyParamBuilder recipe(String recipe) { + policyParm.recipe = recipe; + return this; + } + + public PolicyParamBuilder retries(Integer retries) { + policyParm.retries = retries; + return this; + } + + public PolicyParamBuilder timeout(Integer timeout) { + policyParm.timeout = timeout; + return this; + } + } +}
\ No newline at end of file diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java new file mode 100644 index 000000000..80a68248a --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +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; + } + + @Override + public String toString() { + return this.result; + } + + /** + * Convert to a result. + * + * @param result result string + * @return Result object + */ + 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/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java new file mode 100644 index 000000000..6e7a8218a --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +import java.io.Serializable; + +public class Target implements Serializable { + + private static final long serialVersionUID = 2180988443264988319L; + + private String resourceId; + private TargetType type; + + public Target() { + //Does Nothing Empty Constructor + } + + 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; + } + + 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; + } + + @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/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java new file mode 100644 index 000000000..7e47f80d8 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +public enum TargetType { + VM("VM"), + PNF("PNF"), + VFC("VFC"), + VNF("VNF") + ; + + private String target; + + private TargetType(String targetType) { + this.target = targetType; + } + + @Override + public String toString() { + return this.target; + } + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/BuilderException.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/BuilderException.java new file mode 100644 index 000000000..3d086d00f --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/BuilderException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.builder; + +public class BuilderException extends Exception { + + private static final long serialVersionUID = 610064813684337895L; + + public BuilderException(String string) { + super(string); + } + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java new file mode 100644 index 000000000..9c0188c1f --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java @@ -0,0 +1,315 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.builder; + +import org.onap.policy.aai.Pnf; +import org.onap.policy.controlloop.policy.ControlLoop; +import org.onap.policy.controlloop.policy.OperationsAccumulateParams; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyParam; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.policy.builder.impl.ControlLoopPolicyBuilderImpl; +import org.onap.policy.sdc.Resource; +import org.onap.policy.sdc.Service; + +public interface ControlLoopPolicyBuilder { + + /** + * Adds one or more services to the ControlLoop. + * + * @param services service to add + * @return builder object + * @throws BuilderException builder exception + */ + public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException; + + /** + * Remove service. + * + * @param services to remove + * @return builder object + * @throws BuilderException builder exception + */ + public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException; + + /** + * Remove all the services. + * + * @return builder object + * @throws BuilderException builder exception + */ + public ControlLoopPolicyBuilder removeAllServices() throws BuilderException; + + /** + * Adds one or more resources to the ControlLoop. + * + * @return builder object + * @throws BuilderException builder exception + */ + public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException; + + /** + * Remove the resources. + * + * @param resources resources to be removed + * @return object + * @throws BuilderException builder exception + */ + public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException; + + /** + * Remove all resources. + * + * @return object + * @throws BuilderException builder exception + */ + public ControlLoopPolicyBuilder removeAllResources() throws BuilderException; + + /** + * Set the PNF. + * + * @param pnf input pnf + * @return builder object + * @throws BuilderException builder exception + */ + public ControlLoopPolicyBuilder setPNF(Pnf pnf) throws BuilderException; + + /** + * Remove PNF. + * + * @return the object + * @throws BuilderException builder exception + */ + public ControlLoopPolicyBuilder removePNF() throws BuilderException; + + /** + * Set the abatement. + * + * @param abatement whether abatement is possible + * @return object + * @throws BuilderException builder exception + */ + 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 timeout value + * @return control loop policy builder + * @throws BuilderException builder exception + */ + 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 policy Policy parameters object + * @return Policy object + * @throws BuilderException builder exception + */ + public Policy setTriggerPolicy(PolicyParam policy) throws BuilderException; + + /** + * Changes the trigger policy to point to another existing Policy. + * + * @param id the id + * @return ControlLoop object + * @throws BuilderException build exception + */ + public ControlLoop setExistingTriggerPolicy(String id) throws BuilderException; + + /** + * Is an open loop. + * + * @return true or false + */ + public boolean isOpenLoop(); + + /** + * Get the trigger policy. + * + * @return the policy object + * @throws BuilderException if there is a builder exception + */ + 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 policyParam policy parameters object + * @param results results + * @return Policy that was set + * @throws BuilderException builder exception + */ + public Policy setPolicyForPolicyResult(PolicyParam policyParam, PolicyResult... results) + throws BuilderException; + + + /** + * Sets the policy result(s) to an existing Operational Policy. + * + * @param policyResultId result ID + * @param policyId id + * @param results results + * @return Policy that was set + * @throws BuilderException builder exception + */ + 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 id for the policy + * @return true if removed else false + * @throws BuilderException builder exception + */ + public boolean removePolicy(String policyID) throws BuilderException; + + /** + * Resets a policy's results to defualt FINAL_* codes. + * + * @return Policy object + * @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 Policy builder object + */ + 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 + */ + public static ControlLoopPolicyBuilder buildControlLoop(String controlLoopName, Integer timeout) { + 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 builder exception + */ + public static ControlLoopPolicyBuilder buildControlLoop(String controlLoopName, Integer timeout, + Resource resource, Service... services) throws BuilderException { + return new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, resource, services); + } + + /** + * Build the control loop. + * + * @param controlLoopName control loop id + * @param timeout timeout + * @param service service + * @param resources resources + * @return builder object + * @throws BuilderException builder exception + */ + public static ControlLoopPolicyBuilder buildControlLoop(String controlLoopName, Integer timeout, + Service service, Resource... resources) throws BuilderException { + return new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, service, resources); + } + + /** + * Build control 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. + * @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 builder exception + */ + public static ControlLoopPolicyBuilder buildControlLoop(String controlLoopName, Integer timeout, Pnf pnf) + throws BuilderException { + return new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, pnf); + } + } + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Message.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Message.java new file mode 100644 index 000000000..4e34a777a --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Message.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.builder; + +public interface Message { + + public String getMessage(); + + public MessageLevel getLevel(); + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java new file mode 100644 index 000000000..cca9e2c0a --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.builder; + +public enum MessageLevel { + INFO, + WARNING, + ERROR, + EXCEPTION; +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Results.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Results.java new file mode 100644 index 000000000..37f619b65 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Results.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.builder; + +import java.util.List; + +public interface Results { + + public List<Message> getMessages(); + + public String getSpecification(); + + public boolean isValid(); + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java new file mode 100644 index 000000000..ed6a54c1e --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java @@ -0,0 +1,544 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.builder.impl; + +import com.google.common.base.Strings; +import java.util.LinkedList; +import java.util.UUID; + +import org.onap.policy.aai.Pnf; +import org.onap.policy.controlloop.compiler.CompilerException; +import org.onap.policy.controlloop.compiler.ControlLoopCompiler; +import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback; +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.OperationsAccumulateParams; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyParam; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder; +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 final String UNKNOWN_POLICY = "Unknown policy "; + private static Logger logger = LoggerFactory.getLogger(ControlLoopPolicyBuilderImpl.class.getName()); + private ControlLoopPolicy controlLoopPolicy; + + /** + * Constructor. + * + * @param controlLoopName control loop id + * @param timeout timeout value + */ + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) { + controlLoopPolicy = new ControlLoopPolicy(); + ControlLoop controlLoop = new ControlLoop(); + controlLoop.setControlLoopName(controlLoopName); + controlLoop.setTimeout(timeout); + controlLoopPolicy.setControlLoop(controlLoop); + } + + /** + * Constructor. + * + * @param controlLoopName control loop id + * @param timeout timeout value + * @param resource resource + * @param services services + * @throws BuilderException builder exception + */ + 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); + } + + /** + * Constructor. + * + * @param controlLoopName control loop id + * @param timeout timeout + * @param service service + * @param resources resources + * @throws BuilderException builder exception + */ + 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 { + controlLoopPolicy.getControlLoop().setPnf(null); + return this; + } + + @Override + public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException { + for (Service service : services) { + if (service == null) { + throw new BuilderException("Service must not be null"); + } + if (service.getServiceUUID() == null && Strings.isNullOrEmpty(service.getServiceName())) { + throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); + } + if (controlLoopPolicy.getControlLoop().getServices() == null) { + controlLoopPolicy.getControlLoop().setServices(new LinkedList<>()); + } + controlLoopPolicy.getControlLoop().getServices().add(service); + } + return this; + } + + @Override + public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException { + if (controlLoopPolicy.getControlLoop().getServices() == null) { + throw new BuilderException("No existing services to remove"); + } + for (Service service : services) { + if (service == null) { + throw new BuilderException("Service must not be null"); + } + if (service.getServiceUUID() == null && Strings.isNullOrEmpty(service.getServiceName())) { + throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); + } + boolean removed = controlLoopPolicy.getControlLoop().getServices().remove(service); + if (!removed) { + throw new BuilderException("Unknown service " + service.getServiceName()); + } + } + return this; + } + + @Override + public ControlLoopPolicyBuilder removeAllServices() throws BuilderException { + controlLoopPolicy.getControlLoop().getServices().clear(); + return this; + } + + + @Override + public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException { + for (Resource resource : resources) { + if (resource == null) { + throw new BuilderException("Resource must not be null"); + } + if (resource.getResourceUuid() == null && Strings.isNullOrEmpty(resource.getResourceName())) { + throw new BuilderException("Invalid resource - need either resourceUUID or resourceName"); + } + if (controlLoopPolicy.getControlLoop().getResources() == null) { + controlLoopPolicy.getControlLoop().setResources(new LinkedList<>()); + } + controlLoopPolicy.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.getPnfName() == null && pnf.getPnfType() == null) { + throw new BuilderException("Invalid PNF - need either pnfName or pnfType"); + } + controlLoopPolicy.getControlLoop().setPnf(pnf); + return this; + } + + @Override + public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException { + if (abatement == null) { + throw new BuilderException("abatement must not be null"); + } + controlLoopPolicy.getControlLoop().setAbatement(abatement); + return this; + } + + @Override + public ControlLoopPolicyBuilder setTimeout(Integer timeout) { + controlLoopPolicy.getControlLoop().setTimeout(timeout); + return this; + } + + @Override + public Policy setTriggerPolicy(PolicyParam policyParam) + throws BuilderException { + + Policy trigger = new Policy(policyParam); + + controlLoopPolicy.getControlLoop().setTrigger_policy(trigger.getId()); + + this.addNewPolicy(trigger); + // + // Return a copy of the policy + // + return new Policy(trigger); + } + + @Override + public ControlLoop setExistingTriggerPolicy(String id) throws BuilderException { + if (id == null) { + throw new BuilderException("Id must not be null"); + } + Policy trigger = this.findPolicy(id); + if (trigger == null) { + throw new BuilderException(UNKNOWN_POLICY + id); + } else { + this.controlLoopPolicy.getControlLoop().setTrigger_policy(id); + } + return new ControlLoop(this.controlLoopPolicy.getControlLoop()); + } + + @Override + public Policy setPolicyForPolicyResult(PolicyParam policyParam, PolicyResult... results) + throws BuilderException { + // + // Find the existing policy + // + Policy existingPolicy = this.findPolicy(policyParam.getId()); + if (existingPolicy == null) { + throw new BuilderException(UNKNOWN_POLICY + policyParam.getId()); + } + // + // Create the new Policy + // + Policy newPolicy = new Policy( + PolicyParam.builder().id(UUID.randomUUID().toString()) + .name(policyParam.getName()) + .description(policyParam.getDescription()) + .actor(policyParam.getActor()) + .payload(policyParam.getPayload()) + .target(policyParam.getTarget()) + .recipe(policyParam.getRecipe()) + .retries(policyParam.getRetries()) + .timeout(policyParam.getTimeout()) + .build()); + // + // 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.controlLoopPolicy.getPolicies().add(newPolicy); + // + // Return a policy to them + // + return new Policy(newPolicy); + } + + @Override + public Policy setPolicyForPolicyResult(String policyResultId, String policyId, PolicyResult... results) + throws BuilderException { + // + // Find the existing policy + // + Policy existingPolicy = this.findPolicy(policyId); + if (existingPolicy == null) { + throw new BuilderException(policyId + " does not exist"); + } + if (this.findPolicy(policyResultId) == null) { + throw new BuilderException("Operational policy " + policyResultId + " does not exist"); + } + // + // Connect the results + // + for (PolicyResult result : results) { + switch (result) { + case FAILURE: + existingPolicy.setFailure(policyResultId); + break; + case FAILURE_EXCEPTION: + existingPolicy.setFailure_exception(policyResultId); + break; + case FAILURE_RETRIES: + existingPolicy.setFailure_retries(policyResultId); + break; + case FAILURE_TIMEOUT: + existingPolicy.setFailure_timeout(policyResultId); + break; + case FAILURE_GUARD: + existingPolicy.setFailure_guard(policyResultId); + break; + case SUCCESS: + existingPolicy.setSuccess(policyResultId); + break; + default: + throw new BuilderException("Invalid PolicyResult " + result); + } + } + return new Policy(this.findPolicy(policyResultId)); + } + + 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 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(controlLoopPolicy); + // + // This is our callback class for our compiler + // + BuilderCompilerCallback callback = new BuilderCompilerCallback(); + // + // Compile it + // + try { + ControlLoopCompiler.compile(controlLoopPolicy, 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.controlLoopPolicy.getPolicies() == null) { + this.controlLoopPolicy.setPolicies(new LinkedList<>()); + } + this.controlLoopPolicy.getPolicies().add(policy); + } + + private Policy findPolicy(String id) { + if (this.controlLoopPolicy.getPolicies() != null) { + for (Policy policy : this.controlLoopPolicy.getPolicies()) { + if (policy.getId().equals(id)) { + return policy; + } + } + } + return null; + } + + @Override + public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException { + if (controlLoopPolicy.getControlLoop().getResources() == null) { + throw new BuilderException("No existing resources to remove"); + } + for (Resource resource : resources) { + if (resource == null) { + throw new BuilderException("Resource must not be null"); + } + if (resource.getResourceUuid() == null && Strings.isNullOrEmpty(resource.getResourceName())) { + throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName"); + } + boolean removed = controlLoopPolicy.getControlLoop().getResources().remove(resource); + if (!removed) { + throw new BuilderException("Unknown resource " + resource.getResourceName()); + } + } + return this; + } + + @Override + public ControlLoopPolicyBuilder removeAllResources() throws BuilderException { + controlLoopPolicy.getControlLoop().getResources().clear(); + return this; + } + + @Override + public Integer calculateTimeout() { + int sum = 0; + for (Policy policy : this.controlLoopPolicy.getPolicies()) { + sum += policy.getTimeout().intValue(); + } + return Integer.valueOf(sum); + } + + @Override + public boolean isOpenLoop() { + return this.controlLoopPolicy.getControlLoop().getTrigger_policy() + .equals(FinalResult.FINAL_OPENLOOP.toString()); + } + + @Override + public Policy getTriggerPolicy() throws BuilderException { + if (this.controlLoopPolicy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) { + return null; + } else { + return new Policy(this.findPolicy(this.controlLoopPolicy.getControlLoop().getTrigger_policy())); + } + } + + @Override + public ControlLoop getControlLoop() { + return new ControlLoop(this.controlLoopPolicy.getControlLoop()); + } + + @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.controlLoopPolicy.getControlLoop().getTrigger_policy().equals(policyId)) { + this.controlLoopPolicy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); + } else { + updateChainedPoliciesForPolicyRemoval(policyId); + } + // + // remove the policy + // + return this.controlLoopPolicy.getPolicies().remove(existingPolicy); + } + + private void updateChainedPoliciesForPolicyRemoval(String idOfPolicyBeingRemoved) { + for (Policy policy : this.controlLoopPolicy.getPolicies()) { + final int index = this.controlLoopPolicy.getPolicies().indexOf(policy); + if (policy.getSuccess().equals(idOfPolicyBeingRemoved)) { + policy.setSuccess(FinalResult.FINAL_SUCCESS.toString()); + } + if (policy.getFailure().equals(idOfPolicyBeingRemoved)) { + policy.setFailure(FinalResult.FINAL_FAILURE.toString()); + } + if (policy.getFailure_retries().equals(idOfPolicyBeingRemoved)) { + policy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString()); + } + if (policy.getFailure_timeout().equals(idOfPolicyBeingRemoved)) { + policy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString()); + } + if (policy.getFailure_exception().equals(idOfPolicyBeingRemoved)) { + policy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString()); + } + if (policy.getFailure_guard().equals(idOfPolicyBeingRemoved)) { + policy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString()); + } + this.controlLoopPolicy.getPolicies().set(index, policy); + } + } + + @Override + public Policy resetPolicyResults(String policyId) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyId); + if (existingPolicy == null) { + throw new BuilderException(UNKNOWN_POLICY + policyId); + } + // + // reset policy results + // + 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() { + // + // Remove all existing operational policies + // + this.controlLoopPolicy.getPolicies().clear(); + // + // Revert controlLoop back to an open loop + // + this.controlLoopPolicy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); + return this; + } + + @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.setOperationsAccumulateParams(operationsAccumulateParams); + return new Policy(existingPolicy); + } + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/MessageImpl.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/MessageImpl.java new file mode 100644 index 000000000..1a03f6d7a --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/MessageImpl.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.builder.impl; + +import org.onap.policy.controlloop.policy.builder.Message; +import org.onap.policy.controlloop.policy.builder.MessageLevel; + +public class MessageImpl implements Message { + + private String message; + private MessageLevel level; + + public MessageImpl(String message, MessageLevel level) { + this.message = message; + this.level = level; + } + + @Override + public String getMessage() { + return message; + } + + @Override + public MessageLevel getLevel() { + return level; + } + +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java new file mode 100644 index 000000000..561f55170 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.builder.impl; + +import java.util.LinkedList; +import java.util.List; + +import org.onap.policy.controlloop.policy.builder.Message; +import org.onap.policy.controlloop.policy.builder.Results; + +public class ResultsImpl implements Results { + + private String specification; + private List<Message> messages = new LinkedList<>(); + + @Override + public List<Message> getMessages() { + return messages; + } + + @Override + public String getSpecification() { + return specification; + } + + @Override + public boolean isValid() { + return (this.specification != null); + } + + public void addMessage(Message message) { + this.messages.add(message); + } + + public void setSpecification(String spec) { + this.specification = spec; + } +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java new file mode 100644 index 000000000..b16ecbb55 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java @@ -0,0 +1,256 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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 freqLimitPerTarget; + private Map<String,String> timeWindow; + private Map<String, String> activeTimeRange; + private Integer minVnfCount; + private Integer maxVnfCount; + + private List<String> blacklist; + + public Constraint() { + // Do Nothing empty constructor. + } + + /** + * Constructor. + * + * @param freqLimitPerTarget frequency limit + * @param timeWindow time window + */ + public Constraint(Integer freqLimitPerTarget, Map<String, String> timeWindow) { + this.freqLimitPerTarget = freqLimitPerTarget; + if (timeWindow != null) { + this.timeWindow = Collections.unmodifiableMap(timeWindow); + } + } + + /** + * Constructor. + * + * @param minVnfCount minimum VNF count + * @param maxVnfCount maximum VNF count + * @param activeTimeRange active time range + */ + public Constraint(Integer minVnfCount, Integer maxVnfCount, Map<String, String> activeTimeRange) { + this.minVnfCount = minVnfCount; + this.maxVnfCount = maxVnfCount; + + if (activeTimeRange != null) { + this.activeTimeRange = Collections.unmodifiableMap(activeTimeRange); + } + } + + public Constraint(List<String> blacklist) { + this.blacklist = new LinkedList<>(blacklist); + } + + /** + * Constructor. + * + * @param freqLimitPerTarget frequency limit + * @param timeWindow time window + * @param blacklist blacklist + */ + public Constraint(Integer freqLimitPerTarget, Map<String, String> timeWindow, List<String> blacklist) { + this.freqLimitPerTarget = freqLimitPerTarget; + this.timeWindow = Collections.unmodifiableMap(timeWindow); + this.blacklist = new LinkedList<>(blacklist); + } + + /** + * Constructor. + * + * @param freqLimitPerTarget frequency limit + * @param timeWindow time window + * @param activeTimeRange active time range + */ + public Constraint(Integer freqLimitPerTarget, Map<String, String> timeWindow, Map<String, String> activeTimeRange) { + this(freqLimitPerTarget, timeWindow); + if (activeTimeRange != null) { + this.activeTimeRange = Collections.unmodifiableMap(activeTimeRange); + } + } + + /** + * Constructor. + * + * @param freqLimitPerTarget frequency limit + * @param timeWindow the time window + * @param activeTimeRange active time range + * @param blacklist incoming blacklist + */ + public Constraint(Integer freqLimitPerTarget, Map<String, String> timeWindow, Map<String, String> activeTimeRange, + List<String> blacklist) { + this(freqLimitPerTarget, timeWindow); + if (activeTimeRange != null) { + this.activeTimeRange = Collections.unmodifiableMap(activeTimeRange); + } + if (blacklist != null) { + this.blacklist = new LinkedList<>(blacklist); + } + } + + /** + * Constructor. + * + * @param constraint objec to copy + */ + public Constraint(Constraint constraint) { + this.freqLimitPerTarget = constraint.freqLimitPerTarget; + this.timeWindow = constraint.timeWindow; + if (constraint.activeTimeRange != null) { + this.activeTimeRange = Collections.unmodifiableMap(constraint.activeTimeRange); + } + this.blacklist = new LinkedList<>(constraint.blacklist); + } + + public Integer getFreq_limit_per_target() { + return freqLimitPerTarget; + } + + + public void setFreq_limit_per_target(Integer freqLimitPerTarget) { + this.freqLimitPerTarget = freqLimitPerTarget; + } + + + public Map<String, String> getTime_window() { + return timeWindow; + } + + + public void setTime_window(Map<String, String> timeWindow) { + this.timeWindow = timeWindow; + } + + + public Map<String, String> getActive_time_range() { + return activeTimeRange; + } + + + public void setActive_time_range(Map<String, String> activeTimeRange) { + this.activeTimeRange = activeTimeRange; + } + + + public List<String> getBlacklist() { + return blacklist; + } + + + public void setBlacklist(List<String> blacklist) { + this.blacklist = blacklist; + } + + + public Integer getMinVnfCount() { + return minVnfCount; + } + + + public void setMinVnfCount(Integer minVnfCount) { + this.minVnfCount = minVnfCount; + } + + + public Integer getMaxVnfCount() { + return maxVnfCount; + } + + + public void setMaxVnfCount(Integer maxVnfCount) { + this.maxVnfCount = maxVnfCount; + } + + /** + * Check if these constraint values are valid. + * + * @return true if valid + */ + public boolean isValid() { + // + // Sonar likes these statements combined as well as not use + // boolean literals. + // + // If the freqLimitPerTarget is null AND the timeWindow is NOT null + // OR + // timeWindow is null AND the freqLimitPerTarget is NOT null + // + // then we want to return false (hence the preceding !) + // + return ! ((freqLimitPerTarget == null && timeWindow != null) + || (timeWindow == null && freqLimitPerTarget != null)); + } + + @Override + public String toString() { + return "Constraint [freq_limit_per_target=" + freqLimitPerTarget + ", time_window=" + + timeWindow + ", active_time_range=" + activeTimeRange + ", blacklist=" + blacklist + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((freqLimitPerTarget == null) ? 0 : freqLimitPerTarget.hashCode()); + result = prime * result + ((timeWindow == null) ? 0 : timeWindow.hashCode()); + result = prime * result + ((activeTimeRange == null) ? 0 : activeTimeRange.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; + return equalsMayBeNull(freqLimitPerTarget, other.freqLimitPerTarget) + && equalsMayBeNull(timeWindow, other.timeWindow) + && equalsMayBeNull(activeTimeRange, other.activeTimeRange) + && equalsMayBeNull(blacklist, other.blacklist); + } + + private boolean equalsMayBeNull(final Object obj1, final Object obj2) { + if (obj1 == null) { + return obj2 == null; + } + return obj1.equals(obj2); + } +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java new file mode 100644 index 000000000..b2d243c4e --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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 ControlLoopGuard(ControlLoopGuard clGuard) { + this.guard = new Guard(); + this.guards = new LinkedList<>(clGuard.guards); + } + + 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; + } + + @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/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java new file mode 100644 index 000000000..163cf0643 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java new file mode 100644 index 000000000..4278b81e5 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java @@ -0,0 +1,191 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; +import java.util.UUID; + +public class GuardPolicy { + + private String id = UUID.randomUUID().toString(); + private String name; + private String description; + private MatchParameters matchParameters; + private LinkedList<Constraint> limitConstraints; + + public GuardPolicy() { + //Do Nothing Empty Constructor. + } + + public GuardPolicy(String id) { + this.id = id; + } + + public GuardPolicy(String name, MatchParameters matchParameters) { + this.name = name; + this.matchParameters = matchParameters; + } + + /** + * Constructor. + * + * @param id id + * @param name name + * @param description description + * @param matchParameters match parameters + */ + public GuardPolicy(String id, String name, String description, MatchParameters matchParameters) { + this(name, matchParameters); + this.id = id; + this.description = description; + } + + /** + * Constructor. + * + * @param name name + * @param matchParameters match parameters + * @param limitConstraints limit constraints + */ + public GuardPolicy(String name, MatchParameters matchParameters, List<Constraint> limitConstraints) { + this(name, matchParameters); + if (limitConstraints != null) { + this.limitConstraints = (LinkedList<Constraint>) 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; + } + + /** + * Constructor. + * + * @param policy copy object + */ + public GuardPolicy(GuardPolicy policy) { + this.id = policy.id; + this.name = policy.name; + this.description = policy.description; + this.matchParameters = new MatchParameters(policy.matchParameters); + if (policy.limitConstraints != null) { + this.limitConstraints = policy.limitConstraints; + } + } + + 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 matchParameters; + } + + public void setMatch_parameters(MatchParameters matchParameters) { + this.matchParameters = matchParameters; + } + + public LinkedList<Constraint> getLimit_constraints() { + return limitConstraints; + } + + public void setLimit_constraints(LinkedList<Constraint> limitConstraints) { + this.limitConstraints = limitConstraints; + } + + public boolean isValid() { + return (id == null || name == null) ? false : true; + } + + @Override + public String toString() { + return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", match_parameters=" + + matchParameters + ", limitConstraints=" + limitConstraints + "]"; + } + + @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 + ((limitConstraints == null) ? 0 : limitConstraints.hashCode()); + result = prime * result + ((matchParameters == null) ? 0 : matchParameters.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; + return equalsMayBeNull(description, other.description) + && equalsMayBeNull(id, other.id) + && equalsMayBeNull(name, other.name) + && equalsMayBeNull(limitConstraints, other.limitConstraints) + && equalsMayBeNull(matchParameters, other.matchParameters); + } + + private boolean equalsMayBeNull(final Object obj1, final Object obj2) { + if ( obj1 == null ) { + return obj2 == null; + } + return obj1.equals(obj2); + } +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java new file mode 100644 index 000000000..e0457e797 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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 MatchParameters(String actor, String recipe) { + this.actor = actor; + this.recipe = recipe; + } + + /** + * Constructor. + * + * @param actor actor + * @param recipe recipe + * @param targets targets + */ + 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; + } + + /** + * Constructor. + * + * @param matchParameters match parameters + */ + 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); + } + } + + 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; + } + + @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; + + return equalsMayBeNull(actor, other.actor) + && equalsMayBeNull(controlLoopName, other.controlLoopName) + && equalsMayBeNull(recipe, other.recipe) + && equalsMayBeNull(targets, other.targets); + } + + private boolean equalsMayBeNull(final Object obj1, final Object obj2) { + if (obj1 == null) { + return obj2 == null; + } + return obj1.equals(obj2); + } +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java new file mode 100644 index 000000000..a6c92ee1a --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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 policies to add + * @return builder object + * @throws BuilderException builder exception + */ + public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException; + + /** + * Removes one or more guard policies from the Control Loop Guard. + * + * @param policies policies to add + * @return builder object + * @throws BuilderException builder exception + */ + public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException; + + /** + * Removes all guard policies from the Control Loop Guard. + * + * @return builder object + * @throws BuilderException builder exception + */ + public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException; + + /** + * Adds one or more time limit constraints to the guard policy. + * + * @param id (guard policy id) + * @param constraints the constraints to add + * @return builder object + * @throws BuilderException builder exception + */ + 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 constraints to remove + * @return builder object + * @throws BuilderException builder exception + */ + public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException; + + /** + * Removes all time limit constraints from the guard policy. + * + * @param id (guard policy id) + * @return builder object + * @throws BuilderException builder exception + */ + 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. + } + /** + * Build the control loop guard. + * + * @param guard the guard + * @return ControlLoopGuardBuilder object + */ + + public static ControlLoopGuardBuilder buildControlLoopGuard(Guard guard) { + + return new ControlLoopGuardBuilderImpl(guard); + + } + } +} diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java new file mode 100644 index 000000000..a84783bc0 --- /dev/null +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java @@ -0,0 +1,249 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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 final String NO_EXISTING_GUARD_POLICY_MATCHING_THE_ID = "No existing guard policy matching the id: "; + private static final String THE_ID_OF_TARGET_GUARD_POLICY_MUST_NOT_BE_NULL = + "The id of target guard policy must not be null"; + 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("Build specification threw ", e); + callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); + } + // + // Save the spec + // + callback.results.setSpecification(dumpedYaml); + return callback.results; + } + +} |