2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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 java.io.InputStream;
25 import java.io.Serializable;
26 import java.util.HashMap;
28 import java.util.Map.Entry;
29 import org.apache.commons.lang3.StringUtils;
30 import org.jgrapht.Graph;
31 import org.jgrapht.graph.ClassBasedEdgeFactory;
32 import org.jgrapht.graph.DefaultEdge;
33 import org.jgrapht.graph.DirectedMultigraph;
34 import org.onap.policy.controlloop.policy.ControlLoop;
35 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
36 import org.onap.policy.controlloop.policy.FinalResult;
37 import org.onap.policy.controlloop.policy.Policy;
38 import org.onap.policy.controlloop.policy.PolicyResult;
39 import org.onap.policy.controlloop.policy.TargetType;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.yaml.snakeyaml.Yaml;
43 import org.yaml.snakeyaml.constructor.Constructor;
46 public class ControlLoopCompiler implements Serializable {
47 private static final String OPERATION_POLICY = "Operation Policy ";
48 private static final long serialVersionUID = 1L;
49 private static final Logger LOGGER = LoggerFactory.getLogger(ControlLoopCompiler.class.getName());
52 * Compiles the policy from an object.
54 public static ControlLoopPolicy compile(ControlLoopPolicy policy,
55 ControlLoopCompilerCallback callback) throws CompilerException {
57 // Ensure the control loop is sane
59 validateControlLoop(policy.getControlLoop(), callback);
61 // Validate the policies
63 validatePolicies(policy, callback);
69 * Compiles the policy from an input stream.
71 * @param yamlSpecification the yaml input stream
72 * @param callback method to callback during compilation
73 * @return Control Loop object
74 * @throws CompilerException throws any compile exception found
76 public static ControlLoopPolicy compile(InputStream yamlSpecification,
77 ControlLoopCompilerCallback callback) throws CompilerException {
78 Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
79 Object obj = yaml.load(yamlSpecification);
81 throw new CompilerException("Could not parse yaml specification.");
83 if (! (obj instanceof ControlLoopPolicy)) {
84 throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object");
86 return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback);
89 private static void validateControlLoop(ControlLoop controlLoop,
90 ControlLoopCompilerCallback callback) throws CompilerException {
91 if (controlLoop == null && callback != null) {
92 callback.onError("controlLoop cannot be null");
94 if (controlLoop != null) {
95 if (StringUtils.isEmpty(controlLoop.getControlLoopName()) && callback != null) {
96 callback.onError("Missing controlLoopName");
98 if ((!controlLoop.getVersion().contentEquals(ControlLoop.getCompilerVersion())) && callback != null) {
99 callback.onError("Unsupported version for this compiler");
101 if (StringUtils.isEmpty(controlLoop.getTrigger_policy())) {
102 throw new CompilerException("trigger_policy is not valid");
107 private static void validatePolicies(ControlLoopPolicy policy,
108 ControlLoopCompilerCallback callback) throws CompilerException {
109 if (policy == null) {
110 throw new CompilerException("policy cannot be null");
112 if (policy.getPolicies() == null) {
113 callback.onWarning("controlLoop is an open loop.");
116 // For this version we can use a directed multigraph, in the future we may not be able to
118 Graph<NodeWrapper, LabeledEdge> graph =
119 new DirectedMultigraph<>(new ClassBasedEdgeFactory<NodeWrapper,
120 LabeledEdge>(LabeledEdge.class));
122 // Check to see if the trigger Event is for OpenLoop, we do so by
123 // attempting to create a FinalResult object from it. If its a policy id, this should
126 FinalResult triggerResult = FinalResult.toResult(policy.getControlLoop().getTrigger_policy());
127 TriggerNodeWrapper triggerNode;
129 // Did this turn into a FinalResult object?
131 if (triggerResult != null) {
132 validateOpenLoopPolicy(policy, triggerResult, callback);
136 validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(policy, callback);
137 triggerNode = new TriggerNodeWrapper(policy.getControlLoop().getControlLoopName());
140 // Add in the trigger node
142 graph.addVertex(triggerNode);
144 // Add in our Final Result nodes. All paths should end to these nodes.
146 FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS);
147 FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE);
148 FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT);
149 FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES);
150 FinalResultNodeWrapper finalFailureException =
151 new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION);
152 FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD);
153 graph.addVertex(finalSuccess);
154 graph.addVertex(finalFailure);
155 graph.addVertex(finalFailureTimeout);
156 graph.addVertex(finalFailureRetries);
157 graph.addVertex(finalFailureException);
158 graph.addVertex(finalFailureGuard);
160 // Work through the policies and add them in as nodes.
162 Map<Policy, PolicyNodeWrapper> mapNodes = addPoliciesAsNodes(policy, graph, triggerNode, callback);
164 // last sweep to connect remaining edges for policy results
166 for (Policy operPolicy : policy.getPolicies()) {
167 PolicyNodeWrapper node = mapNodes.get(operPolicy);
169 // Just ensure this has something
174 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getSuccess(), finalSuccess,
175 PolicyResult.SUCCESS, node);
176 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure(), finalFailure,
177 PolicyResult.FAILURE, node);
178 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_timeout(), finalFailureTimeout,
179 PolicyResult.FAILURE_TIMEOUT, node);
180 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_retries(), finalFailureRetries,
181 PolicyResult.FAILURE_RETRIES, node);
182 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_exception(), finalFailureException,
183 PolicyResult.FAILURE_EXCEPTION, node);
184 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_guard(), finalFailureGuard,
185 PolicyResult.FAILURE_GUARD, node);
187 validateNodesAndEdges(graph, callback);
191 private static void validateOpenLoopPolicy(ControlLoopPolicy policy, FinalResult triggerResult,
192 ControlLoopCompilerCallback callback) throws CompilerException {
194 // Ensure they didn't use some other FinalResult code
196 if (triggerResult != FinalResult.FINAL_OPENLOOP) {
197 throw new CompilerException("Unexpected Final Result for trigger_policy, should only be "
198 + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
201 // They really shouldn't have any policies attached.
203 if ((policy.getPolicies() != null || policy.getPolicies().isEmpty()) && callback != null) {
204 callback.onWarning("Open Loop policy contains policies. The policies will never be invoked.");
208 private static void validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(ControlLoopPolicy policy,
209 ControlLoopCompilerCallback callback) throws CompilerException {
211 boolean triggerPolicyFound = false;
212 for (Policy operPolicy : policy.getPolicies()) {
213 sum += operPolicy.getTimeout().intValue();
214 if (policy.getControlLoop().getTrigger_policy().equals(operPolicy.getId())) {
215 triggerPolicyFound = true;
218 if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) {
219 callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts.");
222 if (!triggerPolicyFound) {
223 throw new CompilerException("Unexpected value for trigger_policy, should only be "
224 + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
228 private static Map<Policy, PolicyNodeWrapper> addPoliciesAsNodes(ControlLoopPolicy policy,
229 Graph<NodeWrapper, LabeledEdge> graph, TriggerNodeWrapper triggerNode,
230 ControlLoopCompilerCallback callback) {
231 Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<>();
232 for (Policy operPolicy : policy.getPolicies()) {
234 // Is it still ok to add?
236 if (!okToAdd(operPolicy, callback)) {
243 // Create wrapper policy node and save it into our map so we can
244 // easily retrieve it.
246 PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy);
247 mapNodes.put(operPolicy, node);
248 graph.addVertex(node);
250 // Is this the trigger policy?
252 if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) {
254 // Yes add an edge from our trigger event node to this policy
256 graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET")));
262 private static void addEdge(Graph<NodeWrapper, LabeledEdge> graph, Map<Policy, PolicyNodeWrapper> mapNodes,
263 String policyId, String connectedPolicy,
264 FinalResultNodeWrapper finalResultNodeWrapper,
265 PolicyResult policyResult, NodeWrapper node) throws CompilerException {
266 FinalResult finalResult = FinalResult.toResult(finalResultNodeWrapper.getId());
267 if (FinalResult.isResult(connectedPolicy, finalResult)) {
268 graph.addEdge(node, finalResultNodeWrapper, new LabeledEdge(node, finalResultNodeWrapper,
269 new FinalResultEdgeWrapper(finalResult)));
271 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, connectedPolicy);
272 if (toNode == null) {
273 throw new CompilerException(OPERATION_POLICY + policyId + " is connected to unknown policy "
276 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(policyResult)));
281 private static void validateNodesAndEdges(Graph<NodeWrapper, LabeledEdge> graph,
282 ControlLoopCompilerCallback callback) throws CompilerException {
283 for (NodeWrapper node : graph.vertexSet()) {
284 if (node instanceof TriggerNodeWrapper) {
285 validateTriggerNodeWrapper(graph, node);
286 } else if (node instanceof FinalResultNodeWrapper) {
287 validateFinalResultNodeWrapper(graph, node);
288 } else if (node instanceof PolicyNodeWrapper) {
289 validatePolicyNodeWrapper(graph, node, callback);
291 for (LabeledEdge edge : graph.outgoingEdgesOf(node)) {
292 LOGGER.info("{} invokes {} upon {}", edge.from.getId(), edge.to.getId(), edge.edge.getId());
297 private static void validateTriggerNodeWrapper(Graph<NodeWrapper, LabeledEdge> graph,
298 NodeWrapper node) throws CompilerException {
299 if (LOGGER.isDebugEnabled()) {
300 LOGGER.info("Trigger Node {}", node);
302 if (graph.inDegreeOf(node) > 0) {
304 // Really should NEVER get here unless someone messed up the code above.
306 throw new CompilerException("No inputs to event trigger");
309 // Should always be 1, except in the future we may support multiple events
311 if (graph.outDegreeOf(node) > 1) {
312 throw new CompilerException("The event trigger should only go to ONE node");
316 private static void validateFinalResultNodeWrapper(Graph<NodeWrapper, LabeledEdge> graph,
317 NodeWrapper node) throws CompilerException {
318 if (LOGGER.isDebugEnabled()) {
319 LOGGER.info("FinalResult Node {}", node);
322 // FinalResult nodes should NEVER have an out edge
324 if (graph.outDegreeOf(node) > 0) {
325 throw new CompilerException("FinalResult nodes should never have any out edges.");
329 private static void validatePolicyNodeWrapper(Graph<NodeWrapper, LabeledEdge> graph,
330 NodeWrapper node, ControlLoopCompilerCallback callback) throws CompilerException {
331 if (LOGGER.isDebugEnabled()) {
332 LOGGER.info("Policy Node {}", node);
335 // All Policy Nodes should have the 5 out degrees defined.
337 if (graph.outDegreeOf(node) != 6) {
338 throw new CompilerException("Policy node should ALWAYS have 6 out degrees.");
341 // All Policy Nodes should have at least 1 in degrees
343 if (graph.inDegreeOf(node) == 0 && callback != null) {
344 callback.onWarning("Policy " + node.getId() + " is not reachable.");
348 private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) {
349 boolean isOk = isPolicyIdOk(operPolicy, callback);
350 if (! isActorOk(operPolicy, callback)) {
353 if (! isRecipeOk(operPolicy, callback)) {
356 if (! isTargetOk(operPolicy, callback)) {
359 if (! arePolicyResultsOk(operPolicy, callback)) {
365 private static boolean isPolicyIdOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
367 if (operPolicy.getId() == null || operPolicy.getId().length() < 1) {
368 if (callback != null) {
369 callback.onError("Operational Policy has an bad ID");
374 // Check if they decided to make the ID a result object
376 if (PolicyResult.toResult(operPolicy.getId()) != null) {
377 if (callback != null) {
378 callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId());
382 if (FinalResult.toResult(operPolicy.getId()) != null) {
383 if (callback != null) {
384 callback.onError("Policy id is set to a FinalResult " + operPolicy.getId());
392 private static boolean isActorOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
393 if (StringUtils.isBlank(operPolicy.getActor())) {
394 if (callback != null) {
395 callback.onError("Policy actor is null");
402 private static boolean isRecipeOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
403 if (StringUtils.isBlank(operPolicy.getRecipe())) {
404 if (callback != null) {
405 callback.onError("Policy recipe is null");
412 private static boolean isTargetOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
414 if (operPolicy.getTarget() == null) {
415 if (callback != null) {
416 callback.onError("Policy target is null");
420 if (operPolicy.getTarget() != null
421 && operPolicy.getTarget().getType() != TargetType.VM
422 && operPolicy.getTarget().getType() != TargetType.VFC
423 && operPolicy.getTarget().getType() != TargetType.PNF) {
424 if (callback != null) {
425 callback.onError("Policy target is invalid");
432 private static boolean arePolicyResultsOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
434 // Check that policy results are connected to either default final * or another policy
436 boolean isOk = isSuccessPolicyResultOk(operPolicy, callback);
437 if (! isFailurePolicyResultOk(operPolicy, callback)) {
440 if (! isFailureRetriesPolicyResultOk(operPolicy, callback)) {
443 if (! isFailureTimeoutPolicyResultOk(operPolicy, callback)) {
446 if (! isFailureExceptionPolicyResultOk(operPolicy, callback)) {
449 if (! isFailureGuardPolicyResultOk(operPolicy, callback)) {
455 private static boolean isSuccessPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
456 if (FinalResult.toResult(operPolicy.getSuccess()) != null
457 && !operPolicy.getSuccess().equals(FinalResult.FINAL_SUCCESS.toString())) {
458 if (callback != null) {
459 callback.onError("Policy success is neither another policy nor FINAL_SUCCESS");
466 private static boolean isFailurePolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
467 if (FinalResult.toResult(operPolicy.getFailure()) != null
468 && !operPolicy.getFailure().equals(FinalResult.FINAL_FAILURE.toString())) {
469 if (callback != null) {
470 callback.onError("Policy failure is neither another policy nor FINAL_FAILURE");
477 private static boolean isFailureRetriesPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
478 if (FinalResult.toResult(operPolicy.getFailure_retries()) != null
479 && !operPolicy.getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())) {
480 if (callback != null) {
481 callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES");
488 private static boolean isFailureTimeoutPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
489 if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null
490 && !operPolicy.getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())) {
491 if (callback != null) {
492 callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT");
499 private static boolean isFailureExceptionPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
500 if (FinalResult.toResult(operPolicy.getFailure_exception()) != null
501 && !operPolicy.getFailure_exception().equals(FinalResult.FINAL_FAILURE_EXCEPTION.toString())) {
502 if (callback != null) {
503 callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION");
510 private static boolean isFailureGuardPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
511 if (FinalResult.toResult(operPolicy.getFailure_guard()) != null
512 && !operPolicy.getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())) {
513 if (callback != null) {
514 callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD");
521 private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) {
522 for (Entry<Policy, PolicyNodeWrapper> entry : mapNodes.entrySet()) {
523 if (entry.getKey().getId().equals(id)) {
524 return entry.getValue();
531 private interface NodeWrapper extends Serializable {
532 public String getId();
535 private static class TriggerNodeWrapper implements NodeWrapper {
536 private static final long serialVersionUID = -187644087811478349L;
537 private String closedLoopControlName;
539 public TriggerNodeWrapper(String closedLoopControlName) {
540 this.closedLoopControlName = closedLoopControlName;
544 public String toString() {
545 return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]";
549 public String getId() {
550 return closedLoopControlName;
555 private static class FinalResultNodeWrapper implements NodeWrapper {
556 private static final long serialVersionUID = 8540008796302474613L;
557 private FinalResult result;
559 public FinalResultNodeWrapper(FinalResult result) {
560 this.result = result;
564 public String toString() {
565 return "FinalResultNodeWrapper [result=" + result + "]";
569 public String getId() {
570 return result.toString();
574 private static class PolicyNodeWrapper implements NodeWrapper {
575 private static final long serialVersionUID = 8170162175653823082L;
576 private transient Policy policy;
578 public PolicyNodeWrapper(Policy operPolicy) {
579 this.policy = operPolicy;
583 public String toString() {
584 return "PolicyNodeWrapper [policy=" + policy + "]";
588 public String getId() {
589 return policy.getId();
594 private interface EdgeWrapper extends Serializable {
595 public String getId();
599 private static class TriggerEdgeWrapper implements EdgeWrapper {
600 private static final long serialVersionUID = 2678151552623278863L;
601 private String trigger;
603 public TriggerEdgeWrapper(String trigger) {
604 this.trigger = trigger;
608 public String getId() {
613 public String toString() {
614 return "TriggerEdgeWrapper [trigger=" + trigger + "]";
619 private static class PolicyResultEdgeWrapper implements EdgeWrapper {
620 private static final long serialVersionUID = 6078569477021558310L;
621 private PolicyResult policyResult;
623 public PolicyResultEdgeWrapper(PolicyResult policyResult) {
625 this.policyResult = policyResult;
629 public String toString() {
630 return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]";
634 public String getId() {
635 return policyResult.toString();
641 private static class FinalResultEdgeWrapper implements EdgeWrapper {
642 private static final long serialVersionUID = -1486381946896779840L;
643 private FinalResult finalResult;
645 public FinalResultEdgeWrapper(FinalResult result) {
646 this.finalResult = result;
650 public String toString() {
651 return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]";
655 public String getId() {
656 return finalResult.toString();
661 private static class LabeledEdge extends DefaultEdge {
662 private static final long serialVersionUID = 579384429573385524L;
664 private NodeWrapper from;
665 private NodeWrapper to;
666 private EdgeWrapper edge;
668 public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) {
674 @SuppressWarnings("unused")
675 public NodeWrapper from() {
679 @SuppressWarnings("unused")
680 public NodeWrapper to() {
684 @SuppressWarnings("unused")
685 public EdgeWrapper edge() {
690 public String toString() {
691 return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]";