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());
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
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.getVERSION())) && 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(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + 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.toString());
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.toString());
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.toString());
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 isOk = isActorOk(operPolicy, callback) ? isOk : false;
357 isOk = isRecipeOk(operPolicy, callback) ? isOk : false;
358 isOk = isTargetOk(operPolicy, callback) ? isOk : false;
359 isOk = arePolicyResultsOk(operPolicy, callback) ? isOk : false;
363 private static boolean isPolicyIdOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
365 if (operPolicy.getId() == null || operPolicy.getId().length() < 1) {
366 if (callback != null) {
367 callback.onError("Operational Policy has an bad ID");
372 // Check if they decided to make the ID a result object
374 if (PolicyResult.toResult(operPolicy.getId()) != null) {
375 if (callback != null) {
376 callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId());
380 if (FinalResult.toResult(operPolicy.getId()) != null) {
381 if (callback != null) {
382 callback.onError("Policy id is set to a FinalResult " + operPolicy.getId());
390 private static boolean isActorOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
392 if (operPolicy.getActor() == null) {
393 if (callback != null) {
394 callback.onError("Policy actor is null");
399 // Construct a list for all valid actors
401 ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI");
403 if (operPolicy.getActor() != null && (!actors.contains(operPolicy.getActor())) ) {
404 if (callback != null) {
405 callback.onError("Policy actor is invalid");
412 private static boolean isRecipeOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
414 if (operPolicy.getRecipe() == null) {
415 if (callback != null) {
416 callback.onError("Policy recipe is null");
421 // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these)
423 ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>()
424 .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig"))
425 .put("AOTS", ImmutableList.of("checkMaintenanceWindow",
426 "checkENodeBTicketHours",
427 "checkEquipmentStatus",
429 "checkEquipmentMaintenance"))
430 .put("MSO", ImmutableList.of("VF Module Create"))
431 .put("SDNO", ImmutableList.of("health-diagnostic-type",
433 "health-diagnostic-history",
434 "health-diagnostic-commands",
435 "health-diagnostic-aes"))
436 .put("SDNR", ImmutableList.of("Restart", "Reboot"))
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 isOk = isFailurePolicyResultOk(operPolicy, callback) ? isOk : false;
476 isOk = isFailureRetriesPolicyResultOk(operPolicy, callback) ? isOk : false;
477 isOk = isFailureTimeoutPolicyResultOk(operPolicy, callback) ? isOk : false;
478 isOk = isFailureExceptionPolicyResultOk(operPolicy, callback) ? isOk : false;
479 isOk = isFailureGuardPolicyResultOk(operPolicy, callback) ? isOk : false;
483 private static boolean isSuccessPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
485 if (FinalResult.toResult(operPolicy.getSuccess()) != null
486 && !operPolicy.getSuccess().equals(FinalResult.FINAL_SUCCESS.toString())) {
487 if (callback != null) {
488 callback.onError("Policy success is neither another policy nor FINAL_SUCCESS");
495 private static boolean isFailurePolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
497 if (FinalResult.toResult(operPolicy.getFailure()) != null
498 && !operPolicy.getFailure().equals(FinalResult.FINAL_FAILURE.toString())) {
499 if (callback != null) {
500 callback.onError("Policy failure is neither another policy nor FINAL_FAILURE");
507 private static boolean isFailureRetriesPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
509 if (FinalResult.toResult(operPolicy.getFailure_retries()) != null
510 && !operPolicy.getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())) {
511 if (callback != null) {
512 callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES");
519 private static boolean isFailureTimeoutPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
521 if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null
522 && !operPolicy.getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())) {
523 if (callback != null) {
524 callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT");
531 private static boolean isFailureExceptionPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
533 if (FinalResult.toResult(operPolicy.getFailure_exception()) != null
534 && !operPolicy.getFailure_exception().equals(FinalResult.FINAL_FAILURE_EXCEPTION.toString())) {
535 if (callback != null) {
536 callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION");
543 private static boolean isFailureGuardPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
545 if (FinalResult.toResult(operPolicy.getFailure_guard()) != null
546 && !operPolicy.getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())) {
547 if (callback != null) {
548 callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD");
555 private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) {
556 for (Entry<Policy, PolicyNodeWrapper> entry : mapNodes.entrySet()) {
557 if (entry.getKey().getId().equals(id)) {
558 return entry.getValue();
565 private interface NodeWrapper extends Serializable {
566 public String getID();
569 private static class TriggerNodeWrapper implements NodeWrapper {
570 private static final long serialVersionUID = -187644087811478349L;
571 private String closedLoopControlName;
573 public TriggerNodeWrapper(String closedLoopControlName) {
574 this.closedLoopControlName = closedLoopControlName;
578 public String toString() {
579 return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]";
583 public String getID() {
584 return closedLoopControlName;
589 private static class FinalResultNodeWrapper implements NodeWrapper {
590 private static final long serialVersionUID = 8540008796302474613L;
591 private FinalResult result;
593 public FinalResultNodeWrapper(FinalResult result) {
594 this.result = result;
598 public String toString() {
599 return "FinalResultNodeWrapper [result=" + result + "]";
603 public String getID() {
604 return result.toString();
608 private static class PolicyNodeWrapper implements NodeWrapper {
609 private static final long serialVersionUID = 8170162175653823082L;
610 private transient Policy policy;
612 public PolicyNodeWrapper(Policy operPolicy) {
613 this.policy = operPolicy;
617 public String toString() {
618 return "PolicyNodeWrapper [policy=" + policy + "]";
622 public String getID() {
623 return policy.getId();
628 private interface EdgeWrapper extends Serializable {
629 public String getID();
633 private static class TriggerEdgeWrapper implements EdgeWrapper {
634 private static final long serialVersionUID = 2678151552623278863L;
635 private String trigger;
637 public TriggerEdgeWrapper(String trigger) {
638 this.trigger = trigger;
642 public String getID() {
647 public String toString() {
648 return "TriggerEdgeWrapper [trigger=" + trigger + "]";
653 private static class PolicyResultEdgeWrapper implements EdgeWrapper {
654 private static final long serialVersionUID = 6078569477021558310L;
655 private PolicyResult policyResult;
657 public PolicyResultEdgeWrapper(PolicyResult policyResult) {
659 this.policyResult = policyResult;
663 public String toString() {
664 return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]";
668 public String getID() {
669 return policyResult.toString();
675 private static class FinalResultEdgeWrapper implements EdgeWrapper {
676 private static final long serialVersionUID = -1486381946896779840L;
677 private FinalResult finalResult;
679 public FinalResultEdgeWrapper(FinalResult result) {
680 this.finalResult = result;
684 public String toString() {
685 return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]";
689 public String getID() {
690 return finalResult.toString();
695 private static class LabeledEdge extends DefaultEdge {
696 private static final long serialVersionUID = 579384429573385524L;
698 private NodeWrapper from;
699 private NodeWrapper to;
700 private EdgeWrapper edge;
702 public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) {
708 @SuppressWarnings("unused")
709 public NodeWrapper from() {
713 @SuppressWarnings("unused")
714 public NodeWrapper to() {
718 @SuppressWarnings("unused")
719 public EdgeWrapper edge() {
724 public String toString() {
725 return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]";