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 java.io.InputStream;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.List;
29 import org.jgrapht.DirectedGraph;
30 import org.jgrapht.graph.ClassBasedEdgeFactory;
31 import org.jgrapht.graph.DefaultEdge;
32 import org.jgrapht.graph.DirectedMultigraph;
33 import org.yaml.snakeyaml.Yaml;
34 import org.yaml.snakeyaml.constructor.Constructor;
36 import org.onap.policy.controlloop.policy.ControlLoop;
37 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
38 import org.onap.policy.controlloop.policy.FinalResult;
39 import org.onap.policy.controlloop.policy.Policy;
40 import org.onap.policy.controlloop.policy.PolicyResult;
41 import org.onap.policy.controlloop.policy.TargetType;
43 import com.google.common.collect.ImmutableList;
44 import com.google.common.collect.ImmutableMap;
46 public class ControlLoopCompiler {
48 public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException {
50 // Ensure the control loop is sane
52 validateControlLoop(policy.controlLoop, callback);
54 // Validate the policies
56 validatePolicies(policy, callback);
61 public static ControlLoopPolicy compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException {
62 Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
63 Object obj = yaml.load(yamlSpecification);
65 throw new CompilerException("Could not parse yaml specification.");
67 if (! (obj instanceof ControlLoopPolicy)) {
68 throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object");
70 return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback);
73 private static void validateControlLoop(ControlLoop controlLoop, ControlLoopCompilerCallback callback) throws CompilerException {
74 if (controlLoop == null) {
75 if (callback != null) {
76 callback.onError("controlLoop cannot be null");
79 if (controlLoop.controlLoopName == null | controlLoop.controlLoopName.length() < 1) {
80 if (callback != null) {
81 callback.onError("Missing controlLoopName");
84 if (! controlLoop.version.contentEquals(ControlLoop.VERSION)) {
85 if (callback != null) {
86 callback.onError("Unsupported version for this compiler");
89 if (controlLoop.trigger_policy == null || controlLoop.trigger_policy.length() < 1) {
90 throw new CompilerException("trigger_policy is not valid");
95 private static void validatePolicies(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException {
97 throw new CompilerException("policy cannot be null");
100 // Chenfei: verify controlLoop overall timeout should be no less than the sum of operational policy timeouts
102 if (policy.policies == null) {
103 callback.onWarning("controlLoop is an open loop.");
107 for (Policy operPolicy : policy.policies) {
108 sum += operPolicy.timeout.intValue();
110 if (policy.controlLoop.timeout.intValue() < sum) {
111 if (callback != null) {
112 callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts.");
116 // For this version we can use a directed multigraph, in the future we may not be able to
118 DirectedGraph<NodeWrapper, LabeledEdge> graph = new DirectedMultigraph<NodeWrapper, LabeledEdge>(new ClassBasedEdgeFactory<NodeWrapper, LabeledEdge>(LabeledEdge.class));
120 // Check to see if the trigger Event is for OpenLoop, we do so by
121 // attempting to create a FinalResult object from it. If its a policy id, this should
124 FinalResult triggerResult = FinalResult.toResult(policy.controlLoop.trigger_policy);
125 TriggerNodeWrapper triggerNode;
127 // Did this turn into a FinalResult object?
129 if (triggerResult != null) {
131 // Ensure they didn't use some other FinalResult code
133 if (triggerResult != FinalResult.FINAL_OPENLOOP) {
134 throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
137 // They really shouldn't have any policies attached.
139 if (policy.policies != null || policy.policies.size() > 0) {
140 if (callback != null) {
141 callback.onWarning("Open Loop policy contains policies. The policies will never be invoked.");
148 // Ok, not a FinalResult object so let's assume that it is a Policy. Which it should be.
150 triggerNode = new TriggerNodeWrapper(policy.controlLoop.controlLoopName);
153 // Add in the trigger node
155 graph.addVertex(triggerNode);
157 // Add in our Final Result nodes. All paths should end to these nodes.
159 FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS);
160 FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE);
161 FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT);
162 FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES);
163 FinalResultNodeWrapper finalFailureException = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION);
164 FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD);
165 graph.addVertex(finalSuccess);
166 graph.addVertex(finalFailure);
167 graph.addVertex(finalFailureTimeout);
168 graph.addVertex(finalFailureRetries);
169 graph.addVertex(finalFailureException);
170 graph.addVertex(finalFailureGuard);
172 // Work through the policies and add them in as nodes.
174 Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<Policy, PolicyNodeWrapper>();
175 for (Policy operPolicy : policy.policies) {
177 // Check the policy id and make sure its sane
179 boolean okToAdd = true;
180 if (operPolicy.id == null || operPolicy.id.length() < 1) {
181 if (callback != null) {
182 callback.onError("Operational Policy has an bad ID");
187 // Check if they decided to make the ID a result object
189 if (PolicyResult.toResult(operPolicy.id) != null) {
190 if (callback != null) {
191 callback.onError("Policy id is set to a PolicyResult " + operPolicy.id);
195 if (FinalResult.toResult(operPolicy.id) != null) {
196 if (callback != null) {
197 callback.onError("Policy id is set to a FinalResult " + operPolicy.id);
202 // Check that the actor/recipe/target are valid
204 if (operPolicy.actor == null) {
205 if (callback != null) {
206 callback.onError("Policy actor is null");
211 // Construct a list for all valid actors
213 ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI");
215 if (operPolicy.actor != null && (!actors.contains(operPolicy.actor)) ) {
216 if (callback != null) {
217 callback.onError("Policy actor is invalid");
221 if (operPolicy.recipe == null) {
222 if (callback != null) {
223 callback.onError("Policy recipe is null");
229 // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these)
231 ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>()
232 .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig"))
233 .put("AOTS", ImmutableList.of("checkMaintenanceWindow", "checkENodeBTicketHours", "checkEquipmentStatus", "checkEimStatus", "checkEquipmentMaintenance"))
234 .put("MSO", ImmutableList.of("VF Module Create"))
235 .put("SDNO", ImmutableList.of("health-diagnostic-type", "health-diagnostic", "health-diagnostic-history", "health-diagnostic-commands", "health-diagnostic-aes"))
236 .put("SDNR", ImmutableList.of("Restart", "Reboot"))
239 if (operPolicy.recipe != null && (!recipes.getOrDefault(operPolicy.actor, Collections.emptyList()).contains(operPolicy.recipe))) {
240 if (callback != null) {
241 callback.onError("Policy recipe is invalid");
245 if (operPolicy.target == null) {
246 if (callback != null) {
247 callback.onError("Policy target is null");
251 if (operPolicy.target != null && operPolicy.target.type != TargetType.VM && operPolicy.target.type != TargetType.VFC && operPolicy.target.type != TargetType.PNF) {
252 if (callback != null) {
253 callback.onError("Policy target is invalid");
258 // Check that policy results are connected to either default final * or another policy
260 if (FinalResult.toResult(operPolicy.success) != null && operPolicy.success != FinalResult.FINAL_SUCCESS.toString()) {
261 if (callback != null) {
262 callback.onError("Policy success is neither another policy nor FINAL_SUCCESS");
266 if (FinalResult.toResult(operPolicy.failure) != null && operPolicy.failure != FinalResult.FINAL_FAILURE.toString()) {
267 if (callback != null) {
268 callback.onError("Policy failure is neither another policy nor FINAL_FAILURE");
272 if (FinalResult.toResult(operPolicy.failure_retries) != null && operPolicy.failure_retries != FinalResult.FINAL_FAILURE_RETRIES.toString()) {
273 if (callback != null) {
274 callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES");
278 if (FinalResult.toResult(operPolicy.failure_timeout) != null && operPolicy.failure_timeout != FinalResult.FINAL_FAILURE_TIMEOUT.toString()) {
279 if (callback != null) {
280 callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT");
284 if (FinalResult.toResult(operPolicy.failure_exception) != null && operPolicy.failure_exception != FinalResult.FINAL_FAILURE_EXCEPTION.toString()) {
285 if (callback != null) {
286 callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION");
290 if (FinalResult.toResult(operPolicy.failure_guard) != null && operPolicy.failure_guard != FinalResult.FINAL_FAILURE_GUARD.toString()) {
291 if (callback != null) {
292 callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD");
297 // Is it still ok to add?
299 if (okToAdd == false) {
306 // Create wrapper policy node and save it into our map so we can
307 // easily retrieve it.
309 PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy);
310 mapNodes.put(operPolicy, node);
311 graph.addVertex(node);
313 // Is this the trigger policy?
315 if (operPolicy.id.equals(policy.controlLoop.trigger_policy)) {
317 // Yes add an edge from our trigger event node to this policy
319 graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET")));
323 // last sweep to connect remaining edges for policy results
325 for (Policy operPolicy : policy.policies) {
326 PolicyNodeWrapper node = mapNodes.get(operPolicy);
328 // Just ensure this has something
333 if (FinalResult.isResult(operPolicy.success, FinalResult.FINAL_SUCCESS)) {
334 graph.addEdge(node, finalSuccess, new LabeledEdge(node, finalSuccess, new FinalResultEdgeWrapper(FinalResult.FINAL_SUCCESS)));
336 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.success);
337 if (toNode == null) {
338 throw new CompilerException("Operation Policy " + operPolicy.id + " success is connected to unknown policy " + operPolicy.success);
340 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.SUCCESS)));
343 if (FinalResult.isResult(operPolicy.failure, FinalResult.FINAL_FAILURE)) {
344 graph.addEdge(node, finalFailure, new LabeledEdge(node, finalFailure, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE)));
346 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure);
347 if (toNode == null) {
348 throw new CompilerException("Operation Policy " + operPolicy.id + " failure is connected to unknown policy " + operPolicy.failure);
350 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE)));
353 if (FinalResult.isResult(operPolicy.failure_timeout, FinalResult.FINAL_FAILURE_TIMEOUT)) {
354 graph.addEdge(node, finalFailureTimeout, new LabeledEdge(node, finalFailureTimeout, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT)));
356 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_timeout);
357 if (toNode == null) {
358 throw new CompilerException("Operation Policy " + operPolicy.id + " failure_timeout is connected to unknown policy " + operPolicy.failure_timeout);
360 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_TIMEOUT)));
363 if (FinalResult.isResult(operPolicy.failure_retries, FinalResult.FINAL_FAILURE_RETRIES)) {
364 graph.addEdge(node, finalFailureRetries, new LabeledEdge(node, finalFailureRetries, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_RETRIES)));
366 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_retries);
367 if (toNode == null) {
368 throw new CompilerException("Operation Policy " + operPolicy.id + " failure_retries is connected to unknown policy " + operPolicy.failure_retries);
370 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_RETRIES)));
373 if (FinalResult.isResult(operPolicy.failure_exception, FinalResult.FINAL_FAILURE_EXCEPTION)) {
374 graph.addEdge(node, finalFailureException, new LabeledEdge(node, finalFailureException, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION)));
376 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_exception);
377 if (toNode == null) {
378 throw new CompilerException("Operation Policy " + operPolicy.id + " failure_exception is connected to unknown policy " + operPolicy.failure_exception);
380 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_EXCEPTION)));
383 if (FinalResult.isResult(operPolicy.failure_guard, FinalResult.FINAL_FAILURE_GUARD)) {
384 graph.addEdge(node, finalFailureGuard, new LabeledEdge(node, finalFailureGuard, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_GUARD)));
386 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_guard);
387 if (toNode == null) {
388 throw new CompilerException("Operation Policy " + operPolicy.id + " failure_guard is connected to unknown policy " + operPolicy.failure_guard);
390 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_GUARD)));
395 // Now validate all the nodes/edges
397 for (NodeWrapper node : graph.vertexSet()) {
398 if (node instanceof TriggerNodeWrapper) {
399 System.out.println("Trigger Node " + node.toString());
400 if (graph.inDegreeOf(node) > 0 ) {
402 // Really should NEVER get here unless someone messed up the code above.
404 throw new CompilerException("No inputs to event trigger");
407 // Should always be 1, except in the future we may support multiple events
409 if (graph.outDegreeOf(node) > 1) {
410 throw new CompilerException("The event trigger should only go to ONE node");
412 } else if (node instanceof FinalResultNodeWrapper) {
413 System.out.println("FinalResult Node " + node.toString());
415 // FinalResult nodes should NEVER have an out edge
417 if (graph.outDegreeOf(node) > 0) {
418 throw new CompilerException("FinalResult nodes should never have any out edges.");
420 } else if (node instanceof PolicyNodeWrapper) {
421 System.out.println("Policy Node " + node.toString());
423 // All Policy Nodes should have the 5 out degrees defined.
425 if (graph.outDegreeOf(node) != 6) {
426 throw new CompilerException("Policy node should ALWAYS have 6 out degrees.");
429 // Chenfei: All Policy Nodes should have at least 1 in degrees
431 if (graph.inDegreeOf(node) == 0) {
432 if (callback != null) {
433 callback.onWarning("Policy " + node.getID() + " is not reachable.");
437 for (LabeledEdge edge : graph.outgoingEdgesOf(node)){
438 System.out.println(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID());
444 private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) {
445 for (Policy key : mapNodes.keySet()) {
446 if (key.id.equals(id)) {
447 return mapNodes.get(key);
453 private interface NodeWrapper {
455 public String getID();
459 private static class TriggerNodeWrapper implements NodeWrapper {
460 public String closedLoopControlName;
462 public TriggerNodeWrapper(String closedLoopControlName) {
463 this.closedLoopControlName = closedLoopControlName;
467 public String toString() {
468 return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]";
472 public String getID() {
473 return closedLoopControlName;
478 private static class FinalResultNodeWrapper implements NodeWrapper {
480 public FinalResult result;
482 public FinalResultNodeWrapper(FinalResult result) {
483 this.result = result;
487 public String toString() {
488 return "FinalResultNodeWrapper [result=" + result + "]";
492 public String getID() {
493 return result.toString();
497 private static class PolicyNodeWrapper implements NodeWrapper {
499 public Policy policy;
501 public PolicyNodeWrapper(Policy operPolicy) {
502 this.policy = operPolicy;
506 public String toString() {
507 return "PolicyNodeWrapper [policy=" + policy + "]";
511 public String getID() {
516 private interface EdgeWrapper {
518 public String getID();
522 private static class TriggerEdgeWrapper implements EdgeWrapper {
524 private String trigger;
526 public TriggerEdgeWrapper(String trigger) {
527 this.trigger = trigger;
531 public String getID() {
536 public String toString() {
537 return "TriggerEdgeWrapper [trigger=" + trigger + "]";
542 private static class PolicyResultEdgeWrapper implements EdgeWrapper {
543 public PolicyResult policyResult;
545 public PolicyResultEdgeWrapper(PolicyResult policyResult) {
547 this.policyResult = policyResult;
551 public String toString() {
552 return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]";
556 public String getID() {
557 return policyResult.toString();
563 private static class FinalResultEdgeWrapper implements EdgeWrapper {
565 public FinalResult finalResult;
566 public FinalResultEdgeWrapper(FinalResult result) {
567 this.finalResult = result;
571 public String toString() {
572 return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]";
576 public String getID() {
577 return finalResult.toString();
582 private static class LabeledEdge extends DefaultEdge {
587 private static final long serialVersionUID = 579384429573385524L;
589 private NodeWrapper from;
590 private NodeWrapper to;
591 private EdgeWrapper edge;
593 public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) {
599 @SuppressWarnings("unused")
600 public NodeWrapper from() {
604 @SuppressWarnings("unused")
605 public NodeWrapper to() {
609 @SuppressWarnings("unused")
610 public EdgeWrapper edge() {
615 public String toString() {
616 return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]";