18c80eed3f12026806b919bac0fd4ea6c4d3db80
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * policy-yaml
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.controlloop.policy.builder.impl;
22
23 import java.util.LinkedList;
24 import java.util.Map;
25 import java.util.UUID;
26
27 import org.onap.policy.aai.PNF;
28 import org.onap.policy.controlloop.compiler.CompilerException;
29 import org.onap.policy.controlloop.compiler.ControlLoopCompiler;
30 import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback;
31 import org.onap.policy.controlloop.policy.ControlLoop;
32 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
33 import org.onap.policy.controlloop.policy.FinalResult;
34 import org.onap.policy.controlloop.policy.OperationsAccumulateParams;
35 import org.onap.policy.controlloop.policy.Policy;
36 import org.onap.policy.controlloop.policy.PolicyResult;
37 import org.onap.policy.controlloop.policy.Target;
38 import org.onap.policy.controlloop.policy.builder.BuilderException;
39 import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder;
40 import org.onap.policy.controlloop.policy.builder.MessageLevel;
41 import org.onap.policy.controlloop.policy.builder.Results;
42 import org.onap.policy.sdc.Resource;
43 import org.onap.policy.sdc.Service;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.yaml.snakeyaml.DumperOptions;
47 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
48 import org.yaml.snakeyaml.Yaml;
49
50 public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder {
51     private static Logger logger = LoggerFactory.getLogger(ControlLoopPolicyBuilderImpl.class.getName());
52     private ControlLoopPolicy policy;
53     
54     public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) throws BuilderException {
55         policy = new ControlLoopPolicy();
56         ControlLoop controlLoop = new ControlLoop();
57         controlLoop.setControlLoopName(controlLoopName);
58         controlLoop.setTimeout(timeout);
59         policy.setControlLoop(controlLoop);
60     }
61     
62     public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException {
63         this(controlLoopName, timeout);
64         this.addResource(resource);
65         this.addService(services);
66     }
67     
68     public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, PNF pnf) throws BuilderException {
69         this(controlLoopName, timeout);
70         this.setPNF(pnf);
71     }
72     
73     public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Service service, Resource[] resources) throws BuilderException {
74         this(controlLoopName, timeout);
75         this.addService(service);
76         this.addResource(resources);
77     }
78     
79     @Override
80     public ControlLoopPolicyBuilder removePNF() throws BuilderException {
81         policy.getControlLoop().setPnf(null);
82         return this;
83     }
84
85     @Override
86     public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException {
87         if (services == null) {
88             throw new BuilderException("Service must not be null");
89         }
90         for (Service service : services) {
91             if (service.getServiceUUID() == null) {
92                 if (service.getServiceName() == null || service.getServiceName().length() < 1) {
93                     throw new BuilderException("Invalid service - need either a serviceUUID or serviceName");
94                 }
95                 if(policy.getControlLoop().getServices()==null){
96                     policy.getControlLoop().setServices(new LinkedList<>());
97                 }
98                 policy.getControlLoop().getServices().add(service);
99             }
100         }
101         return this;
102     }
103     
104     @Override
105     public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException {
106         if (services == null) {
107             throw new BuilderException("Service must not be null");
108         }
109         if (policy.getControlLoop().getServices() == null) {
110             throw new BuilderException("No existing services to remove");
111         }
112         for (Service service : services) {
113             if (service.getServiceUUID() == null) {
114                 if (service.getServiceName() == null || service.getServiceName().length() < 1) {
115                     throw new BuilderException("Invalid service - need either a serviceUUID or serviceName");
116                 }
117             }
118             boolean removed = policy.getControlLoop().getServices().remove(service);
119             if (!removed) {
120                 throw new BuilderException("Unknown service " + service.getServiceName());
121             }
122         }
123         return this;
124     }
125
126     @Override
127     public ControlLoopPolicyBuilder removeAllServices() throws BuilderException {
128         policy.getControlLoop().getServices().clear();
129         return this;
130     }
131
132     
133     @Override
134     public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException {
135         if (resources == null) {
136             throw new BuilderException("resources must not be null");
137         }
138         for (Resource resource : resources) {
139             if (resource.getResourceUUID() == null) {
140                 if (resource.getResourceName() == null || resource.getResourceName().length() <= 0) {
141                     throw new BuilderException("Invalid resource - need either resourceUUID or resourceName");
142                 }
143             }
144             if(policy.getControlLoop().getResources()==null){
145                 policy.getControlLoop().setResources(new LinkedList<>());
146             }
147             policy.getControlLoop().getResources().add(resource);
148         }
149         return this;
150     }
151     
152     @Override
153     public ControlLoopPolicyBuilder setPNF(PNF pnf) throws BuilderException {
154         if (pnf == null) {
155             throw new BuilderException("PNF must not be null");
156         }
157         if (pnf.PNFName == null) {
158             if (pnf.PNFType == null) {
159                 throw new BuilderException("Invalid PNF - need either pnfName or pnfType");
160             }
161         }
162         policy.getControlLoop().setPnf(pnf);
163         return this;
164     }
165     
166     @Override
167     public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException{
168         if (abatement == null) {
169             throw new BuilderException("abatement must not be null");
170         }
171         policy.getControlLoop().setAbatement(abatement);
172         return this;
173     }
174     
175     @Override
176     public ControlLoopPolicyBuilder setTimeout(Integer timeout) {
177         policy.getControlLoop().setTimeout(timeout);
178         return this;
179     }
180     
181     @Override
182     public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe,
183             Map<String, String> payload, Integer retries, Integer timeout) throws BuilderException {
184         
185         Policy trigger = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout);
186         
187         policy.getControlLoop().setTrigger_policy(trigger.getId());
188         
189         this.addNewPolicy(trigger);
190         //
191         // Return a copy of the policy
192         //
193         return new Policy(trigger);
194     }
195
196     @Override
197     public Policy setPolicyForPolicyResult(String name, String description, String actor,
198             Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException {
199         //
200         // Find the existing policy
201         //
202         Policy existingPolicy = this.findPolicy(policyID);
203         if (existingPolicy == null) {
204             throw new BuilderException("Unknown policy " + policyID);
205         }
206         //
207         // Create the new Policy
208         //
209         Policy newPolicy = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout);
210         //
211         // Connect the results
212         //
213         for (PolicyResult result : results) {
214             switch (result) {
215             case FAILURE:
216                 existingPolicy.setFailure(newPolicy.getId());
217                 break;
218             case FAILURE_EXCEPTION:
219                 existingPolicy.setFailure_exception(newPolicy.getId());
220                 break;
221             case FAILURE_RETRIES:
222                 existingPolicy.setFailure_retries(newPolicy.getId());
223                 break;
224             case FAILURE_TIMEOUT:
225                 existingPolicy.setFailure_timeout(newPolicy.getId());
226                 break;
227             case FAILURE_GUARD:
228                 existingPolicy.setFailure_guard(newPolicy.getId());
229                 break;
230             case SUCCESS:
231                 existingPolicy.setSuccess(newPolicy.getId());
232                 break;
233             default:
234                 throw new BuilderException("Invalid PolicyResult " + result);
235             }
236         }
237         //
238         // Add it to our list
239         //
240         this.policy.getPolicies().add(newPolicy);
241         //
242         // Return a policy to them
243         //
244         return new Policy(newPolicy);
245     }
246     
247     private class BuilderCompilerCallback implements ControlLoopCompilerCallback {
248
249         private ResultsImpl results = new ResultsImpl();
250         
251         @Override
252         public boolean onWarning(String message) {
253             results.addMessage(new MessageImpl(message, MessageLevel.WARNING));
254             return false;
255         }
256
257         @Override
258         public boolean onError(String message) {
259             results.addMessage(new MessageImpl(message, MessageLevel.ERROR));
260             return false;
261         }
262     }
263
264     @Override
265     public Results  buildSpecification() {
266         //
267         // Dump the specification
268         //
269         DumperOptions options = new DumperOptions();
270         options.setDefaultFlowStyle(FlowStyle.BLOCK);
271         options.setPrettyFlow(true);
272         Yaml yaml = new Yaml(options);
273         String dumpedYaml = yaml.dump(policy);
274         //
275         // This is our callback class for our compiler
276         //
277         BuilderCompilerCallback callback = new BuilderCompilerCallback();
278         //
279         // Compile it
280         //
281         try {
282             ControlLoopCompiler.compile(policy, callback);
283         } catch (CompilerException e) {
284             logger.error(e.getMessage() + e);
285             callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION));
286         }
287         //
288         // Save the spec
289         //
290         callback.results.setSpecification(dumpedYaml);
291         return callback.results;
292     }
293
294     private void addNewPolicy(Policy policy) {
295         if (this.policy.getPolicies() == null) {
296             this.policy.setPolicies(new LinkedList<>());
297         }
298         this.policy.getPolicies().add(policy);
299     }
300     
301     private Policy findPolicy(String id) {
302         for (Policy policy : this.policy.getPolicies()) {
303             if (policy.getId().equals(id)) {
304                 return policy;
305             }
306         }
307         return null;
308     }
309
310     @Override
311     public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException {
312         if (resources == null) {
313             throw new BuilderException("Resource must not be null");
314         }
315         if (policy.getControlLoop().getResources() == null) {
316             throw new BuilderException("No existing resources to remove");
317         }
318         for (Resource resource : resources) {
319             if (resource.getResourceUUID() == null) {
320                 if (resource.getResourceName() == null || resource.getResourceName().length() < 1) {
321                     throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName");
322                 }
323             }
324             boolean removed = policy.getControlLoop().getResources().remove(resource); 
325             if (!removed) {
326                 throw new BuilderException("Unknown resource " + resource.getResourceName());
327             }
328         }
329         return this; 
330     }
331
332     @Override
333     public ControlLoopPolicyBuilder removeAllResources() throws BuilderException {
334         policy.getControlLoop().getResources().clear();
335         return this;
336     }
337
338     @Override
339     public Integer calculateTimeout() {
340         int sum = 0;
341         for (Policy policy : this.policy.getPolicies()) {
342             sum += policy.getTimeout().intValue();
343         }
344         return new Integer(sum);
345     }
346
347     @Override
348     public ControlLoop setTriggerPolicy(String id) throws BuilderException {
349         if (id == null) {
350             throw new BuilderException("Id must not be null");
351         }
352         Policy trigger = this.findPolicy(id);
353         if (trigger == null) {
354             throw new BuilderException("Unknown policy " + id);
355         }
356         else {
357             this.policy.getControlLoop().setTrigger_policy(id);
358         }
359         return new ControlLoop(this.policy.getControlLoop());
360     }
361
362     @Override
363     public boolean isOpenLoop() {
364         if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) {
365             return true;
366         }   
367         else {
368             return false;
369         }
370     }
371
372     @Override
373     public Policy getTriggerPolicy() throws BuilderException {
374         if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) {
375             return null;
376         }
377         else {
378             Policy trigger = new Policy(this.findPolicy(this.policy.getControlLoop().getTrigger_policy()));
379             return trigger;
380         }
381     }
382
383     @Override
384     public ControlLoop getControlLoop() {
385         ControlLoop loop = new ControlLoop(this.policy.getControlLoop());
386         return loop;
387     }
388
389     @Override
390     public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results)
391             throws BuilderException {
392         //
393         // Find the existing policy
394         //
395         Policy existingPolicy = this.findPolicy(policyID);
396         if (existingPolicy == null) {
397             throw new BuilderException(policyID + " does not exist");
398         }
399         if (this.findPolicy(policyResultID) == null) {
400             throw new BuilderException("Operational policy " + policyResultID + " does not exist");
401         }
402         //
403         // Connect the results
404         //
405         for (PolicyResult result : results) {
406             switch (result) {
407             case FAILURE:
408                 existingPolicy.setFailure(policyResultID);
409                 break;
410             case FAILURE_EXCEPTION:
411                 existingPolicy.setFailure_exception(policyResultID);
412                 break;
413             case FAILURE_RETRIES:
414                 existingPolicy.setFailure_retries(policyResultID);
415                 break;
416             case FAILURE_TIMEOUT:
417                 existingPolicy.setFailure_timeout(policyResultID);
418                 break;
419             case FAILURE_GUARD:
420                 existingPolicy.setFailure_guard(policyResultID);
421                 break;
422             case SUCCESS:
423                 existingPolicy.setSuccess(policyResultID);
424                 break;
425             default:
426                 throw new BuilderException("Invalid PolicyResult " + result);
427             }
428         }
429         return new Policy(this.findPolicy(policyResultID));
430     }
431
432     @Override
433     public boolean removePolicy(String policyID) throws BuilderException {
434         Policy existingPolicy = this.findPolicy(policyID);
435         if (existingPolicy == null) {
436             throw new BuilderException("Unknown policy " + policyID);
437         }
438         //
439         // Check if the policy to remove is trigger_policy
440         //
441         if (this.policy.getControlLoop().getTrigger_policy().equals(policyID)) {
442             this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString());
443         }
444         else {
445             //
446             // Update policies
447             //
448             for (Policy policy : this.policy.getPolicies()) {
449                 int index = this.policy.getPolicies().indexOf(policy);
450                 if (policy.getSuccess().equals(policyID)) {
451                     policy.setSuccess(FinalResult.FINAL_SUCCESS.toString());
452                 }
453                 if (policy.getFailure().equals(policyID)) {
454                     policy.setFailure(FinalResult.FINAL_FAILURE.toString());
455                 }
456                 if (policy.getFailure_retries().equals(policyID)) {
457                     policy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString());
458                 }
459                 if (policy.getFailure_timeout().equals(policyID)) {
460                     policy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString());
461                 }
462                 if (policy.getFailure_exception().equals(policyID)) {
463                     policy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString());
464                 }
465                 if (policy.getFailure_guard().equals(policyID)) {
466                     policy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString());
467                 }
468                 this.policy.getPolicies().set(index, policy);
469             }
470         }
471         //
472         // remove the policy
473         //
474         boolean removed = this.policy.getPolicies().remove(existingPolicy);
475         return removed;
476     }
477
478     @Override
479     public Policy resetPolicyResults(String policyID) throws BuilderException {
480         Policy existingPolicy = this.findPolicy(policyID);
481         if (existingPolicy == null) {
482             throw new BuilderException("Unknown policy " + policyID);
483         }
484         //
485         // reset policy results
486         //
487         existingPolicy.setSuccess(FinalResult.FINAL_SUCCESS.toString());
488         existingPolicy.setFailure(FinalResult.FINAL_FAILURE.toString());
489         existingPolicy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString());
490         existingPolicy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString());
491         existingPolicy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString());
492         existingPolicy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString());
493         return new Policy(existingPolicy);
494     }
495
496     @Override
497     public ControlLoopPolicyBuilder removeAllPolicies() {
498         //
499         // Remove all existing operational policies
500         //
501         this.policy.getPolicies().clear();
502         //
503         // Revert controlLoop back to an open loop
504         //
505         this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString());
506         return this;
507     }
508     
509     @Override
510     public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException {
511         Policy existingPolicy = this.findPolicy(policyID);
512         if (existingPolicy == null) {
513             throw new BuilderException("Unknown policy " + policyID);
514         }
515         //
516         // Add operationsAccumulateParams to existingPolicy
517         //
518         existingPolicy.setOperationsAccumulateParams(operationsAccumulateParams);
519         return new Policy(existingPolicy);
520     }
521
522 }