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 long serialVersionUID = 1L;
51 private static Logger LOGGER = LoggerFactory.getLogger(ControlLoopCompiler.class.getName());
53 public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException {
55 // Ensure the control loop is sane
57 validateControlLoop(policy.getControlLoop(), callback);
59 // Validate the policies
61 validatePolicies(policy, callback);
66 public static ControlLoopPolicy compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException {
67 Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
68 Object obj = yaml.load(yamlSpecification);
70 throw new CompilerException("Could not parse yaml specification.");
72 if (! (obj instanceof ControlLoopPolicy)) {
73 throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object");
75 return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback);
78 private static void validateControlLoop(ControlLoop controlLoop, ControlLoopCompilerCallback callback) throws CompilerException {
79 if (controlLoop == null && callback != null) {
80 callback.onError("controlLoop cannot be null");
82 if (controlLoop!=null){
83 if ((controlLoop.getControlLoopName() == null || controlLoop.getControlLoopName().length() < 1) && callback != null) {
84 callback.onError("Missing controlLoopName");
86 if ((!controlLoop.getVersion().contentEquals(ControlLoop.getVERSION())) && callback != null) {
87 callback.onError("Unsupported version for this compiler");
89 if (controlLoop.getTrigger_policy() == null || controlLoop.getTrigger_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 // verify controlLoop overall timeout should be no less than the sum of operational policy timeouts
102 if (policy.getPolicies() == null) {
103 callback.onWarning("controlLoop is an open loop.");
107 for (Policy operPolicy : policy.getPolicies()) {
108 sum += operPolicy.getTimeout().intValue();
110 if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) {
111 callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts.");
114 // For this version we can use a directed multigraph, in the future we may not be able to
116 DirectedGraph<NodeWrapper, LabeledEdge> graph = new DirectedMultigraph<>(new ClassBasedEdgeFactory<NodeWrapper, LabeledEdge>(LabeledEdge.class));
118 // Check to see if the trigger Event is for OpenLoop, we do so by
119 // attempting to create a FinalResult object from it. If its a policy id, this should
122 FinalResult triggerResult = FinalResult.toResult(policy.getControlLoop().getTrigger_policy());
123 TriggerNodeWrapper triggerNode;
125 // Did this turn into a FinalResult object?
127 if (triggerResult != null) {
129 // Ensure they didn't use some other FinalResult code
131 if (triggerResult != FinalResult.FINAL_OPENLOOP) {
132 throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
135 // They really shouldn't have any policies attached.
137 if ((policy.getPolicies() != null || policy.getPolicies().isEmpty())&& callback != null ) {
138 callback.onWarning("Open Loop policy contains policies. The policies will never be invoked.");
144 // Ok, not a FinalResult object so let's assume that it is a Policy. Which it should be.
146 triggerNode = new TriggerNodeWrapper(policy.getControlLoop().getControlLoopName());
149 // Add in the trigger node
151 graph.addVertex(triggerNode);
153 // Add in our Final Result nodes. All paths should end to these nodes.
155 FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS);
156 FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE);
157 FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT);
158 FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES);
159 FinalResultNodeWrapper finalFailureException = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION);
160 FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD);
161 graph.addVertex(finalSuccess);
162 graph.addVertex(finalFailure);
163 graph.addVertex(finalFailureTimeout);
164 graph.addVertex(finalFailureRetries);
165 graph.addVertex(finalFailureException);
166 graph.addVertex(finalFailureGuard);
168 // Work through the policies and add them in as nodes.
170 Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<>();
171 for (Policy operPolicy : policy.getPolicies()) {
173 // Is it still ok to add?
175 if (!okToAdd(operPolicy, callback)) {
182 // Create wrapper policy node and save it into our map so we can
183 // easily retrieve it.
185 PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy);
186 mapNodes.put(operPolicy, node);
187 graph.addVertex(node);
189 // Is this the trigger policy?
191 if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) {
193 // Yes add an edge from our trigger event node to this policy
195 graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET")));
199 // last sweep to connect remaining edges for policy results
201 for (Policy operPolicy : policy.getPolicies()) {
202 PolicyNodeWrapper node = mapNodes.get(operPolicy);
204 // Just ensure this has something
209 if (FinalResult.isResult(operPolicy.getSuccess(), FinalResult.FINAL_SUCCESS)) {
210 graph.addEdge(node, finalSuccess, new LabeledEdge(node, finalSuccess, new FinalResultEdgeWrapper(FinalResult.FINAL_SUCCESS)));
212 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getSuccess());
213 if (toNode == null) {
214 throw new CompilerException("Operation Policy " + operPolicy.getId() + " success is connected to unknown policy " + operPolicy.getSuccess());
216 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.SUCCESS)));
219 if (FinalResult.isResult(operPolicy.getFailure(), FinalResult.FINAL_FAILURE)) {
220 graph.addEdge(node, finalFailure, new LabeledEdge(node, finalFailure, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE)));
222 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure());
223 if (toNode == null) {
224 throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure is connected to unknown policy " + operPolicy.getFailure());
226 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE)));
229 if (FinalResult.isResult(operPolicy.getFailure_timeout(), FinalResult.FINAL_FAILURE_TIMEOUT)) {
230 graph.addEdge(node, finalFailureTimeout, new LabeledEdge(node, finalFailureTimeout, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT)));
232 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_timeout());
233 if (toNode == null) {
234 throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_timeout is connected to unknown policy " + operPolicy.getFailure_timeout());
236 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_TIMEOUT)));
239 if (FinalResult.isResult(operPolicy.getFailure_retries(), FinalResult.FINAL_FAILURE_RETRIES)) {
240 graph.addEdge(node, finalFailureRetries, new LabeledEdge(node, finalFailureRetries, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_RETRIES)));
242 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_retries());
243 if (toNode == null) {
244 throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_retries is connected to unknown policy " + operPolicy.getFailure_retries());
246 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_RETRIES)));
249 if (FinalResult.isResult(operPolicy.getFailure_exception(), FinalResult.FINAL_FAILURE_EXCEPTION)) {
250 graph.addEdge(node, finalFailureException, new LabeledEdge(node, finalFailureException, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION)));
252 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_exception());
253 if (toNode == null) {
254 throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_exception is connected to unknown policy " + operPolicy.getFailure_exception());
256 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_EXCEPTION)));
259 if (FinalResult.isResult(operPolicy.getFailure_guard(), FinalResult.FINAL_FAILURE_GUARD)) {
260 graph.addEdge(node, finalFailureGuard, new LabeledEdge(node, finalFailureGuard, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_GUARD)));
262 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_guard());
263 if (toNode == null) {
264 throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_guard is connected to unknown policy " + operPolicy.getFailure_guard());
266 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_GUARD)));
271 // Now validate all the nodes/edges
273 for (NodeWrapper node : graph.vertexSet()) {
274 if (node instanceof TriggerNodeWrapper) {
275 LOGGER.info("Trigger Node " + node.toString());
276 if (graph.inDegreeOf(node) > 0 ) {
278 // Really should NEVER get here unless someone messed up the code above.
280 throw new CompilerException("No inputs to event trigger");
283 // Should always be 1, except in the future we may support multiple events
285 if (graph.outDegreeOf(node) > 1) {
286 throw new CompilerException("The event trigger should only go to ONE node");
288 } else if (node instanceof FinalResultNodeWrapper) {
289 LOGGER.info("FinalResult Node " + node.toString());
291 // FinalResult nodes should NEVER have an out edge
293 if (graph.outDegreeOf(node) > 0) {
294 throw new CompilerException("FinalResult nodes should never have any out edges.");
296 } else if (node instanceof PolicyNodeWrapper) {
297 LOGGER.info("Policy Node " + node.toString());
299 // All Policy Nodes should have the 5 out degrees defined.
301 if (graph.outDegreeOf(node) != 6) {
302 throw new CompilerException("Policy node should ALWAYS have 6 out degrees.");
305 // All Policy Nodes should have at least 1 in degrees
307 if (graph.inDegreeOf(node) == 0 && callback != null) {
308 callback.onWarning("Policy " + node.getID() + " is not reachable.");
311 for (LabeledEdge edge : graph.outgoingEdgesOf(node)){
312 LOGGER.info(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID());
318 private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) {
320 // Check the policy id and make sure its sane
322 boolean okToAdd = true;
323 if (operPolicy.getId() == null || operPolicy.getId().length() < 1) {
324 if (callback != null) {
325 callback.onError("Operational Policy has an bad ID");
330 // Check if they decided to make the ID a result object
332 if (PolicyResult.toResult(operPolicy.getId()) != null) {
333 if (callback != null) {
334 callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId());
338 if (FinalResult.toResult(operPolicy.getId()) != null) {
339 if (callback != null) {
340 callback.onError("Policy id is set to a FinalResult " + operPolicy.getId());
345 // Check that the actor/recipe/target are valid
347 if (operPolicy.getActor() == null) {
348 if (callback != null) {
349 callback.onError("Policy actor is null");
354 // Construct a list for all valid actors
356 ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI");
358 if (operPolicy.getActor() != null && (!actors.contains(operPolicy.getActor())) ) {
359 if (callback != null) {
360 callback.onError("Policy actor is invalid");
364 if (operPolicy.getRecipe() == null) {
365 if (callback != null) {
366 callback.onError("Policy recipe is null");
371 // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these)
373 ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>()
374 .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig"))
375 .put("AOTS", ImmutableList.of("checkMaintenanceWindow", "checkENodeBTicketHours", "checkEquipmentStatus", "checkEimStatus", "checkEquipmentMaintenance"))
376 .put("MSO", ImmutableList.of("VF Module Create"))
377 .put("SDNO", ImmutableList.of("health-diagnostic-type", "health-diagnostic", "health-diagnostic-history", "health-diagnostic-commands", "health-diagnostic-aes"))
378 .put("SDNR", ImmutableList.of("Restart", "Reboot"))
381 if (operPolicy.getRecipe() != null && (!recipes.getOrDefault(operPolicy.getActor(), Collections.emptyList()).contains(operPolicy.getRecipe()))) {
382 if (callback != null) {
383 callback.onError("Policy recipe is invalid");
387 if (operPolicy.getTarget() == null) {
388 if (callback != null) {
389 callback.onError("Policy target is null");
393 if (operPolicy.getTarget() != null && operPolicy.getTarget().getType() != TargetType.VM && operPolicy.getTarget().getType() != TargetType.VFC && operPolicy.getTarget().getType() != TargetType.PNF) {
394 if (callback != null) {
395 callback.onError("Policy target is invalid");
400 // Check that policy results are connected to either default final * or another policy
402 if (FinalResult.toResult(operPolicy.getSuccess()) != null && operPolicy.getSuccess() != FinalResult.FINAL_SUCCESS.toString()) {
403 if (callback != null) {
404 callback.onError("Policy success is neither another policy nor FINAL_SUCCESS");
408 if (FinalResult.toResult(operPolicy.getFailure()) != null && operPolicy.getFailure() != FinalResult.FINAL_FAILURE.toString()) {
409 if (callback != null) {
410 callback.onError("Policy failure is neither another policy nor FINAL_FAILURE");
414 if (FinalResult.toResult(operPolicy.getFailure_retries()) != null && operPolicy.getFailure_retries() != FinalResult.FINAL_FAILURE_RETRIES.toString()) {
415 if (callback != null) {
416 callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES");
420 if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null && operPolicy.getFailure_timeout() != FinalResult.FINAL_FAILURE_TIMEOUT.toString()) {
421 if (callback != null) {
422 callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT");
426 if (FinalResult.toResult(operPolicy.getFailure_exception()) != null && operPolicy.getFailure_exception() != FinalResult.FINAL_FAILURE_EXCEPTION.toString()) {
427 if (callback != null) {
428 callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION");
432 if (FinalResult.toResult(operPolicy.getFailure_guard()) != null && operPolicy.getFailure_guard() != FinalResult.FINAL_FAILURE_GUARD.toString()) {
433 if (callback != null) {
434 callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD");
441 private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) {
442 for (Entry<Policy, PolicyNodeWrapper> entry : mapNodes.entrySet()) {
443 if (entry.getKey().getId().equals(id)) {
444 return entry.getValue();
451 private interface NodeWrapper extends Serializable{
452 public String getID();
455 private static class TriggerNodeWrapper implements NodeWrapper {
456 private static final long serialVersionUID = -187644087811478349L;
457 private String closedLoopControlName;
459 public TriggerNodeWrapper(String closedLoopControlName) {
460 this.closedLoopControlName = closedLoopControlName;
464 public String toString() {
465 return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]";
469 public String getID() {
470 return closedLoopControlName;
475 private static class FinalResultNodeWrapper implements NodeWrapper {
476 private static final long serialVersionUID = 8540008796302474613L;
477 private FinalResult result;
479 public FinalResultNodeWrapper(FinalResult result) {
480 this.result = result;
484 public String toString() {
485 return "FinalResultNodeWrapper [result=" + result + "]";
489 public String getID() {
490 return result.toString();
494 private static class PolicyNodeWrapper implements NodeWrapper {
495 private static final long serialVersionUID = 8170162175653823082L;
496 private Policy policy;
498 public PolicyNodeWrapper(Policy operPolicy) {
499 this.policy = operPolicy;
503 public String toString() {
504 return "PolicyNodeWrapper [policy=" + policy + "]";
508 public String getID() {
509 return policy.getId();
514 private interface EdgeWrapper extends Serializable{
515 public String getID();
519 private static class TriggerEdgeWrapper implements EdgeWrapper {
520 private static final long serialVersionUID = 2678151552623278863L;
521 private String trigger;
523 public TriggerEdgeWrapper(String trigger) {
524 this.trigger = trigger;
528 public String getID() {
533 public String toString() {
534 return "TriggerEdgeWrapper [trigger=" + trigger + "]";
539 private static class PolicyResultEdgeWrapper implements EdgeWrapper {
540 private static final long serialVersionUID = 6078569477021558310L;
541 private PolicyResult policyResult;
543 public PolicyResultEdgeWrapper(PolicyResult policyResult) {
545 this.policyResult = policyResult;
549 public String toString() {
550 return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]";
554 public String getID() {
555 return policyResult.toString();
561 private static class FinalResultEdgeWrapper implements EdgeWrapper {
562 private static final long serialVersionUID = -1486381946896779840L;
563 private FinalResult finalResult;
564 public FinalResultEdgeWrapper(FinalResult result) {
565 this.finalResult = result;
569 public String toString() {
570 return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]";
574 public String getID() {
575 return finalResult.toString();
580 private static class LabeledEdge extends DefaultEdge {
581 private static final long serialVersionUID = 579384429573385524L;
583 private NodeWrapper from;
584 private NodeWrapper to;
585 private EdgeWrapper edge;
587 public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) {
593 @SuppressWarnings("unused")
594 public NodeWrapper from() {
598 @SuppressWarnings("unused")
599 public NodeWrapper to() {
603 @SuppressWarnings("unused")
604 public EdgeWrapper edge() {
609 public String toString() {
610 return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]";