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.openecomp.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.openecomp.policy.controlloop.policy.ControlLoop;
34 import org.openecomp.policy.controlloop.policy.ControlLoopPolicy;
35 import org.openecomp.policy.controlloop.policy.FinalResult;
36 import org.openecomp.policy.controlloop.policy.Policy;
37 import org.openecomp.policy.controlloop.policy.PolicyResult;
38 import org.openecomp.policy.controlloop.policy.TargetType;
39 import org.yaml.snakeyaml.Yaml;
40 import org.yaml.snakeyaml.constructor.Constructor;
42 import com.google.common.collect.ImmutableList;
43 import com.google.common.collect.ImmutableMap;
45 public class ControlLoopCompiler {
47 public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException {
49 // Ensure the control loop is sane
51 validateControlLoop(policy.controlLoop, callback);
53 // Validate the policies
55 validatePolicies(policy, callback);
59 public static ControlLoopPolicy compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException {
60 Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
61 Object obj = yaml.load(yamlSpecification);
63 throw new CompilerException("Could not parse yaml specification.");
65 if (! (obj instanceof ControlLoopPolicy)) {
66 throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object");
68 return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback);
71 private static void validateControlLoop(ControlLoop controlLoop, ControlLoopCompilerCallback callback) throws CompilerException {
72 if (controlLoop == null) {
73 if (callback != null) {
74 callback.onError("controlLoop cannot be null");
77 if (controlLoop.controlLoopName == null | controlLoop.controlLoopName.length() < 1) {
78 if (callback != null) {
79 callback.onError("Missing controlLoopName");
82 if (! controlLoop.version.contentEquals(ControlLoop.VERSION)) {
83 if (callback != null) {
84 callback.onError("Unsupported version for this compiler");
87 if (controlLoop.trigger_policy == null || controlLoop.trigger_policy.length() < 1) {
88 throw new CompilerException("trigger_policy is not valid");
93 private static void validatePolicies(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException {
95 throw new CompilerException("policy cannot be null");
98 // verify controlLoop overall timeout should be no less than the sum of operational policy timeouts
100 if (policy.policies == null) {
101 callback.onWarning("controlLoop is an open loop.");
105 for (Policy operPolicy : policy.policies) {
106 sum += operPolicy.timeout.intValue();
108 if (policy.controlLoop.timeout.intValue() < sum) {
109 if (callback != null) {
110 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<NodeWrapper, LabeledEdge>(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.controlLoop.trigger_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.policies != null || policy.policies.size() > 0) {
138 if (callback != null) {
139 callback.onWarning("Open Loop policy contains policies. The policies will never be invoked.");
146 // Ok, not a FinalResult object so let's assume that it is a Policy. Which it should be.
148 triggerNode = new TriggerNodeWrapper(policy.controlLoop.controlLoopName);
151 // Add in the trigger node
153 graph.addVertex(triggerNode);
155 // Add in our Final Result nodes. All paths should end to these nodes.
157 FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS);
158 FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE);
159 FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT);
160 FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES);
161 FinalResultNodeWrapper finalFailureException = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION);
162 FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD);
163 graph.addVertex(finalSuccess);
164 graph.addVertex(finalFailure);
165 graph.addVertex(finalFailureTimeout);
166 graph.addVertex(finalFailureRetries);
167 graph.addVertex(finalFailureException);
168 graph.addVertex(finalFailureGuard);
170 // Work through the policies and add them in as nodes.
172 Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<Policy, PolicyNodeWrapper>();
173 for (Policy operPolicy : policy.policies) {
175 // Check the policy id and make sure its sane
177 boolean okToAdd = true;
178 if (operPolicy.id == null || operPolicy.id.length() < 1) {
179 if (callback != null) {
180 callback.onError("Operational Policy has an bad ID");
185 // Check if they decided to make the ID a result object
187 if (PolicyResult.toResult(operPolicy.id) != null) {
188 if (callback != null) {
189 callback.onError("Policy id is set to a PolicyResult " + operPolicy.id);
193 if (FinalResult.toResult(operPolicy.id) != null) {
194 if (callback != null) {
195 callback.onError("Policy id is set to a FinalResult " + operPolicy.id);
200 // Check that the actor/recipe/target are valid
202 if (operPolicy.actor == null) {
203 if (callback != null) {
204 callback.onError("Policy actor is null");
209 // Construct a list for all valid actors
211 ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI");
213 if (operPolicy.actor != null && (!actors.contains(operPolicy.actor)) ) {
214 if (callback != null) {
215 callback.onError("Policy actor is invalid");
219 if (operPolicy.recipe == null) {
220 if (callback != null) {
221 callback.onError("Policy recipe is null");
227 // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these)
229 ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>()
230 .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig"))
231 .put("AOTS", ImmutableList.of("checkMaintenanceWindow", "checkENodeBTicketHours", "checkEquipmentStatus", "checkEimStatus", "checkEquipmentMaintenance"))
232 .put("MSO", ImmutableList.of("VF Module Create"))
233 .put("SDNO", ImmutableList.of("health-diagnostic-type", "health-diagnostic", "health-diagnostic-history", "health-diagnostic-commands", "health-diagnostic-aes"))
234 .put("SDNR", ImmutableList.of("Restart", "Reboot"))
237 if (operPolicy.recipe != null && (!recipes.getOrDefault(operPolicy.actor, Collections.emptyList()).contains(operPolicy.recipe))) {
238 if (callback != null) {
239 callback.onError("Policy recipe is invalid");
243 if (operPolicy.target == null) {
244 if (callback != null) {
245 callback.onError("Policy target is null");
249 if (operPolicy.target != null && operPolicy.target.type != TargetType.VM && operPolicy.target.type != TargetType.VFC && operPolicy.target.type != TargetType.PNF) {
250 if (callback != null) {
251 callback.onError("Policy target is invalid");
256 // Check that policy results are connected to either default final * or another policy
258 if (FinalResult.toResult(operPolicy.success) != null && operPolicy.success != FinalResult.FINAL_SUCCESS.toString()) {
259 if (callback != null) {
260 callback.onError("Policy success is neither another policy nor FINAL_SUCCESS");
264 if (FinalResult.toResult(operPolicy.failure) != null && operPolicy.failure != FinalResult.FINAL_FAILURE.toString()) {
265 if (callback != null) {
266 callback.onError("Policy failure is neither another policy nor FINAL_FAILURE");
270 if (FinalResult.toResult(operPolicy.failure_retries) != null && operPolicy.failure_retries != FinalResult.FINAL_FAILURE_RETRIES.toString()) {
271 if (callback != null) {
272 callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES");
276 if (FinalResult.toResult(operPolicy.failure_timeout) != null && operPolicy.failure_timeout != FinalResult.FINAL_FAILURE_TIMEOUT.toString()) {
277 if (callback != null) {
278 callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT");
282 if (FinalResult.toResult(operPolicy.failure_exception) != null && operPolicy.failure_exception != FinalResult.FINAL_FAILURE_EXCEPTION.toString()) {
283 if (callback != null) {
284 callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION");
288 if (FinalResult.toResult(operPolicy.failure_guard) != null && operPolicy.failure_guard != FinalResult.FINAL_FAILURE_GUARD.toString()) {
289 if (callback != null) {
290 callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD");
295 // Is it still ok to add?
297 if (okToAdd == false) {
304 // Create wrapper policy node and save it into our map so we can
305 // easily retrieve it.
307 PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy);
308 mapNodes.put(operPolicy, node);
309 graph.addVertex(node);
311 // Is this the trigger policy?
313 if (operPolicy.id.equals(policy.controlLoop.trigger_policy)) {
315 // Yes add an edge from our trigger event node to this policy
317 graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET")));
321 // last sweep to connect remaining edges for policy results
323 for (Policy operPolicy : policy.policies) {
324 PolicyNodeWrapper node = mapNodes.get(operPolicy);
326 // Just ensure this has something
331 if (FinalResult.isResult(operPolicy.success, FinalResult.FINAL_SUCCESS)) {
332 graph.addEdge(node, finalSuccess, new LabeledEdge(node, finalSuccess, new FinalResultEdgeWrapper(FinalResult.FINAL_SUCCESS)));
334 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.success);
335 if (toNode == null) {
336 throw new CompilerException("Operation Policy " + operPolicy.id + " success is connected to unknown policy " + operPolicy.success);
338 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.SUCCESS)));
341 if (FinalResult.isResult(operPolicy.failure, FinalResult.FINAL_FAILURE)) {
342 graph.addEdge(node, finalFailure, new LabeledEdge(node, finalFailure, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE)));
344 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure);
345 if (toNode == null) {
346 throw new CompilerException("Operation Policy " + operPolicy.id + " failure is connected to unknown policy " + operPolicy.failure);
348 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE)));
351 if (FinalResult.isResult(operPolicy.failure_timeout, FinalResult.FINAL_FAILURE_TIMEOUT)) {
352 graph.addEdge(node, finalFailureTimeout, new LabeledEdge(node, finalFailureTimeout, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT)));
354 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_timeout);
355 if (toNode == null) {
356 throw new CompilerException("Operation Policy " + operPolicy.id + " failure_timeout is connected to unknown policy " + operPolicy.failure_timeout);
358 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_TIMEOUT)));
361 if (FinalResult.isResult(operPolicy.failure_retries, FinalResult.FINAL_FAILURE_RETRIES)) {
362 graph.addEdge(node, finalFailureRetries, new LabeledEdge(node, finalFailureRetries, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_RETRIES)));
364 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_retries);
365 if (toNode == null) {
366 throw new CompilerException("Operation Policy " + operPolicy.id + " failure_retries is connected to unknown policy " + operPolicy.failure_retries);
368 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_RETRIES)));
371 if (FinalResult.isResult(operPolicy.failure_exception, FinalResult.FINAL_FAILURE_EXCEPTION)) {
372 graph.addEdge(node, finalFailureException, new LabeledEdge(node, finalFailureException, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION)));
374 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_exception);
375 if (toNode == null) {
376 throw new CompilerException("Operation Policy " + operPolicy.id + " failure_exception is connected to unknown policy " + operPolicy.failure_exception);
378 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_EXCEPTION)));
381 if (FinalResult.isResult(operPolicy.failure_guard, FinalResult.FINAL_FAILURE_GUARD)) {
382 graph.addEdge(node, finalFailureGuard, new LabeledEdge(node, finalFailureGuard, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_GUARD)));
384 PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_guard);
385 if (toNode == null) {
386 throw new CompilerException("Operation Policy " + operPolicy.id + " failure_guard is connected to unknown policy " + operPolicy.failure_guard);
388 graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_GUARD)));
393 // Now validate all the nodes/edges
395 for (NodeWrapper node : graph.vertexSet()) {
396 if (node instanceof TriggerNodeWrapper) {
397 System.out.println("Trigger Node " + node.toString());
398 if (graph.inDegreeOf(node) > 0 ) {
400 // Really should NEVER get here unless someone messed up the code above.
402 throw new CompilerException("No inputs to event trigger");
405 // Should always be 1, except in the future we may support multiple events
407 if (graph.outDegreeOf(node) > 1) {
408 throw new CompilerException("The event trigger should only go to ONE node");
410 } else if (node instanceof FinalResultNodeWrapper) {
411 System.out.println("FinalResult Node " + node.toString());
413 // FinalResult nodes should NEVER have an out edge
415 if (graph.outDegreeOf(node) > 0) {
416 throw new CompilerException("FinalResult nodes should never have any out edges.");
418 } else if (node instanceof PolicyNodeWrapper) {
419 System.out.println("Policy Node " + node.toString());
421 // All Policy Nodes should have the 5 out degrees defined.
423 if (graph.outDegreeOf(node) != 6) {
424 throw new CompilerException("Policy node should ALWAYS have 6 out degrees.");
427 // Chenfei: All Policy Nodes should have at least 1 in degrees
429 if (graph.inDegreeOf(node) == 0) {
430 if (callback != null) {
431 callback.onWarning("Policy " + node.getID() + " is not reachable.");
435 for (LabeledEdge edge : graph.outgoingEdgesOf(node)){
436 System.out.println(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID());
442 private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) {
443 for (Policy key : mapNodes.keySet()) {
444 if (key.id.equals(id)) {
445 return mapNodes.get(key);
451 private interface NodeWrapper {
453 public String getID();
457 private static class TriggerNodeWrapper implements NodeWrapper {
458 public String closedLoopControlName;
460 public TriggerNodeWrapper(String closedLoopControlName) {
461 this.closedLoopControlName = closedLoopControlName;
465 public String toString() {
466 return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]";
470 public String getID() {
471 return closedLoopControlName;
476 private static class FinalResultNodeWrapper implements NodeWrapper {
478 public FinalResult result;
480 public FinalResultNodeWrapper(FinalResult result) {
481 this.result = result;
485 public String toString() {
486 return "FinalResultNodeWrapper [result=" + result + "]";
490 public String getID() {
491 return result.toString();
495 private static class PolicyNodeWrapper implements NodeWrapper {
497 public Policy policy;
499 public PolicyNodeWrapper(Policy operPolicy) {
500 this.policy = operPolicy;
504 public String toString() {
505 return "PolicyNodeWrapper [policy=" + policy + "]";
509 public String getID() {
514 private interface EdgeWrapper {
516 public String getID();
520 private static class TriggerEdgeWrapper implements EdgeWrapper {
522 private String trigger;
524 public TriggerEdgeWrapper(String trigger) {
525 this.trigger = trigger;
529 public String getID() {
534 public String toString() {
535 return "TriggerEdgeWrapper [trigger=" + trigger + "]";
540 private static class PolicyResultEdgeWrapper implements EdgeWrapper {
541 public 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 {
563 public 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 {
585 private static final long serialVersionUID = 579384429573385524L;
587 private NodeWrapper from;
588 private NodeWrapper to;
589 private EdgeWrapper edge;
591 public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) {
597 @SuppressWarnings("unused")
598 public NodeWrapper from() {
602 @SuppressWarnings("unused")
603 public NodeWrapper to() {
607 @SuppressWarnings("unused")
608 public EdgeWrapper edge() {
613 public String toString() {
614 return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]";