2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2019 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.controlloop.compiler;
24 import com.google.common.collect.ImmutableList;
25 import com.google.common.collect.ImmutableMap;
27 import java.io.InputStream;
28 import java.io.Serializable;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import org.jgrapht.DirectedGraph;
36 import org.jgrapht.graph.ClassBasedEdgeFactory;
37 import org.jgrapht.graph.DefaultEdge;
38 import org.jgrapht.graph.DirectedMultigraph;
39 import org.onap.policy.controlloop.policy.ControlLoop;
40 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
41 import org.onap.policy.controlloop.policy.FinalResult;
42 import org.onap.policy.controlloop.policy.Policy;
43 import org.onap.policy.controlloop.policy.PolicyResult;
44 import org.onap.policy.controlloop.policy.TargetType;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.yaml.snakeyaml.Yaml;
48 import org.yaml.snakeyaml.constructor.Constructor;
51 public class ControlLoopCompiler implements Serializable {
52 private static final String OPERATION_POLICY = "Operation Policy ";
53 private static final long serialVersionUID = 1L;
54 private static final Logger LOGGER = LoggerFactory.getLogger(ControlLoopCompiler.class.getName());
57 * Compiles the policy from an object.
59 public static ControlLoopPolicy compile(ControlLoopPolicy policy,
60 ControlLoopCompilerCallback callback) throws CompilerException {
62 // Ensure the control loop is sane
64 validateControlLoop(policy.getControlLoop(), callback);
66 // Validate the policies
68 validatePolicies(policy, callback);
74 * Compiles the policy from an input stream.
76 * @param yamlSpecification the yaml input stream
77 * @param callback method to callback during compilation
78 * @return Control Loop object
79 * @throws CompilerException throws any compile exception found
81 public static ControlLoopPolicy compile(InputStream yamlSpecification,
82 ControlLoopCompilerCallback callback) throws CompilerException {
83 Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
84 Object obj = yaml.load(yamlSpecification);
86 throw new CompilerException("Could not parse yaml specification.");
88 if (! (obj instanceof ControlLoopPolicy)) {
89 throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object");
91 return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback);
94 private static void validateControlLoop(ControlLoop controlLoop,
95 ControlLoopCompilerCallback callback) throws CompilerException {
96 if (controlLoop == null && callback != null) {
97 callback.onError("controlLoop cannot be null");
99 if (controlLoop != null) {
100 if ((controlLoop.getControlLoopName() == null || controlLoop.getControlLoopName().length() < 1)
101 && callback != null) {
102 callback.onError("Missing controlLoopName");
104 if ((!controlLoop.getVersion().contentEquals(ControlLoop.getCompilerVersion())) && callback != null) {
105 callback.onError("Unsupported version for this compiler");
107 if (controlLoop.getTrigger_policy() == null || controlLoop.getTrigger_policy().length() < 1) {
108 throw new CompilerException("trigger_policy is not valid");
113 private static void validatePolicies(ControlLoopPolicy policy,
114 ControlLoopCompilerCallback callback) throws CompilerException {
115 if (policy == null) {
116 throw new CompilerException("policy cannot be null");
118 if (policy.getPolicies() == null) {
119 callback.onWarning("controlLoop is an open loop.");
122 // For this version we can use a directed multigraph, in the future we may not be able to
124 DirectedGraph<NodeWrapper, LabeledEdge> graph =
125 new DirectedMultigraph<>(new ClassBasedEdgeFactory<NodeWrapper,
126 LabeledEdge>(LabeledEdge.class));
128 // Check to see if the trigger Event is for OpenLoop, we do so by
129 // attempting to create a FinalResult object from it. If its a policy id, this should
132 FinalResult triggerResult = FinalResult.toResult(policy.getControlLoop().getTrigger_policy());
133 TriggerNodeWrapper triggerNode;
135 // Did this turn into a FinalResult object?
137 if (triggerResult != null) {
138 validateOpenLoopPolicy(policy, triggerResult, callback);
142 validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(policy, callback);
143 triggerNode = new TriggerNodeWrapper(policy.getControlLoop().getControlLoopName());
146 // Add in the trigger node
148 graph.addVertex(triggerNode);
150 // Add in our Final Result nodes. All paths should end to these nodes.
152 FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS);
153 FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE);
154 FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT);
155 FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES);
156 FinalResultNodeWrapper finalFailureException =
157 new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION);
158 FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD);
159 graph.addVertex(finalSuccess);
160 graph.addVertex(finalFailure);
161 graph.addVertex(finalFailureTimeout);
162 graph.addVertex(finalFailureRetries);
163 graph.addVertex(finalFailureException);
164 graph.addVertex(finalFailureGuard);
166 // Work through the policies and add them in as nodes.
168 Map<Policy, PolicyNodeWrapper> mapNodes = addPoliciesAsNodes(policy, graph, triggerNode, callback);
170 // last sweep to connect remaining edges for policy results
172 for (Policy operPolicy : policy.getPolicies()) {
173 PolicyNodeWrapper node = mapNodes.get(operPolicy);
175 // Just ensure this has something
180 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getSuccess(), finalSuccess,
181 PolicyResult.SUCCESS, node);
182 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure(), finalFailure,
183 PolicyResult.FAILURE, node);
184 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_timeout(), finalFailureTimeout,
185 PolicyResult.FAILURE_TIMEOUT, node);
186 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_retries(), finalFailureRetries,
187 PolicyResult.FAILURE_RETRIES, node);
188 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_exception(), finalFailureException,
189 PolicyResult.FAILURE_EXCEPTION, node);
190 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_guard(), finalFailureGuard,
191 PolicyResult.FAILURE_GUARD, node);
193 validateNodesAndEdges(graph, callback);
197 private static void validateOpenLoopPolicy(ControlLoopPolicy policy, FinalResult triggerResult,
198 ControlLoopCompilerCallback callback) throws CompilerException {
200 // Ensure they didn't use some other FinalResult code
202 if (triggerResult != FinalResult.FINAL_OPENLOOP) {
203 throw new CompilerException("Unexpected Final Result for trigger_policy, should only be "
204 + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
207 // They really shouldn't have any policies attached.
209 if ((policy.getPolicies() != null || policy.getPolicies().isEmpty()) && callback != null ) {
210 callback.onWarning("Open Loop policy contains policies. The policies will never be invoked.");
214 private static void validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(ControlLoopPolicy policy,
215 ControlLoopCompilerCallback callback) throws CompilerException {
217 boolean triggerPolicyFound = false;
218 for (Policy operPolicy : policy.getPolicies()) {
219 sum += operPolicy.getTimeout().intValue();
220 if (policy.getControlLoop().getTrigger_policy().equals(operPolicy.getId())) {
221 triggerPolicyFound = true;
224 if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) {
225 callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts.");
228 if (!triggerPolicyFound) {
229 throw new CompilerException("Unexpected value for trigger_policy, should only be "
230 + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
234 private static Map<Policy, PolicyNodeWrapper> addPoliciesAsNodes(ControlLoopPolicy policy,
235 DirectedGraph<NodeWrapper, LabeledEdge> graph, TriggerNodeWrapper triggerNode,
236 ControlLoopCompilerCallback callback) {
237 Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<>();
238 for (Policy operPolicy : policy.getPolicies()) {
240 // Is it still ok to add?
242 if (!okToAdd(operPolicy, callback)) {
249 // Create wrapper policy node and save it into our map so we can
250 // easily retrieve it.
252 PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy);
253 mapNodes.put(operPolicy, node);
254 graph.addVertex(node);
256 // Is this the trigger policy?
258 if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) {
260 // Yes add an edge from our trigger event node to this policy
262 graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET")));
268 private static void addEdge(DirectedGraph<NodeWrapper, LabeledEdge> graph, Map<Policy, PolicyNodeWrapper> mapNodes,
269 String policyId, String connectedPolicy,
270 FinalResultNodeWrapper finalResultNodeWrapper,
271 PolicyResult policyResult, NodeWrapper node) throws CompilerException {
272 FinalResult finalResult = FinalResult.toResult(finalResultNodeWrapper.getId());
273 if (FinalResult.isResult(connectedPolicy, finalResult)) {
274 graph.addEdge(node, finalResultNodeWrapper, new LabeledEdge(node, finalResultNodeWrapper,
275 new FinalResultEdgeWrapper(finalResult)));
277 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, connectedPolicy);
278 if (toNode == null) {
279 throw new CompilerException(OPERATION_POLICY + policyId + " is connected to unknown policy "
282 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(policyResult)));
287 private static void validateNodesAndEdges(DirectedGraph<NodeWrapper, LabeledEdge> graph,
288 ControlLoopCompilerCallback callback) throws CompilerException {
289 for (NodeWrapper node : graph.vertexSet()) {
290 if (node instanceof TriggerNodeWrapper) {
291 validateTriggerNodeWrapper(graph, node);
292 } else if (node instanceof FinalResultNodeWrapper) {
293 validateFinalResultNodeWrapper(graph, node);
294 } else if (node instanceof PolicyNodeWrapper) {
295 validatePolicyNodeWrapper(graph, node, callback);
297 for (LabeledEdge edge : graph.outgoingEdgesOf(node)) {
298 LOGGER.info("{} invokes {} upon {}", edge.from.getId(), edge.to.getId(), edge.edge.getId());
303 private static void validateTriggerNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
304 NodeWrapper node) throws CompilerException {
305 if (LOGGER.isDebugEnabled()) {
306 LOGGER.info("Trigger Node {}", node);
308 if (graph.inDegreeOf(node) > 0 ) {
310 // Really should NEVER get here unless someone messed up the code above.
312 throw new CompilerException("No inputs to event trigger");
315 // Should always be 1, except in the future we may support multiple events
317 if (graph.outDegreeOf(node) > 1) {
318 throw new CompilerException("The event trigger should only go to ONE node");
322 private static void validateFinalResultNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
323 NodeWrapper node) throws CompilerException {
324 if (LOGGER.isDebugEnabled()) {
325 LOGGER.info("FinalResult Node {}", node);
328 // FinalResult nodes should NEVER have an out edge
330 if (graph.outDegreeOf(node) > 0) {
331 throw new CompilerException("FinalResult nodes should never have any out edges.");
335 private static void validatePolicyNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
336 NodeWrapper node, ControlLoopCompilerCallback callback) throws CompilerException {
337 if (LOGGER.isDebugEnabled()) {
338 LOGGER.info("Policy Node {}", node);
341 // All Policy Nodes should have the 5 out degrees defined.
343 if (graph.outDegreeOf(node) != 6) {
344 throw new CompilerException("Policy node should ALWAYS have 6 out degrees.");
347 // All Policy Nodes should have at least 1 in degrees
349 if (graph.inDegreeOf(node) == 0 && callback != null) {
350 callback.onWarning("Policy " + node.getId() + " is not reachable.");
354 private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) {
355 boolean isOk = isPolicyIdOk(operPolicy, callback);
356 if (! isActorOk(operPolicy, callback)) {
359 if (! isRecipeOk(operPolicy, callback)) {
362 if (! isTargetOk(operPolicy, callback) ) {
365 if (! arePolicyResultsOk(operPolicy, callback) ) {
371 private static boolean isPolicyIdOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
373 if (operPolicy.getId() == null || operPolicy.getId().length() < 1) {
374 if (callback != null) {
375 callback.onError("Operational Policy has an bad ID");
380 // Check if they decided to make the ID a result object
382 if (PolicyResult.toResult(operPolicy.getId()) != null) {
383 if (callback != null) {
384 callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId());
388 if (FinalResult.toResult(operPolicy.getId()) != null) {
389 if (callback != null) {
390 callback.onError("Policy id is set to a FinalResult " + operPolicy.getId());
398 private static boolean isActorOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
400 if (operPolicy.getActor() == null) {
401 if (callback != null) {
402 callback.onError("Policy actor is null");
407 // Construct a list for all valid actors
409 ImmutableList<String> actors = ImmutableList.of("APPC", "SDNC", "SDNR", "SO", "VFC");
411 if (operPolicy.getActor() != null && (!actors.contains(operPolicy.getActor())) ) {
412 if (callback != null) {
413 callback.onError("Policy actor is invalid");
420 private static boolean isRecipeOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
422 if (operPolicy.getRecipe() == null) {
423 if (callback != null) {
424 callback.onError("Policy recipe is null");
429 // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these)
431 ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>()
432 .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig"))
433 .put("SDNC", ImmutableList.of("Reroute"))
434 .put("SDNR", ImmutableList.of("ModifyConfig"))
435 .put("SO", ImmutableList.of("VF Module Create", "VF Module Delete"))
436 .put("VFC", ImmutableList.of("Restart"))
439 if (operPolicy.getRecipe() != null
440 && (!recipes.getOrDefault(operPolicy.getActor(),
441 Collections.emptyList()).contains(operPolicy.getRecipe()))) {
442 if (callback != null) {
443 callback.onError("Policy recipe is invalid");
450 private static boolean isTargetOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
452 if (operPolicy.getTarget() == null) {
453 if (callback != null) {
454 callback.onError("Policy target is null");
458 if (operPolicy.getTarget() != null
459 && operPolicy.getTarget().getType() != TargetType.VM
460 && operPolicy.getTarget().getType() != TargetType.VFC
461 && operPolicy.getTarget().getType() != TargetType.PNF) {
462 if (callback != null) {
463 callback.onError("Policy target is invalid");
470 private static boolean arePolicyResultsOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
472 // Check that policy results are connected to either default final * or another policy
474 boolean isOk = isSuccessPolicyResultOk(operPolicy, callback);
475 if (! isFailurePolicyResultOk(operPolicy, callback) ) {
478 if (! isFailureRetriesPolicyResultOk(operPolicy, callback) ) {
481 if (! isFailureTimeoutPolicyResultOk(operPolicy, callback) ) {
484 if (! isFailureExceptionPolicyResultOk(operPolicy, callback) ) {
487 if (! isFailureGuardPolicyResultOk(operPolicy, callback) ) {
493 private static boolean isSuccessPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
495 if (FinalResult.toResult(operPolicy.getSuccess()) != null
496 && !operPolicy.getSuccess().equals(FinalResult.FINAL_SUCCESS.toString())) {
497 if (callback != null) {
498 callback.onError("Policy success is neither another policy nor FINAL_SUCCESS");
505 private static boolean isFailurePolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
507 if (FinalResult.toResult(operPolicy.getFailure()) != null
508 && !operPolicy.getFailure().equals(FinalResult.FINAL_FAILURE.toString())) {
509 if (callback != null) {
510 callback.onError("Policy failure is neither another policy nor FINAL_FAILURE");
517 private static boolean isFailureRetriesPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
519 if (FinalResult.toResult(operPolicy.getFailure_retries()) != null
520 && !operPolicy.getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())) {
521 if (callback != null) {
522 callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES");
529 private static boolean isFailureTimeoutPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
531 if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null
532 && !operPolicy.getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())) {
533 if (callback != null) {
534 callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT");
541 private static boolean isFailureExceptionPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
543 if (FinalResult.toResult(operPolicy.getFailure_exception()) != null
544 && !operPolicy.getFailure_exception().equals(FinalResult.FINAL_FAILURE_EXCEPTION.toString())) {
545 if (callback != null) {
546 callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION");
553 private static boolean isFailureGuardPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
555 if (FinalResult.toResult(operPolicy.getFailure_guard()) != null
556 && !operPolicy.getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())) {
557 if (callback != null) {
558 callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD");
565 private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) {
566 for (Entry<Policy, PolicyNodeWrapper> entry : mapNodes.entrySet()) {
567 if (entry.getKey().getId().equals(id)) {
568 return entry.getValue();
575 private interface NodeWrapper extends Serializable {
576 public String getId();
579 private static class TriggerNodeWrapper implements NodeWrapper {
580 private static final long serialVersionUID = -187644087811478349L;
581 private String closedLoopControlName;
583 public TriggerNodeWrapper(String closedLoopControlName) {
584 this.closedLoopControlName = closedLoopControlName;
588 public String toString() {
589 return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]";
593 public String getId() {
594 return closedLoopControlName;
599 private static class FinalResultNodeWrapper implements NodeWrapper {
600 private static final long serialVersionUID = 8540008796302474613L;
601 private FinalResult result;
603 public FinalResultNodeWrapper(FinalResult result) {
604 this.result = result;
608 public String toString() {
609 return "FinalResultNodeWrapper [result=" + result + "]";
613 public String getId() {
614 return result.toString();
618 private static class PolicyNodeWrapper implements NodeWrapper {
619 private static final long serialVersionUID = 8170162175653823082L;
620 private transient Policy policy;
622 public PolicyNodeWrapper(Policy operPolicy) {
623 this.policy = operPolicy;
627 public String toString() {
628 return "PolicyNodeWrapper [policy=" + policy + "]";
632 public String getId() {
633 return policy.getId();
638 private interface EdgeWrapper extends Serializable {
639 public String getId();
643 private static class TriggerEdgeWrapper implements EdgeWrapper {
644 private static final long serialVersionUID = 2678151552623278863L;
645 private String trigger;
647 public TriggerEdgeWrapper(String trigger) {
648 this.trigger = trigger;
652 public String getId() {
657 public String toString() {
658 return "TriggerEdgeWrapper [trigger=" + trigger + "]";
663 private static class PolicyResultEdgeWrapper implements EdgeWrapper {
664 private static final long serialVersionUID = 6078569477021558310L;
665 private PolicyResult policyResult;
667 public PolicyResultEdgeWrapper(PolicyResult policyResult) {
669 this.policyResult = policyResult;
673 public String toString() {
674 return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]";
678 public String getId() {
679 return policyResult.toString();
685 private static class FinalResultEdgeWrapper implements EdgeWrapper {
686 private static final long serialVersionUID = -1486381946896779840L;
687 private FinalResult finalResult;
689 public FinalResultEdgeWrapper(FinalResult result) {
690 this.finalResult = result;
694 public String toString() {
695 return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]";
699 public String getId() {
700 return finalResult.toString();
705 private static class LabeledEdge extends DefaultEdge {
706 private static final long serialVersionUID = 579384429573385524L;
708 private NodeWrapper from;
709 private NodeWrapper to;
710 private EdgeWrapper edge;
712 public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) {
718 @SuppressWarnings("unused")
719 public NodeWrapper from() {
723 @SuppressWarnings("unused")
724 public NodeWrapper to() {
728 @SuppressWarnings("unused")
729 public EdgeWrapper edge() {
734 public String toString() {
735 return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]";