2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.controlloop.compiler;
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.collect.ImmutableMap;
26 import java.io.InputStream;
27 import java.io.Serializable;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
32 import java.util.Map.Entry;
34 import org.jgrapht.DirectedGraph;
35 import org.jgrapht.graph.ClassBasedEdgeFactory;
36 import org.jgrapht.graph.DefaultEdge;
37 import org.jgrapht.graph.DirectedMultigraph;
38 import org.onap.policy.controlloop.policy.ControlLoop;
39 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
40 import org.onap.policy.controlloop.policy.FinalResult;
41 import org.onap.policy.controlloop.policy.Policy;
42 import org.onap.policy.controlloop.policy.PolicyResult;
43 import org.onap.policy.controlloop.policy.TargetType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.yaml.snakeyaml.Yaml;
47 import org.yaml.snakeyaml.constructor.Constructor;
50 public class ControlLoopCompiler implements Serializable {
51 private static final String OPERATION_POLICY = "Operation Policy ";
52 private static final long serialVersionUID = 1L;
53 private static final Logger LOGGER = LoggerFactory.getLogger(ControlLoopCompiler.class.getName());
56 * Compiles the policy from an object.
58 public static ControlLoopPolicy compile(ControlLoopPolicy policy,
59 ControlLoopCompilerCallback callback) throws CompilerException {
61 // Ensure the control loop is sane
63 validateControlLoop(policy.getControlLoop(), callback);
65 // Validate the policies
67 validatePolicies(policy, callback);
73 * Compiles the policy from an input stream.
75 * @param yamlSpecification the yaml input stream
76 * @param callback method to callback during compilation
77 * @return Control Loop object
78 * @throws CompilerException throws any compile exception found
80 public static ControlLoopPolicy compile(InputStream yamlSpecification,
81 ControlLoopCompilerCallback callback) throws CompilerException {
82 Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
83 Object obj = yaml.load(yamlSpecification);
85 throw new CompilerException("Could not parse yaml specification.");
87 if (! (obj instanceof ControlLoopPolicy)) {
88 throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object");
90 return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback);
93 private static void validateControlLoop(ControlLoop controlLoop,
94 ControlLoopCompilerCallback callback) throws CompilerException {
95 if (controlLoop == null && callback != null) {
96 callback.onError("controlLoop cannot be null");
98 if (controlLoop != null) {
99 if ((controlLoop.getControlLoopName() == null || controlLoop.getControlLoopName().length() < 1)
100 && callback != null) {
101 callback.onError("Missing controlLoopName");
103 if ((!controlLoop.getVersion().contentEquals(ControlLoop.getCompilerVersion())) && callback != null) {
104 callback.onError("Unsupported version for this compiler");
106 if (controlLoop.getTrigger_policy() == null || controlLoop.getTrigger_policy().length() < 1) {
107 throw new CompilerException("trigger_policy is not valid");
112 private static void validatePolicies(ControlLoopPolicy policy,
113 ControlLoopCompilerCallback callback) throws CompilerException {
114 if (policy == null) {
115 throw new CompilerException("policy cannot be null");
117 if (policy.getPolicies() == null) {
118 callback.onWarning("controlLoop is an open loop.");
121 // For this version we can use a directed multigraph, in the future we may not be able to
123 DirectedGraph<NodeWrapper, LabeledEdge> graph =
124 new DirectedMultigraph<>(new ClassBasedEdgeFactory<NodeWrapper,
125 LabeledEdge>(LabeledEdge.class));
127 // Check to see if the trigger Event is for OpenLoop, we do so by
128 // attempting to create a FinalResult object from it. If its a policy id, this should
131 FinalResult triggerResult = FinalResult.toResult(policy.getControlLoop().getTrigger_policy());
132 TriggerNodeWrapper triggerNode;
134 // Did this turn into a FinalResult object?
136 if (triggerResult != null) {
137 validateOpenLoopPolicy(policy, triggerResult, callback);
141 validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(policy, callback);
142 triggerNode = new TriggerNodeWrapper(policy.getControlLoop().getControlLoopName());
145 // Add in the trigger node
147 graph.addVertex(triggerNode);
149 // Add in our Final Result nodes. All paths should end to these nodes.
151 FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS);
152 FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE);
153 FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT);
154 FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES);
155 FinalResultNodeWrapper finalFailureException =
156 new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION);
157 FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD);
158 graph.addVertex(finalSuccess);
159 graph.addVertex(finalFailure);
160 graph.addVertex(finalFailureTimeout);
161 graph.addVertex(finalFailureRetries);
162 graph.addVertex(finalFailureException);
163 graph.addVertex(finalFailureGuard);
165 // Work through the policies and add them in as nodes.
167 Map<Policy, PolicyNodeWrapper> mapNodes = addPoliciesAsNodes(policy, graph, triggerNode, callback);
169 // last sweep to connect remaining edges for policy results
171 for (Policy operPolicy : policy.getPolicies()) {
172 PolicyNodeWrapper node = mapNodes.get(operPolicy);
174 // Just ensure this has something
179 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getSuccess(), finalSuccess,
180 PolicyResult.SUCCESS, node);
181 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure(), finalFailure,
182 PolicyResult.FAILURE, node);
183 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_timeout(), finalFailureTimeout,
184 PolicyResult.FAILURE_TIMEOUT, node);
185 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_retries(), finalFailureRetries,
186 PolicyResult.FAILURE_RETRIES, node);
187 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_exception(), finalFailureException,
188 PolicyResult.FAILURE_EXCEPTION, node);
189 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_guard(), finalFailureGuard,
190 PolicyResult.FAILURE_GUARD, node);
192 validateNodesAndEdges(graph, callback);
196 private static void validateOpenLoopPolicy(ControlLoopPolicy policy, FinalResult triggerResult,
197 ControlLoopCompilerCallback callback) throws CompilerException {
199 // Ensure they didn't use some other FinalResult code
201 if (triggerResult != FinalResult.FINAL_OPENLOOP) {
202 throw new CompilerException("Unexpected Final Result for trigger_policy, should only be "
203 + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
206 // They really shouldn't have any policies attached.
208 if ((policy.getPolicies() != null || policy.getPolicies().isEmpty()) && callback != null ) {
209 callback.onWarning("Open Loop policy contains policies. The policies will never be invoked.");
213 private static void validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(ControlLoopPolicy policy,
214 ControlLoopCompilerCallback callback) throws CompilerException {
216 boolean triggerPolicyFound = false;
217 for (Policy operPolicy : policy.getPolicies()) {
218 sum += operPolicy.getTimeout().intValue();
219 if (policy.getControlLoop().getTrigger_policy().equals(operPolicy.getId())) {
220 triggerPolicyFound = true;
223 if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) {
224 callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts.");
227 if (!triggerPolicyFound) {
228 throw new CompilerException("Unexpected value for trigger_policy, should only be "
229 + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
233 private static Map<Policy, PolicyNodeWrapper> addPoliciesAsNodes(ControlLoopPolicy policy,
234 DirectedGraph<NodeWrapper, LabeledEdge> graph, TriggerNodeWrapper triggerNode,
235 ControlLoopCompilerCallback callback) {
236 Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<>();
237 for (Policy operPolicy : policy.getPolicies()) {
239 // Is it still ok to add?
241 if (!okToAdd(operPolicy, callback)) {
248 // Create wrapper policy node and save it into our map so we can
249 // easily retrieve it.
251 PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy);
252 mapNodes.put(operPolicy, node);
253 graph.addVertex(node);
255 // Is this the trigger policy?
257 if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) {
259 // Yes add an edge from our trigger event node to this policy
261 graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET")));
267 private static void addEdge(DirectedGraph<NodeWrapper, LabeledEdge> graph, Map<Policy, PolicyNodeWrapper> mapNodes,
268 String policyId, String connectedPolicy,
269 FinalResultNodeWrapper finalResultNodeWrapper,
270 PolicyResult policyResult, NodeWrapper node) throws CompilerException {
271 FinalResult finalResult = FinalResult.toResult(finalResultNodeWrapper.getId());
272 if (FinalResult.isResult(connectedPolicy, finalResult)) {
273 graph.addEdge(node, finalResultNodeWrapper, new LabeledEdge(node, finalResultNodeWrapper,
274 new FinalResultEdgeWrapper(finalResult)));
276 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, connectedPolicy);
277 if (toNode == null) {
278 throw new CompilerException(OPERATION_POLICY + policyId + " is connected to unknown policy "
281 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(policyResult)));
286 private static void validateNodesAndEdges(DirectedGraph<NodeWrapper, LabeledEdge> graph,
287 ControlLoopCompilerCallback callback) throws CompilerException {
288 for (NodeWrapper node : graph.vertexSet()) {
289 if (node instanceof TriggerNodeWrapper) {
290 validateTriggerNodeWrapper(graph, node);
291 } else if (node instanceof FinalResultNodeWrapper) {
292 validateFinalResultNodeWrapper(graph, node);
293 } else if (node instanceof PolicyNodeWrapper) {
294 validatePolicyNodeWrapper(graph, node, callback);
296 for (LabeledEdge edge : graph.outgoingEdgesOf(node)) {
297 LOGGER.info("{} invokes {} upon {}", edge.from.getId(), edge.to.getId(), edge.edge.getId());
302 private static void validateTriggerNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
303 NodeWrapper node) throws CompilerException {
304 if (LOGGER.isDebugEnabled()) {
305 LOGGER.info("Trigger Node {}", node);
307 if (graph.inDegreeOf(node) > 0 ) {
309 // Really should NEVER get here unless someone messed up the code above.
311 throw new CompilerException("No inputs to event trigger");
314 // Should always be 1, except in the future we may support multiple events
316 if (graph.outDegreeOf(node) > 1) {
317 throw new CompilerException("The event trigger should only go to ONE node");
321 private static void validateFinalResultNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
322 NodeWrapper node) throws CompilerException {
323 if (LOGGER.isDebugEnabled()) {
324 LOGGER.info("FinalResult Node {}", node);
327 // FinalResult nodes should NEVER have an out edge
329 if (graph.outDegreeOf(node) > 0) {
330 throw new CompilerException("FinalResult nodes should never have any out edges.");
334 private static void validatePolicyNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
335 NodeWrapper node, ControlLoopCompilerCallback callback) throws CompilerException {
336 if (LOGGER.isDebugEnabled()) {
337 LOGGER.info("Policy Node {}", node);
340 // All Policy Nodes should have the 5 out degrees defined.
342 if (graph.outDegreeOf(node) != 6) {
343 throw new CompilerException("Policy node should ALWAYS have 6 out degrees.");
346 // All Policy Nodes should have at least 1 in degrees
348 if (graph.inDegreeOf(node) == 0 && callback != null) {
349 callback.onWarning("Policy " + node.getId() + " is not reachable.");
353 private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) {
354 boolean isOk = isPolicyIdOk(operPolicy, callback);
355 if (! isActorOk(operPolicy, callback)) {
358 if (! isRecipeOk(operPolicy, callback)) {
361 if (! isTargetOk(operPolicy, callback) ) {
364 if (! arePolicyResultsOk(operPolicy, callback) ) {
370 private static boolean isPolicyIdOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
372 if (operPolicy.getId() == null || operPolicy.getId().length() < 1) {
373 if (callback != null) {
374 callback.onError("Operational Policy has an bad ID");
379 // Check if they decided to make the ID a result object
381 if (PolicyResult.toResult(operPolicy.getId()) != null) {
382 if (callback != null) {
383 callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId());
387 if (FinalResult.toResult(operPolicy.getId()) != null) {
388 if (callback != null) {
389 callback.onError("Policy id is set to a FinalResult " + operPolicy.getId());
397 private static boolean isActorOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
399 if (operPolicy.getActor() == null) {
400 if (callback != null) {
401 callback.onError("Policy actor is null");
406 // Construct a list for all valid actors
408 ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI");
410 if (operPolicy.getActor() != null && (!actors.contains(operPolicy.getActor())) ) {
411 if (callback != null) {
412 callback.onError("Policy actor is invalid");
419 private static boolean isRecipeOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
421 if (operPolicy.getRecipe() == null) {
422 if (callback != null) {
423 callback.onError("Policy recipe is null");
428 // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these)
430 ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>()
431 .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig"))
432 .put("AOTS", ImmutableList.of("checkMaintenanceWindow",
433 "checkENodeBTicketHours",
434 "checkEquipmentStatus",
436 "checkEquipmentMaintenance"))
437 .put("MSO", ImmutableList.of("VF Module Create"))
438 .put("SDNO", ImmutableList.of("health-diagnostic-type",
440 "health-diagnostic-history",
441 "health-diagnostic-commands",
442 "health-diagnostic-aes"))
443 .put("SDNR", ImmutableList.of("Restart", "Reboot"))
446 if (operPolicy.getRecipe() != null
447 && (!recipes.getOrDefault(operPolicy.getActor(),
448 Collections.emptyList()).contains(operPolicy.getRecipe()))) {
449 if (callback != null) {
450 callback.onError("Policy recipe is invalid");
457 private static boolean isTargetOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
459 if (operPolicy.getTarget() == null) {
460 if (callback != null) {
461 callback.onError("Policy target is null");
465 if (operPolicy.getTarget() != null
466 && operPolicy.getTarget().getType() != TargetType.VM
467 && operPolicy.getTarget().getType() != TargetType.VFC
468 && operPolicy.getTarget().getType() != TargetType.PNF) {
469 if (callback != null) {
470 callback.onError("Policy target is invalid");
477 private static boolean arePolicyResultsOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
479 // Check that policy results are connected to either default final * or another policy
481 boolean isOk = isSuccessPolicyResultOk(operPolicy, callback);
482 if (! isFailurePolicyResultOk(operPolicy, callback) ) {
485 if (! isFailureRetriesPolicyResultOk(operPolicy, callback) ) {
488 if (! isFailureTimeoutPolicyResultOk(operPolicy, callback) ) {
491 if (! isFailureExceptionPolicyResultOk(operPolicy, callback) ) {
494 if (! isFailureGuardPolicyResultOk(operPolicy, callback) ) {
500 private static boolean isSuccessPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
502 if (FinalResult.toResult(operPolicy.getSuccess()) != null
503 && !operPolicy.getSuccess().equals(FinalResult.FINAL_SUCCESS.toString())) {
504 if (callback != null) {
505 callback.onError("Policy success is neither another policy nor FINAL_SUCCESS");
512 private static boolean isFailurePolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
514 if (FinalResult.toResult(operPolicy.getFailure()) != null
515 && !operPolicy.getFailure().equals(FinalResult.FINAL_FAILURE.toString())) {
516 if (callback != null) {
517 callback.onError("Policy failure is neither another policy nor FINAL_FAILURE");
524 private static boolean isFailureRetriesPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
526 if (FinalResult.toResult(operPolicy.getFailure_retries()) != null
527 && !operPolicy.getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())) {
528 if (callback != null) {
529 callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES");
536 private static boolean isFailureTimeoutPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
538 if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null
539 && !operPolicy.getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())) {
540 if (callback != null) {
541 callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT");
548 private static boolean isFailureExceptionPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
550 if (FinalResult.toResult(operPolicy.getFailure_exception()) != null
551 && !operPolicy.getFailure_exception().equals(FinalResult.FINAL_FAILURE_EXCEPTION.toString())) {
552 if (callback != null) {
553 callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION");
560 private static boolean isFailureGuardPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
562 if (FinalResult.toResult(operPolicy.getFailure_guard()) != null
563 && !operPolicy.getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())) {
564 if (callback != null) {
565 callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD");
572 private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) {
573 for (Entry<Policy, PolicyNodeWrapper> entry : mapNodes.entrySet()) {
574 if (entry.getKey().getId().equals(id)) {
575 return entry.getValue();
582 private interface NodeWrapper extends Serializable {
583 public String getId();
586 private static class TriggerNodeWrapper implements NodeWrapper {
587 private static final long serialVersionUID = -187644087811478349L;
588 private String closedLoopControlName;
590 public TriggerNodeWrapper(String closedLoopControlName) {
591 this.closedLoopControlName = closedLoopControlName;
595 public String toString() {
596 return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]";
600 public String getId() {
601 return closedLoopControlName;
606 private static class FinalResultNodeWrapper implements NodeWrapper {
607 private static final long serialVersionUID = 8540008796302474613L;
608 private FinalResult result;
610 public FinalResultNodeWrapper(FinalResult result) {
611 this.result = result;
615 public String toString() {
616 return "FinalResultNodeWrapper [result=" + result + "]";
620 public String getId() {
621 return result.toString();
625 private static class PolicyNodeWrapper implements NodeWrapper {
626 private static final long serialVersionUID = 8170162175653823082L;
627 private transient Policy policy;
629 public PolicyNodeWrapper(Policy operPolicy) {
630 this.policy = operPolicy;
634 public String toString() {
635 return "PolicyNodeWrapper [policy=" + policy + "]";
639 public String getId() {
640 return policy.getId();
645 private interface EdgeWrapper extends Serializable {
646 public String getId();
650 private static class TriggerEdgeWrapper implements EdgeWrapper {
651 private static final long serialVersionUID = 2678151552623278863L;
652 private String trigger;
654 public TriggerEdgeWrapper(String trigger) {
655 this.trigger = trigger;
659 public String getId() {
664 public String toString() {
665 return "TriggerEdgeWrapper [trigger=" + trigger + "]";
670 private static class PolicyResultEdgeWrapper implements EdgeWrapper {
671 private static final long serialVersionUID = 6078569477021558310L;
672 private PolicyResult policyResult;
674 public PolicyResultEdgeWrapper(PolicyResult policyResult) {
676 this.policyResult = policyResult;
680 public String toString() {
681 return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]";
685 public String getId() {
686 return policyResult.toString();
692 private static class FinalResultEdgeWrapper implements EdgeWrapper {
693 private static final long serialVersionUID = -1486381946896779840L;
694 private FinalResult finalResult;
696 public FinalResultEdgeWrapper(FinalResult result) {
697 this.finalResult = result;
701 public String toString() {
702 return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]";
706 public String getId() {
707 return finalResult.toString();
712 private static class LabeledEdge extends DefaultEdge {
713 private static final long serialVersionUID = 579384429573385524L;
715 private NodeWrapper from;
716 private NodeWrapper to;
717 private EdgeWrapper edge;
719 public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) {
725 @SuppressWarnings("unused")
726 public NodeWrapper from() {
730 @SuppressWarnings("unused")
731 public NodeWrapper to() {
735 @SuppressWarnings("unused")
736 public EdgeWrapper edge() {
741 public String toString() {
742 return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]";