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.io.Serializable;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.Map.Entry;
31 import org.jgrapht.DirectedGraph;
32 import org.jgrapht.graph.ClassBasedEdgeFactory;
33 import org.jgrapht.graph.DefaultEdge;
34 import org.jgrapht.graph.DirectedMultigraph;
35 import org.onap.policy.controlloop.policy.ControlLoop;
36 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
37 import org.onap.policy.controlloop.policy.FinalResult;
38 import org.onap.policy.controlloop.policy.Policy;
39 import org.onap.policy.controlloop.policy.PolicyResult;
40 import org.onap.policy.controlloop.policy.TargetType;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.yaml.snakeyaml.Yaml;
44 import org.yaml.snakeyaml.constructor.Constructor;
46 import com.google.common.collect.ImmutableList;
47 import com.google.common.collect.ImmutableMap;
49 public class ControlLoopCompiler implements Serializable{
50 private static final String OPERATION_POLICY = "Operation Policy ";
51 private static final long serialVersionUID = 1L;
52 private static final Logger LOGGER = LoggerFactory.getLogger(ControlLoopCompiler.class.getName());
54 public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException {
56 // Ensure the control loop is sane
58 validateControlLoop(policy.getControlLoop(), callback);
60 // Validate the policies
62 validatePolicies(policy, callback);
67 public static ControlLoopPolicy compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException {
68 Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
69 Object obj = yaml.load(yamlSpecification);
71 throw new CompilerException("Could not parse yaml specification.");
73 if (! (obj instanceof ControlLoopPolicy)) {
74 throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object");
76 return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback);
79 private static void validateControlLoop(ControlLoop controlLoop, ControlLoopCompilerCallback callback) throws CompilerException {
80 if (controlLoop == null && callback != null) {
81 callback.onError("controlLoop cannot be null");
83 if (controlLoop!=null){
84 if ((controlLoop.getControlLoopName() == null || controlLoop.getControlLoopName().length() < 1) && callback != null) {
85 callback.onError("Missing controlLoopName");
87 if ((!controlLoop.getVersion().contentEquals(ControlLoop.getVERSION())) && callback != null) {
88 callback.onError("Unsupported version for this compiler");
90 if (controlLoop.getTrigger_policy() == null || controlLoop.getTrigger_policy().length() < 1) {
91 throw new CompilerException("trigger_policy is not valid");
96 private static void validatePolicies(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException {
98 throw new CompilerException("policy cannot be null");
100 if (policy.getPolicies() == null) {
101 callback.onWarning("controlLoop is an open loop.");
105 // For this version we can use a directed multigraph, in the future we may not be able to
107 DirectedGraph<NodeWrapper, LabeledEdge> graph = new DirectedMultigraph<>(new ClassBasedEdgeFactory<NodeWrapper, LabeledEdge>(LabeledEdge.class));
109 // Check to see if the trigger Event is for OpenLoop, we do so by
110 // attempting to create a FinalResult object from it. If its a policy id, this should
113 FinalResult triggerResult = FinalResult.toResult(policy.getControlLoop().getTrigger_policy());
114 TriggerNodeWrapper triggerNode;
116 // Did this turn into a FinalResult object?
118 if (triggerResult != null) {
119 validateOpenLoopPolicy(policy, triggerResult, callback);
123 validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(policy, callback);
124 triggerNode = new TriggerNodeWrapper(policy.getControlLoop().getControlLoopName());
127 // Add in the trigger node
129 graph.addVertex(triggerNode);
131 // Add in our Final Result nodes. All paths should end to these nodes.
133 FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS);
134 FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE);
135 FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT);
136 FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES);
137 FinalResultNodeWrapper finalFailureException = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION);
138 FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD);
139 graph.addVertex(finalSuccess);
140 graph.addVertex(finalFailure);
141 graph.addVertex(finalFailureTimeout);
142 graph.addVertex(finalFailureRetries);
143 graph.addVertex(finalFailureException);
144 graph.addVertex(finalFailureGuard);
146 // Work through the policies and add them in as nodes.
148 Map<Policy, PolicyNodeWrapper> mapNodes = addPoliciesAsNodes(policy, graph, triggerNode, callback);
150 // last sweep to connect remaining edges for policy results
152 for (Policy operPolicy : policy.getPolicies()) {
153 PolicyNodeWrapper node = mapNodes.get(operPolicy);
155 // Just ensure this has something
160 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getSuccess(), finalSuccess, PolicyResult.SUCCESS, node);
161 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure(), finalFailure, PolicyResult.FAILURE, node);
162 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_timeout(), finalFailureTimeout, PolicyResult.FAILURE_TIMEOUT, node);
163 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_retries(), finalFailureRetries, PolicyResult.FAILURE_RETRIES, node);
164 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_exception(), finalFailureException, PolicyResult.FAILURE_EXCEPTION, node);
165 addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_guard(), finalFailureGuard, PolicyResult.FAILURE_GUARD, node);
167 validateNodesAndEdges(graph, callback);
171 private static void validateOpenLoopPolicy(ControlLoopPolicy policy, FinalResult triggerResult, ControlLoopCompilerCallback callback) throws CompilerException{
173 // Ensure they didn't use some other FinalResult code
175 if (triggerResult != FinalResult.FINAL_OPENLOOP) {
176 throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
179 // They really shouldn't have any policies attached.
181 if ((policy.getPolicies() != null || policy.getPolicies().isEmpty())&& callback != null ) {
182 callback.onWarning("Open Loop policy contains policies. The policies will never be invoked.");
186 private static void validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException{
188 boolean triggerPolicyFound = false;
189 for (Policy operPolicy : policy.getPolicies()) {
190 sum += operPolicy.getTimeout().intValue();
191 if (policy.getControlLoop().getTrigger_policy().equals(operPolicy.getId())){
192 triggerPolicyFound = true;
195 if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) {
196 callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts.");
199 if (!triggerPolicyFound){
200 throw new CompilerException("Unexpected value for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
204 private static Map<Policy, PolicyNodeWrapper> addPoliciesAsNodes(ControlLoopPolicy policy,
205 DirectedGraph<NodeWrapper, LabeledEdge> graph, TriggerNodeWrapper triggerNode, ControlLoopCompilerCallback callback){
206 Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<>();
207 for (Policy operPolicy : policy.getPolicies()) {
209 // Is it still ok to add?
211 if (!okToAdd(operPolicy, callback)) {
218 // Create wrapper policy node and save it into our map so we can
219 // easily retrieve it.
221 PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy);
222 mapNodes.put(operPolicy, node);
223 graph.addVertex(node);
225 // Is this the trigger policy?
227 if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) {
229 // Yes add an edge from our trigger event node to this policy
231 graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET")));
237 private static void addEdge(DirectedGraph<NodeWrapper, LabeledEdge> graph, Map<Policy, PolicyNodeWrapper> mapNodes, String policyId, String connectedPolicy,
238 FinalResultNodeWrapper finalResultNodeWrapper, PolicyResult policyResult, NodeWrapper node) throws CompilerException{
239 FinalResult finalResult = FinalResult.toResult(finalResultNodeWrapper.getID());
240 if (FinalResult.isResult(connectedPolicy, finalResult)) {
241 graph.addEdge(node, finalResultNodeWrapper, new LabeledEdge(node, finalResultNodeWrapper, new FinalResultEdgeWrapper(finalResult)));
243 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, connectedPolicy);
244 if (toNode == null) {
245 throw new CompilerException(OPERATION_POLICY + policyId + " is connected to unknown policy " + connectedPolicy);
247 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(policyResult)));
252 private static void validateNodesAndEdges(DirectedGraph<NodeWrapper, LabeledEdge> graph, ControlLoopCompilerCallback callback) throws CompilerException{
253 for (NodeWrapper node : graph.vertexSet()) {
254 if (node instanceof TriggerNodeWrapper) {
255 validateTriggerNodeWrapper(graph, node);
256 } else if (node instanceof FinalResultNodeWrapper) {
257 validateFinalResultNodeWrapper(graph, node);
258 } else if (node instanceof PolicyNodeWrapper) {
259 validatePolicyNodeWrapper(graph, node, callback);
261 for (LabeledEdge edge : graph.outgoingEdgesOf(node)){
262 LOGGER.info(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID());
267 private static void validateTriggerNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph, NodeWrapper node) throws CompilerException{
268 if (LOGGER.isDebugEnabled()) {
269 LOGGER.info("Trigger Node {}", node.toString());
271 if (graph.inDegreeOf(node) > 0 ) {
273 // Really should NEVER get here unless someone messed up the code above.
275 throw new CompilerException("No inputs to event trigger");
278 // Should always be 1, except in the future we may support multiple events
280 if (graph.outDegreeOf(node) > 1) {
281 throw new CompilerException("The event trigger should only go to ONE node");
285 private static void validateFinalResultNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph, NodeWrapper node) throws CompilerException{
286 if (LOGGER.isDebugEnabled()) {
287 LOGGER.info("FinalResult Node {}", node.toString());
290 // FinalResult nodes should NEVER have an out edge
292 if (graph.outDegreeOf(node) > 0) {
293 throw new CompilerException("FinalResult nodes should never have any out edges.");
297 private static void validatePolicyNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph, NodeWrapper node, ControlLoopCompilerCallback callback) throws CompilerException{
298 if (LOGGER.isDebugEnabled()) {
299 LOGGER.info("Policy Node {}", node.toString());
302 // All Policy Nodes should have the 5 out degrees defined.
304 if (graph.outDegreeOf(node) != 6) {
305 throw new CompilerException("Policy node should ALWAYS have 6 out degrees.");
308 // All Policy Nodes should have at least 1 in degrees
310 if (graph.inDegreeOf(node) == 0 && callback != null) {
311 callback.onWarning("Policy " + node.getID() + " is not reachable.");
315 private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) {
316 boolean isOk = isPolicyIdOk(operPolicy, callback);
317 isOk = isActorOk(operPolicy, callback) ? isOk : false;
318 isOk = isRecipeOk(operPolicy, callback) ? isOk : false;
319 isOk = isTargetOk(operPolicy, callback) ? isOk : false;
320 isOk = arePolicyResultsOk(operPolicy, callback) ? isOk : false;
324 private static boolean isPolicyIdOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
326 if (operPolicy.getId() == null || operPolicy.getId().length() < 1) {
327 if (callback != null) {
328 callback.onError("Operational Policy has an bad ID");
333 // Check if they decided to make the ID a result object
335 if (PolicyResult.toResult(operPolicy.getId()) != null) {
336 if (callback != null) {
337 callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId());
341 if (FinalResult.toResult(operPolicy.getId()) != null) {
342 if (callback != null) {
343 callback.onError("Policy id is set to a FinalResult " + operPolicy.getId());
351 private static boolean isActorOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
353 if (operPolicy.getActor() == null) {
354 if (callback != null) {
355 callback.onError("Policy actor is null");
360 // Construct a list for all valid actors
362 ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI");
364 if (operPolicy.getActor() != null && (!actors.contains(operPolicy.getActor())) ) {
365 if (callback != null) {
366 callback.onError("Policy actor is invalid");
373 private static boolean isRecipeOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
375 if (operPolicy.getRecipe() == null) {
376 if (callback != null) {
377 callback.onError("Policy recipe is null");
382 // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these)
384 ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>()
385 .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig"))
386 .put("AOTS", ImmutableList.of("checkMaintenanceWindow", "checkENodeBTicketHours", "checkEquipmentStatus", "checkEimStatus", "checkEquipmentMaintenance"))
387 .put("MSO", ImmutableList.of("VF Module Create"))
388 .put("SDNO", ImmutableList.of("health-diagnostic-type", "health-diagnostic", "health-diagnostic-history", "health-diagnostic-commands", "health-diagnostic-aes"))
389 .put("SDNR", ImmutableList.of("Restart", "Reboot"))
392 if (operPolicy.getRecipe() != null && (!recipes.getOrDefault(operPolicy.getActor(), Collections.emptyList()).contains(operPolicy.getRecipe()))) {
393 if (callback != null) {
394 callback.onError("Policy recipe is invalid");
401 private static boolean isTargetOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
403 if (operPolicy.getTarget() == null) {
404 if (callback != null) {
405 callback.onError("Policy target is null");
409 if (operPolicy.getTarget() != null && operPolicy.getTarget().getType() != TargetType.VM && operPolicy.getTarget().getType() != TargetType.VFC && operPolicy.getTarget().getType() != TargetType.PNF) {
410 if (callback != null) {
411 callback.onError("Policy target is invalid");
418 private static boolean arePolicyResultsOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
420 // Check that policy results are connected to either default final * or another policy
422 boolean isOk = isSuccessPolicyResultOk(operPolicy, callback);
423 isOk = isFailurePolicyResultOk(operPolicy, callback) ? isOk : false;
424 isOk = isFailureRetriesPolicyResultOk(operPolicy, callback) ? isOk : false;
425 isOk = isFailureTimeoutPolicyResultOk(operPolicy, callback) ? isOk : false;
426 isOk = isFailureExceptionPolicyResultOk(operPolicy, callback) ? isOk : false;
427 isOk = isFailureGuardPolicyResultOk(operPolicy, callback) ? isOk : false;
431 private static boolean isSuccessPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){
433 if (FinalResult.toResult(operPolicy.getSuccess()) != null && !operPolicy.getSuccess().equals(FinalResult.FINAL_SUCCESS.toString())) {
434 if (callback != null) {
435 callback.onError("Policy success is neither another policy nor FINAL_SUCCESS");
442 private static boolean isFailurePolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){
444 if (FinalResult.toResult(operPolicy.getFailure()) != null && !operPolicy.getFailure().equals(FinalResult.FINAL_FAILURE.toString())) {
445 if (callback != null) {
446 callback.onError("Policy failure is neither another policy nor FINAL_FAILURE");
453 private static boolean isFailureRetriesPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){
455 if (FinalResult.toResult(operPolicy.getFailure_retries()) != null && !operPolicy.getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())) {
456 if (callback != null) {
457 callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES");
464 private static boolean isFailureTimeoutPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){
466 if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null && !operPolicy.getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())) {
467 if (callback != null) {
468 callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT");
475 private static boolean isFailureExceptionPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){
477 if (FinalResult.toResult(operPolicy.getFailure_exception()) != null && !operPolicy.getFailure_exception().equals(FinalResult.FINAL_FAILURE_EXCEPTION.toString())) {
478 if (callback != null) {
479 callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION");
486 private static boolean isFailureGuardPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){
488 if (FinalResult.toResult(operPolicy.getFailure_guard()) != null && !operPolicy.getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())) {
489 if (callback != null) {
490 callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD");
497 private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) {
498 for (Entry<Policy, PolicyNodeWrapper> entry : mapNodes.entrySet()) {
499 if (entry.getKey().getId().equals(id)) {
500 return entry.getValue();
507 private interface NodeWrapper extends Serializable{
508 public String getID();
511 private static class TriggerNodeWrapper implements NodeWrapper {
512 private static final long serialVersionUID = -187644087811478349L;
513 private String closedLoopControlName;
515 public TriggerNodeWrapper(String closedLoopControlName) {
516 this.closedLoopControlName = closedLoopControlName;
520 public String toString() {
521 return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]";
525 public String getID() {
526 return closedLoopControlName;
531 private static class FinalResultNodeWrapper implements NodeWrapper {
532 private static final long serialVersionUID = 8540008796302474613L;
533 private FinalResult result;
535 public FinalResultNodeWrapper(FinalResult result) {
536 this.result = result;
540 public String toString() {
541 return "FinalResultNodeWrapper [result=" + result + "]";
545 public String getID() {
546 return result.toString();
550 private static class PolicyNodeWrapper implements NodeWrapper {
551 private static final long serialVersionUID = 8170162175653823082L;
552 private transient Policy policy;
554 public PolicyNodeWrapper(Policy operPolicy) {
555 this.policy = operPolicy;
559 public String toString() {
560 return "PolicyNodeWrapper [policy=" + policy + "]";
564 public String getID() {
565 return policy.getId();
570 private interface EdgeWrapper extends Serializable{
571 public String getID();
575 private static class TriggerEdgeWrapper implements EdgeWrapper {
576 private static final long serialVersionUID = 2678151552623278863L;
577 private String trigger;
579 public TriggerEdgeWrapper(String trigger) {
580 this.trigger = trigger;
584 public String getID() {
589 public String toString() {
590 return "TriggerEdgeWrapper [trigger=" + trigger + "]";
595 private static class PolicyResultEdgeWrapper implements EdgeWrapper {
596 private static final long serialVersionUID = 6078569477021558310L;
597 private PolicyResult policyResult;
599 public PolicyResultEdgeWrapper(PolicyResult policyResult) {
601 this.policyResult = policyResult;
605 public String toString() {
606 return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]";
610 public String getID() {
611 return policyResult.toString();
617 private static class FinalResultEdgeWrapper implements EdgeWrapper {
618 private static final long serialVersionUID = -1486381946896779840L;
619 private FinalResult finalResult;
620 public FinalResultEdgeWrapper(FinalResult result) {
621 this.finalResult = result;
625 public String toString() {
626 return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]";
630 public String getID() {
631 return finalResult.toString();
636 private static class LabeledEdge extends DefaultEdge {
637 private static final long serialVersionUID = 579384429573385524L;
639 private NodeWrapper from;
640 private NodeWrapper to;
641 private EdgeWrapper edge;
643 public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) {
649 @SuppressWarnings("unused")
650 public NodeWrapper from() {
654 @SuppressWarnings("unused")
655 public NodeWrapper to() {
659 @SuppressWarnings("unused")
660 public EdgeWrapper edge() {
665 public String toString() {
666 return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]";