2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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());
55 public static ControlLoopPolicy compile(ControlLoopPolicy policy,
56 ControlLoopCompilerCallback callback) throws CompilerException {
58 // Ensure the control loop is sane
60 validateControlLoop(policy.getControlLoop(), callback);
62 // Validate the policies
64 validatePolicies(policy, callback);
69 public static ControlLoopPolicy compile(InputStream yamlSpecification,
70 ControlLoopCompilerCallback callback) throws CompilerException {
71 Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
72 Object obj = yaml.load(yamlSpecification);
74 throw new CompilerException("Could not parse yaml specification.");
76 if (! (obj instanceof ControlLoopPolicy)) {
77 throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object");
79 return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback);
82 private static void validateControlLoop(ControlLoop controlLoop,
83 ControlLoopCompilerCallback callback) throws CompilerException {
84 if (controlLoop == null && callback != null) {
85 callback.onError("controlLoop cannot be null");
87 if (controlLoop!=null){
88 if ((controlLoop.getControlLoopName() == null || controlLoop.getControlLoopName().length() < 1)
89 && callback != null) {
90 callback.onError("Missing controlLoopName");
92 if ((!controlLoop.getVersion().contentEquals(ControlLoop.getVERSION())) && callback != null) {
93 callback.onError("Unsupported version for this compiler");
95 if (controlLoop.getTrigger_policy() == null || controlLoop.getTrigger_policy().length() < 1) {
96 throw new CompilerException("trigger_policy is not valid");
101 private static void validatePolicies(ControlLoopPolicy policy,
102 ControlLoopCompilerCallback callback) throws CompilerException {
103 if (policy == null) {
104 throw new CompilerException("policy cannot be null");
106 if (policy.getPolicies() == null) {
107 callback.onWarning("controlLoop is an open loop.");
110 // For this version we can use a directed multigraph, in the future we may not be able to
112 DirectedGraph<NodeWrapper, LabeledEdge> graph =
113 new DirectedMultigraph<>(new ClassBasedEdgeFactory<NodeWrapper,
114 LabeledEdge>(LabeledEdge.class));
116 // Check to see if the trigger Event is for OpenLoop, we do so by
117 // attempting to create a FinalResult object from it. If its a policy id, this should
120 FinalResult triggerResult = FinalResult.toResult(policy.getControlLoop().getTrigger_policy());
121 TriggerNodeWrapper triggerNode;
123 // Did this turn into a FinalResult object?
125 if (triggerResult != null) {
126 validateOpenLoopPolicy(policy, triggerResult, callback);
130 validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(policy, callback);
131 triggerNode = new TriggerNodeWrapper(policy.getControlLoop().getControlLoopName());
134 // Add in the trigger node
136 graph.addVertex(triggerNode);
138 // Add in our Final Result nodes. All paths should end to these nodes.
140 FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS);
141 FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE);
142 FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT);
143 FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES);
144 FinalResultNodeWrapper finalFailureException =
145 new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION);
146 FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD);
147 graph.addVertex(finalSuccess);
148 graph.addVertex(finalFailure);
149 graph.addVertex(finalFailureTimeout);
150 graph.addVertex(finalFailureRetries);
151 graph.addVertex(finalFailureException);
152 graph.addVertex(finalFailureGuard);
154 // Work through the policies and add them in as nodes.
156 Map<Policy, PolicyNodeWrapper> mapNodes = addPoliciesAsNodes(policy, graph, triggerNode, callback);
158 // last sweep to connect remaining edges for policy results
160 for (Policy operPolicy : policy.getPolicies()) {
161 PolicyNodeWrapper node = mapNodes.get(operPolicy);
163 // Just ensure this has something
168 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getSuccess(), finalSuccess,
169 PolicyResult.SUCCESS, node);
170 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure(), finalFailure,
171 PolicyResult.FAILURE, node);
172 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_timeout(), finalFailureTimeout,
173 PolicyResult.FAILURE_TIMEOUT, node);
174 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_retries(), finalFailureRetries,
175 PolicyResult.FAILURE_RETRIES, node);
176 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_exception(), finalFailureException,
177 PolicyResult.FAILURE_EXCEPTION, node);
178 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_guard(), finalFailureGuard,
179 PolicyResult.FAILURE_GUARD, node);
181 validateNodesAndEdges(graph, callback);
185 private static void validateOpenLoopPolicy(ControlLoopPolicy policy, FinalResult triggerResult,
186 ControlLoopCompilerCallback callback) throws CompilerException {
188 // Ensure they didn't use some other FinalResult code
190 if (triggerResult != FinalResult.FINAL_OPENLOOP) {
191 throw new CompilerException("Unexpected Final Result for trigger_policy, should only be "
192 + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
195 // They really shouldn't have any policies attached.
197 if ((policy.getPolicies() != null || policy.getPolicies().isEmpty()) && callback != null ) {
198 callback.onWarning("Open Loop policy contains policies. The policies will never be invoked.");
202 private static void validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(ControlLoopPolicy policy,
203 ControlLoopCompilerCallback callback) throws CompilerException {
205 boolean triggerPolicyFound = false;
206 for (Policy operPolicy : policy.getPolicies()) {
207 sum += operPolicy.getTimeout().intValue();
208 if (policy.getControlLoop().getTrigger_policy().equals(operPolicy.getId())) {
209 triggerPolicyFound = true;
212 if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) {
213 callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts.");
216 if (!triggerPolicyFound) {
217 throw new CompilerException("Unexpected value for trigger_policy, should only be "
218 + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
222 private static Map<Policy, PolicyNodeWrapper> addPoliciesAsNodes(ControlLoopPolicy policy,
223 DirectedGraph<NodeWrapper, LabeledEdge> graph, TriggerNodeWrapper triggerNode,
224 ControlLoopCompilerCallback callback) {
225 Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<>();
226 for (Policy operPolicy : policy.getPolicies()) {
228 // Is it still ok to add?
230 if (!okToAdd(operPolicy, callback)) {
237 // Create wrapper policy node and save it into our map so we can
238 // easily retrieve it.
240 PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy);
241 mapNodes.put(operPolicy, node);
242 graph.addVertex(node);
244 // Is this the trigger policy?
246 if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) {
248 // Yes add an edge from our trigger event node to this policy
250 graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET")));
256 private static void addEdge(DirectedGraph<NodeWrapper, LabeledEdge> graph, Map<Policy, PolicyNodeWrapper> mapNodes,
257 String policyId, String connectedPolicy,
258 FinalResultNodeWrapper finalResultNodeWrapper,
259 PolicyResult policyResult, NodeWrapper node) throws CompilerException {
260 FinalResult finalResult = FinalResult.toResult(finalResultNodeWrapper.getID());
261 if (FinalResult.isResult(connectedPolicy, finalResult)) {
262 graph.addEdge(node, finalResultNodeWrapper, new LabeledEdge(node, finalResultNodeWrapper,
263 new FinalResultEdgeWrapper(finalResult)));
265 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, connectedPolicy);
266 if (toNode == null) {
267 throw new CompilerException(OPERATION_POLICY + policyId + " is connected to unknown policy "
270 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(policyResult)));
275 private static void validateNodesAndEdges(DirectedGraph<NodeWrapper, LabeledEdge> graph,
276 ControlLoopCompilerCallback callback) throws CompilerException {
277 for (NodeWrapper node : graph.vertexSet()) {
278 if (node instanceof TriggerNodeWrapper) {
279 validateTriggerNodeWrapper(graph, node);
280 } else if (node instanceof FinalResultNodeWrapper) {
281 validateFinalResultNodeWrapper(graph, node);
282 } else if (node instanceof PolicyNodeWrapper) {
283 validatePolicyNodeWrapper(graph, node, callback);
285 for (LabeledEdge edge : graph.outgoingEdgesOf(node)) {
286 LOGGER.info(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID());
291 private static void validateTriggerNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
292 NodeWrapper node) throws CompilerException {
293 if (LOGGER.isDebugEnabled()) {
294 LOGGER.info("Trigger Node {}", node.toString());
296 if (graph.inDegreeOf(node) > 0 ) {
298 // Really should NEVER get here unless someone messed up the code above.
300 throw new CompilerException("No inputs to event trigger");
303 // Should always be 1, except in the future we may support multiple events
305 if (graph.outDegreeOf(node) > 1) {
306 throw new CompilerException("The event trigger should only go to ONE node");
310 private static void validateFinalResultNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
311 NodeWrapper node) throws CompilerException {
312 if (LOGGER.isDebugEnabled()) {
313 LOGGER.info("FinalResult Node {}", node.toString());
316 // FinalResult nodes should NEVER have an out edge
318 if (graph.outDegreeOf(node) > 0) {
319 throw new CompilerException("FinalResult nodes should never have any out edges.");
323 private static void validatePolicyNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
324 NodeWrapper node, ControlLoopCompilerCallback callback) throws CompilerException {
325 if (LOGGER.isDebugEnabled()) {
326 LOGGER.info("Policy Node {}", node.toString());
329 // All Policy Nodes should have the 5 out degrees defined.
331 if (graph.outDegreeOf(node) != 6) {
332 throw new CompilerException("Policy node should ALWAYS have 6 out degrees.");
335 // All Policy Nodes should have at least 1 in degrees
337 if (graph.inDegreeOf(node) == 0 && callback != null) {
338 callback.onWarning("Policy " + node.getID() + " is not reachable.");
342 private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) {
343 boolean isOk = isPolicyIdOk(operPolicy, callback);
344 isOk = isActorOk(operPolicy, callback) ? isOk : false;
345 isOk = isRecipeOk(operPolicy, callback) ? isOk : false;
346 isOk = isTargetOk(operPolicy, callback) ? isOk : false;
347 isOk = arePolicyResultsOk(operPolicy, callback) ? isOk : false;
351 private static boolean isPolicyIdOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
353 if (operPolicy.getId() == null || operPolicy.getId().length() < 1) {
354 if (callback != null) {
355 callback.onError("Operational Policy has an bad ID");
360 // Check if they decided to make the ID a result object
362 if (PolicyResult.toResult(operPolicy.getId()) != null) {
363 if (callback != null) {
364 callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId());
368 if (FinalResult.toResult(operPolicy.getId()) != null) {
369 if (callback != null) {
370 callback.onError("Policy id is set to a FinalResult " + operPolicy.getId());
378 private static boolean isActorOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
380 if (operPolicy.getActor() == null) {
381 if (callback != null) {
382 callback.onError("Policy actor is null");
387 // Construct a list for all valid actors
389 ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI");
391 if (operPolicy.getActor() != null && (!actors.contains(operPolicy.getActor())) ) {
392 if (callback != null) {
393 callback.onError("Policy actor is invalid");
400 private static boolean isRecipeOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
402 if (operPolicy.getRecipe() == null) {
403 if (callback != null) {
404 callback.onError("Policy recipe is null");
409 // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these)
411 ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>()
412 .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig"))
413 .put("AOTS", ImmutableList.of("checkMaintenanceWindow",
414 "checkENodeBTicketHours",
415 "checkEquipmentStatus",
417 "checkEquipmentMaintenance"))
418 .put("MSO", ImmutableList.of("VF Module Create"))
419 .put("SDNO", ImmutableList.of("health-diagnostic-type",
421 "health-diagnostic-history",
422 "health-diagnostic-commands",
423 "health-diagnostic-aes"))
424 .put("SDNR", ImmutableList.of("Restart", "Reboot"))
427 if (operPolicy.getRecipe() != null
428 && (!recipes.getOrDefault(operPolicy.getActor(),
429 Collections.emptyList()).contains(operPolicy.getRecipe()))) {
430 if (callback != null) {
431 callback.onError("Policy recipe is invalid");
438 private static boolean isTargetOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
440 if (operPolicy.getTarget() == null) {
441 if (callback != null) {
442 callback.onError("Policy target is null");
446 if (operPolicy.getTarget() != null
447 && operPolicy.getTarget().getType() != TargetType.VM
448 && operPolicy.getTarget().getType() != TargetType.VFC
449 && operPolicy.getTarget().getType() != TargetType.PNF) {
450 if (callback != null) {
451 callback.onError("Policy target is invalid");
458 private static boolean arePolicyResultsOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
460 // Check that policy results are connected to either default final * or another policy
462 boolean isOk = isSuccessPolicyResultOk(operPolicy, callback);
463 isOk = isFailurePolicyResultOk(operPolicy, callback) ? isOk : false;
464 isOk = isFailureRetriesPolicyResultOk(operPolicy, callback) ? isOk : false;
465 isOk = isFailureTimeoutPolicyResultOk(operPolicy, callback) ? isOk : false;
466 isOk = isFailureExceptionPolicyResultOk(operPolicy, callback) ? isOk : false;
467 isOk = isFailureGuardPolicyResultOk(operPolicy, callback) ? isOk : false;
471 private static boolean isSuccessPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
473 if (FinalResult.toResult(operPolicy.getSuccess()) != null
474 && !operPolicy.getSuccess().equals(FinalResult.FINAL_SUCCESS.toString())) {
475 if (callback != null) {
476 callback.onError("Policy success is neither another policy nor FINAL_SUCCESS");
483 private static boolean isFailurePolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
485 if (FinalResult.toResult(operPolicy.getFailure()) != null
486 && !operPolicy.getFailure().equals(FinalResult.FINAL_FAILURE.toString())) {
487 if (callback != null) {
488 callback.onError("Policy failure is neither another policy nor FINAL_FAILURE");
495 private static boolean isFailureRetriesPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
497 if (FinalResult.toResult(operPolicy.getFailure_retries()) != null
498 && !operPolicy.getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())) {
499 if (callback != null) {
500 callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES");
507 private static boolean isFailureTimeoutPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
509 if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null
510 && !operPolicy.getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())) {
511 if (callback != null) {
512 callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT");
519 private static boolean isFailureExceptionPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
521 if (FinalResult.toResult(operPolicy.getFailure_exception()) != null
522 && !operPolicy.getFailure_exception().equals(FinalResult.FINAL_FAILURE_EXCEPTION.toString())) {
523 if (callback != null) {
524 callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION");
531 private static boolean isFailureGuardPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
533 if (FinalResult.toResult(operPolicy.getFailure_guard()) != null
534 && !operPolicy.getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())) {
535 if (callback != null) {
536 callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD");
543 private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) {
544 for (Entry<Policy, PolicyNodeWrapper> entry : mapNodes.entrySet()) {
545 if (entry.getKey().getId().equals(id)) {
546 return entry.getValue();
553 private interface NodeWrapper extends Serializable {
554 public String getID();
557 private static class TriggerNodeWrapper implements NodeWrapper {
558 private static final long serialVersionUID = -187644087811478349L;
559 private String closedLoopControlName;
561 public TriggerNodeWrapper(String closedLoopControlName) {
562 this.closedLoopControlName = closedLoopControlName;
566 public String toString() {
567 return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]";
571 public String getID() {
572 return closedLoopControlName;
577 private static class FinalResultNodeWrapper implements NodeWrapper {
578 private static final long serialVersionUID = 8540008796302474613L;
579 private FinalResult result;
581 public FinalResultNodeWrapper(FinalResult result) {
582 this.result = result;
586 public String toString() {
587 return "FinalResultNodeWrapper [result=" + result + "]";
591 public String getID() {
592 return result.toString();
596 private static class PolicyNodeWrapper implements NodeWrapper {
597 private static final long serialVersionUID = 8170162175653823082L;
598 private transient Policy policy;
600 public PolicyNodeWrapper(Policy operPolicy) {
601 this.policy = operPolicy;
605 public String toString() {
606 return "PolicyNodeWrapper [policy=" + policy + "]";
610 public String getID() {
611 return policy.getId();
616 private interface EdgeWrapper extends Serializable {
617 public String getID();
621 private static class TriggerEdgeWrapper implements EdgeWrapper {
622 private static final long serialVersionUID = 2678151552623278863L;
623 private String trigger;
625 public TriggerEdgeWrapper(String trigger) {
626 this.trigger = trigger;
630 public String getID() {
635 public String toString() {
636 return "TriggerEdgeWrapper [trigger=" + trigger + "]";
641 private static class PolicyResultEdgeWrapper implements EdgeWrapper {
642 private static final long serialVersionUID = 6078569477021558310L;
643 private PolicyResult policyResult;
645 public PolicyResultEdgeWrapper(PolicyResult policyResult) {
647 this.policyResult = policyResult;
651 public String toString() {
652 return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]";
656 public String getID() {
657 return policyResult.toString();
663 private static class FinalResultEdgeWrapper implements EdgeWrapper {
664 private static final long serialVersionUID = -1486381946896779840L;
665 private FinalResult finalResult;
667 public FinalResultEdgeWrapper(FinalResult result) {
668 this.finalResult = result;
672 public String toString() {
673 return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]";
677 public String getID() {
678 return finalResult.toString();
683 private static class LabeledEdge extends DefaultEdge {
684 private static final long serialVersionUID = 579384429573385524L;
686 private NodeWrapper from;
687 private NodeWrapper to;
688 private EdgeWrapper edge;
690 public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) {
696 @SuppressWarnings("unused")
697 public NodeWrapper from() {
701 @SuppressWarnings("unused")
702 public NodeWrapper to() {
706 @SuppressWarnings("unused")
707 public EdgeWrapper edge() {
712 public String toString() {
713 return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]";