5f5baf0bd2957190c5b5f10189767959807288ad
[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.getPNFName() == null && pnf.getPNFType() == null) {
158                         throw new BuilderException("Invalid PNF - need either pnfName or pnfType");
159                 }
160                 policy.getControlLoop().setPnf(pnf);
161                 return this;
162         }
163
164         @Override
165         public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException{
166                 if (abatement == null) {
167                         throw new BuilderException("abatement must not be null");
168                 }
169                 policy.getControlLoop().setAbatement(abatement);
170                 return this;
171         }
172
173         @Override
174         public ControlLoopPolicyBuilder setTimeout(Integer timeout) {
175                 policy.getControlLoop().setTimeout(timeout);
176                 return this;
177         }
178
179         @Override
180         public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe,
181                         Map<String, String> payload, Integer retries, Integer timeout) throws BuilderException {
182
183                 Policy trigger = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout);
184
185                 policy.getControlLoop().setTrigger_policy(trigger.getId());
186
187                 this.addNewPolicy(trigger);
188                 //
189                 // Return a copy of the policy
190                 //
191                 return new Policy(trigger);
192         }
193
194         @Override
195         public Policy setPolicyForPolicyResult(String name, String description, String actor,
196                         Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException {
197                 //
198                 // Find the existing policy
199                 //
200                 Policy existingPolicy = this.findPolicy(policyID);
201                 if (existingPolicy == null) {
202                         throw new BuilderException("Unknown policy " + policyID);
203                 }
204                 //
205                 // Create the new Policy
206                 //
207                 Policy newPolicy = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout);
208                 //
209                 // Connect the results
210                 //
211                 for (PolicyResult result : results) {
212                         switch (result) {
213                         case FAILURE:
214                                 existingPolicy.setFailure(newPolicy.getId());
215                                 break;
216                         case FAILURE_EXCEPTION:
217                                 existingPolicy.setFailure_exception(newPolicy.getId());
218                                 break;
219                         case FAILURE_RETRIES:
220                                 existingPolicy.setFailure_retries(newPolicy.getId());
221                                 break;
222                         case FAILURE_TIMEOUT:
223                                 existingPolicy.setFailure_timeout(newPolicy.getId());
224                                 break;
225                         case FAILURE_GUARD:
226                                 existingPolicy.setFailure_guard(newPolicy.getId());
227                                 break;
228                         case SUCCESS:
229                                 existingPolicy.setSuccess(newPolicy.getId());
230                                 break;
231                         default:
232                                 throw new BuilderException("Invalid PolicyResult " + result);
233                         }
234                 }
235                 //
236                 // Add it to our list
237                 //
238                 this.policy.getPolicies().add(newPolicy);
239                 //
240                 // Return a policy to them
241                 //
242                 return new Policy(newPolicy);
243         }
244
245         private class BuilderCompilerCallback implements ControlLoopCompilerCallback {
246
247                 private ResultsImpl results = new ResultsImpl();
248
249                 @Override
250                 public boolean onWarning(String message) {
251                         results.addMessage(new MessageImpl(message, MessageLevel.WARNING));
252                         return false;
253                 }
254
255                 @Override
256                 public boolean onError(String message) {
257                         results.addMessage(new MessageImpl(message, MessageLevel.ERROR));
258                         return false;
259                 }
260         }
261
262         @Override
263         public Results  buildSpecification() {
264                 //
265                 // Dump the specification
266                 //
267                 DumperOptions options = new DumperOptions();
268                 options.setDefaultFlowStyle(FlowStyle.BLOCK);
269                 options.setPrettyFlow(true);
270                 Yaml yaml = new Yaml(options);
271                 String dumpedYaml = yaml.dump(policy);
272                 //
273                 // This is our callback class for our compiler
274                 //
275                 BuilderCompilerCallback callback = new BuilderCompilerCallback();
276                 //
277                 // Compile it
278                 //
279                 try {
280                         ControlLoopCompiler.compile(policy, callback);
281                 } catch (CompilerException e) {
282                         logger.error(e.getMessage() + e);
283                         callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION));
284                 }
285                 //
286                 // Save the spec
287                 //
288                 callback.results.setSpecification(dumpedYaml);
289                 return callback.results;
290         }
291
292         private void addNewPolicy(Policy policy) {
293                 if (this.policy.getPolicies() == null) {
294                         this.policy.setPolicies(new LinkedList<>());
295                 }
296                 this.policy.getPolicies().add(policy);
297         }
298
299         private Policy findPolicy(String id) {
300                 for (Policy policy : this.policy.getPolicies()) {
301                         if (policy.getId().equals(id)) {
302                                 return policy;
303                         }
304                 }
305                 return null;
306         }
307
308         @Override
309         public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException {
310                 if (resources == null) {
311                         throw new BuilderException("Resource must not be null");
312                 }
313                 if (policy.getControlLoop().getResources() == null) {
314                         throw new BuilderException("No existing resources to remove");
315                 }
316                 for (Resource resource : resources) {
317                         if (resource.getResourceUUID() == null) {
318                                 if (resource.getResourceName() == null || resource.getResourceName().length() < 1) {
319                                         throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName");
320                                 }
321                         }
322                         boolean removed = policy.getControlLoop().getResources().remove(resource); 
323                         if (!removed) {
324                                 throw new BuilderException("Unknown resource " + resource.getResourceName());
325                         }
326                 }
327                 return this; 
328         }
329
330         @Override
331         public ControlLoopPolicyBuilder removeAllResources() throws BuilderException {
332                 policy.getControlLoop().getResources().clear();
333                 return this;
334         }
335
336         @Override
337         public Integer calculateTimeout() {
338                 int sum = 0;
339                 for (Policy policy : this.policy.getPolicies()) {
340                         sum += policy.getTimeout().intValue();
341                 }
342                 return new Integer(sum);
343         }
344
345         @Override
346         public ControlLoop setTriggerPolicy(String id) throws BuilderException {
347                 if (id == null) {
348                         throw new BuilderException("Id must not be null");
349                 }
350                 Policy trigger = this.findPolicy(id);
351                 if (trigger == null) {
352                         throw new BuilderException("Unknown policy " + id);
353                 }
354                 else {
355                         this.policy.getControlLoop().setTrigger_policy(id);
356                 }
357                 return new ControlLoop(this.policy.getControlLoop());
358         }
359
360         @Override
361         public boolean isOpenLoop() {
362                 if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) {
363                         return true;
364                 }   
365                 else {
366                         return false;
367                 }
368         }
369
370         @Override
371         public Policy getTriggerPolicy() throws BuilderException {
372                 if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) {
373                         return null;
374                 }
375                 else {
376                         return new Policy(this.findPolicy(this.policy.getControlLoop().getTrigger_policy()));
377                 }
378         }
379
380         @Override
381         public ControlLoop getControlLoop() {
382                 return new ControlLoop(this.policy.getControlLoop());
383         }
384
385         @Override
386         public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results)
387                         throws BuilderException {
388                 //
389                 // Find the existing policy
390                 //
391                 Policy existingPolicy = this.findPolicy(policyID);
392                 if (existingPolicy == null) {
393                         throw new BuilderException(policyID + " does not exist");
394                 }
395                 if (this.findPolicy(policyResultID) == null) {
396                         throw new BuilderException("Operational policy " + policyResultID + " does not exist");
397                 }
398                 //
399                 // Connect the results
400                 //
401                 for (PolicyResult result : results) {
402                         switch (result) {
403                         case FAILURE:
404                                 existingPolicy.setFailure(policyResultID);
405                                 break;
406                         case FAILURE_EXCEPTION:
407                                 existingPolicy.setFailure_exception(policyResultID);
408                                 break;
409                         case FAILURE_RETRIES:
410                                 existingPolicy.setFailure_retries(policyResultID);
411                                 break;
412                         case FAILURE_TIMEOUT:
413                                 existingPolicy.setFailure_timeout(policyResultID);
414                                 break;
415                         case FAILURE_GUARD:
416                                 existingPolicy.setFailure_guard(policyResultID);
417                                 break;
418                         case SUCCESS:
419                                 existingPolicy.setSuccess(policyResultID);
420                                 break;
421                         default:
422                                 throw new BuilderException("Invalid PolicyResult " + result);
423                         }
424                 }
425                 return new Policy(this.findPolicy(policyResultID));
426         }
427
428         @Override
429         public boolean removePolicy(String policyID) throws BuilderException {
430                 Policy existingPolicy = this.findPolicy(policyID);
431                 if (existingPolicy == null) {
432                         throw new BuilderException("Unknown policy " + policyID);
433                 }
434                 //
435                 // Check if the policy to remove is trigger_policy
436                 //
437                 if (this.policy.getControlLoop().getTrigger_policy().equals(policyID)) {
438                         this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString());
439                 }
440                 else {
441                         //
442                         // Update policies
443                         //
444                         for (Policy policy : this.policy.getPolicies()) {
445                                 int index = this.policy.getPolicies().indexOf(policy);
446                                 if (policy.getSuccess().equals(policyID)) {
447                                         policy.setSuccess(FinalResult.FINAL_SUCCESS.toString());
448                                 }
449                                 if (policy.getFailure().equals(policyID)) {
450                                         policy.setFailure(FinalResult.FINAL_FAILURE.toString());
451                                 }
452                                 if (policy.getFailure_retries().equals(policyID)) {
453                                         policy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString());
454                                 }
455                                 if (policy.getFailure_timeout().equals(policyID)) {
456                                         policy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString());
457                                 }
458                                 if (policy.getFailure_exception().equals(policyID)) {
459                                         policy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString());
460                                 }
461                                 if (policy.getFailure_guard().equals(policyID)) {
462                                         policy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString());
463                                 }
464                                 this.policy.getPolicies().set(index, policy);
465                         }
466                 }
467                 //
468                 // remove the policy
469                 //
470                 boolean removed = this.policy.getPolicies().remove(existingPolicy);
471                 return removed;
472         }
473
474         @Override
475         public Policy resetPolicyResults(String policyID) throws BuilderException {
476                 Policy existingPolicy = this.findPolicy(policyID);
477                 if (existingPolicy == null) {
478                         throw new BuilderException("Unknown policy " + policyID);
479                 }
480                 //
481                 // reset policy results
482                 //
483                 existingPolicy.setSuccess(FinalResult.FINAL_SUCCESS.toString());
484                 existingPolicy.setFailure(FinalResult.FINAL_FAILURE.toString());
485                 existingPolicy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString());
486                 existingPolicy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString());
487                 existingPolicy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString());
488                 existingPolicy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString());
489                 return new Policy(existingPolicy);
490         }
491
492         @Override
493         public ControlLoopPolicyBuilder removeAllPolicies() {
494                 //
495                 // Remove all existing operational policies
496                 //
497                 this.policy.getPolicies().clear();
498                 //
499                 // Revert controlLoop back to an open loop
500                 //
501                 this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString());
502                 return this;
503         }
504
505         @Override
506         public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException {
507                 Policy existingPolicy = this.findPolicy(policyID);
508                 if (existingPolicy == null) {
509                         throw new BuilderException("Unknown policy " + policyID);
510                 }
511                 //
512                 // Add operationsAccumulateParams to existingPolicy
513                 //
514                 existingPolicy.setOperationsAccumulateParams(operationsAccumulateParams);
515                 return new Policy(existingPolicy);
516         }
517
518 }