2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017-2018 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.policy.builder.impl;
 
  23 import com.google.common.base.Strings;
 
  24 import java.util.LinkedList;
 
  26 import java.util.UUID;
 
  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.PolicyParam;
 
  37 import org.onap.policy.controlloop.policy.PolicyResult;
 
  38 import org.onap.policy.controlloop.policy.Target;
 
  39 import org.onap.policy.controlloop.policy.builder.BuilderException;
 
  40 import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder;
 
  41 import org.onap.policy.controlloop.policy.builder.MessageLevel;
 
  42 import org.onap.policy.controlloop.policy.builder.Results;
 
  43 import org.onap.policy.sdc.Resource;
 
  44 import org.onap.policy.sdc.Service;
 
  45 import org.slf4j.Logger;
 
  46 import org.slf4j.LoggerFactory;
 
  47 import org.yaml.snakeyaml.DumperOptions;
 
  48 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
 
  49 import org.yaml.snakeyaml.Yaml;
 
  51 public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder {
 
  52     private static final String UNKNOWN_POLICY = "Unknown policy ";
 
  53     private static Logger logger = LoggerFactory.getLogger(ControlLoopPolicyBuilderImpl.class.getName());
 
  54     private ControlLoopPolicy controlLoopPolicy;
 
  59      * @param controlLoopName control loop id
 
  60      * @param timeout timeout value
 
  62     public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) {
 
  63         controlLoopPolicy = new ControlLoopPolicy();
 
  64         ControlLoop controlLoop = new ControlLoop();
 
  65         controlLoop.setControlLoopName(controlLoopName);
 
  66         controlLoop.setTimeout(timeout);
 
  67         controlLoopPolicy.setControlLoop(controlLoop);
 
  73      * @param controlLoopName control loop id
 
  74      * @param timeout timeout value
 
  75      * @param resource resource
 
  76      * @param services services
 
  77      * @throws BuilderException builder exception
 
  79     public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Resource resource, Service... services)
 
  80             throws BuilderException {
 
  81         this(controlLoopName, timeout);
 
  82         this.addResource(resource);
 
  83         this.addService(services);
 
  86     public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Pnf pnf) throws BuilderException {
 
  87         this(controlLoopName, timeout);
 
  94      * @param controlLoopName control loop id
 
  95      * @param timeout timeout
 
  96      * @param service service
 
  97      * @param resources resources
 
  98      * @throws BuilderException builder exception
 
 100     public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Service service, Resource[] resources)
 
 101             throws BuilderException {
 
 102         this(controlLoopName, timeout);
 
 103         this.addService(service);
 
 104         this.addResource(resources);
 
 108     public ControlLoopPolicyBuilder removePNF() throws BuilderException {
 
 109         controlLoopPolicy.getControlLoop().setPnf(null);
 
 114     public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException {
 
 115         for (Service service : services) {
 
 116             if (service == null) {
 
 117                 throw new BuilderException("Service must not be null");
 
 119             if (service.getServiceUUID() == null && Strings.isNullOrEmpty(service.getServiceName())) {
 
 120                 throw new BuilderException("Invalid service - need either a serviceUUID or serviceName");
 
 122             if (controlLoopPolicy.getControlLoop().getServices() == null) {
 
 123                 controlLoopPolicy.getControlLoop().setServices(new LinkedList<>());
 
 125             controlLoopPolicy.getControlLoop().getServices().add(service);
 
 131     public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException {
 
 132         if (controlLoopPolicy.getControlLoop().getServices() == null) {
 
 133             throw new BuilderException("No existing services to remove");
 
 135         for (Service service : services) {
 
 136             if (service == null) {
 
 137                 throw new BuilderException("Service must not be null");
 
 139             if (service.getServiceUUID() == null && Strings.isNullOrEmpty(service.getServiceName())) {
 
 140                 throw new BuilderException("Invalid service - need either a serviceUUID or serviceName");
 
 142             boolean removed = controlLoopPolicy.getControlLoop().getServices().remove(service);
 
 144                 throw new BuilderException("Unknown service " + service.getServiceName());
 
 151     public ControlLoopPolicyBuilder removeAllServices() throws BuilderException {
 
 152         controlLoopPolicy.getControlLoop().getServices().clear();
 
 158     public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException {
 
 159         for (Resource resource : resources) {
 
 160             if (resource == null) {
 
 161                 throw new BuilderException("Resource must not be null");
 
 163             if (resource.getResourceUuid() == null && Strings.isNullOrEmpty(resource.getResourceName())) {
 
 164                 throw new BuilderException("Invalid resource - need either resourceUUID or resourceName");
 
 166             if (controlLoopPolicy.getControlLoop().getResources() == null) {
 
 167                 controlLoopPolicy.getControlLoop().setResources(new LinkedList<>());
 
 169             controlLoopPolicy.getControlLoop().getResources().add(resource);
 
 175     public ControlLoopPolicyBuilder setPNF(Pnf pnf) throws BuilderException {
 
 177             throw new BuilderException("PNF must not be null");
 
 179         if (pnf.getPnfName() == null && pnf.getPnfType() == null) {
 
 180             throw new BuilderException("Invalid PNF - need either pnfName or pnfType");
 
 182         controlLoopPolicy.getControlLoop().setPnf(pnf);
 
 187     public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException {
 
 188         if (abatement == null) {
 
 189             throw new BuilderException("abatement must not be null");
 
 191         controlLoopPolicy.getControlLoop().setAbatement(abatement);
 
 196     public ControlLoopPolicyBuilder setTimeout(Integer timeout) {
 
 197         controlLoopPolicy.getControlLoop().setTimeout(timeout);
 
 202     public Policy setTriggerPolicy(PolicyParam policyParam)
 
 203             throws BuilderException {
 
 205         Policy trigger = new Policy(policyParam);
 
 207         controlLoopPolicy.getControlLoop().setTrigger_policy(trigger.getId());
 
 209         this.addNewPolicy(trigger);
 
 211         // Return a copy of the policy
 
 213         return new Policy(trigger);
 
 217     public ControlLoop setExistingTriggerPolicy(String id) throws BuilderException {
 
 219             throw new BuilderException("Id must not be null");
 
 221         Policy trigger = this.findPolicy(id);
 
 222         if (trigger == null) {
 
 223             throw new BuilderException(UNKNOWN_POLICY + id);
 
 225             this.controlLoopPolicy.getControlLoop().setTrigger_policy(id);
 
 227         return new ControlLoop(this.controlLoopPolicy.getControlLoop());
 
 231     public Policy setPolicyForPolicyResult(String name, String description, String actor, Target target, String recipe,
 
 232                                            Map<String, String> payload, Integer retries, Integer timeout,
 
 233                                            String policyId, PolicyResult... results)
 
 234             throws BuilderException {
 
 236         // Find the existing policy
 
 238         Policy existingPolicy = this.findPolicy(policyId);
 
 239         if (existingPolicy == null) {
 
 240             throw new BuilderException(UNKNOWN_POLICY + policyId);
 
 243         // Create the new Policy
 
 245         Policy newPolicy = new Policy(
 
 246                 PolicyParam.builder().id(UUID.randomUUID().toString())
 
 248                 .description(description)
 
 257         // Connect the results
 
 259         for (PolicyResult result : results) {
 
 262                     existingPolicy.setFailure(newPolicy.getId());
 
 264                 case FAILURE_EXCEPTION:
 
 265                     existingPolicy.setFailure_exception(newPolicy.getId());
 
 267                 case FAILURE_RETRIES:
 
 268                     existingPolicy.setFailure_retries(newPolicy.getId());
 
 270                 case FAILURE_TIMEOUT:
 
 271                     existingPolicy.setFailure_timeout(newPolicy.getId());
 
 274                     existingPolicy.setFailure_guard(newPolicy.getId());
 
 277                     existingPolicy.setSuccess(newPolicy.getId());
 
 280                     throw new BuilderException("Invalid PolicyResult " + result);
 
 284         // Add it to our list
 
 286         this.controlLoopPolicy.getPolicies().add(newPolicy);
 
 288         // Return a policy to them
 
 290         return new Policy(newPolicy);
 
 294     public Policy setPolicyForPolicyResult(String policyResultId, String policyId, PolicyResult... results)
 
 295             throws BuilderException {
 
 297         // Find the existing policy
 
 299         Policy existingPolicy = this.findPolicy(policyId);
 
 300         if (existingPolicy == null) {
 
 301             throw new BuilderException(policyId + " does not exist");
 
 303         if (this.findPolicy(policyResultId) == null) {
 
 304             throw new BuilderException("Operational policy " + policyResultId + " does not exist");
 
 307         // Connect the results
 
 309         for (PolicyResult result : results) {
 
 312                     existingPolicy.setFailure(policyResultId);
 
 314                 case FAILURE_EXCEPTION:
 
 315                     existingPolicy.setFailure_exception(policyResultId);
 
 317                 case FAILURE_RETRIES:
 
 318                     existingPolicy.setFailure_retries(policyResultId);
 
 320                 case FAILURE_TIMEOUT:
 
 321                     existingPolicy.setFailure_timeout(policyResultId);
 
 324                     existingPolicy.setFailure_guard(policyResultId);
 
 327                     existingPolicy.setSuccess(policyResultId);
 
 330                     throw new BuilderException("Invalid PolicyResult " + result);
 
 333         return new Policy(this.findPolicy(policyResultId));
 
 336     private class BuilderCompilerCallback implements ControlLoopCompilerCallback {
 
 338         private ResultsImpl results = new ResultsImpl();
 
 341         public boolean onWarning(String message) {
 
 342             results.addMessage(new MessageImpl(message, MessageLevel.WARNING));
 
 347         public boolean onError(String message) {
 
 348             results.addMessage(new MessageImpl(message, MessageLevel.ERROR));
 
 354     public Results buildSpecification() {
 
 356         // Dump the specification
 
 358         DumperOptions options = new DumperOptions();
 
 359         options.setDefaultFlowStyle(FlowStyle.BLOCK);
 
 360         options.setPrettyFlow(true);
 
 361         Yaml yaml = new Yaml(options);
 
 362         String dumpedYaml = yaml.dump(controlLoopPolicy);
 
 364         // This is our callback class for our compiler
 
 366         BuilderCompilerCallback callback = new BuilderCompilerCallback();
 
 371             ControlLoopCompiler.compile(controlLoopPolicy, callback);
 
 372         } catch (CompilerException e) {
 
 373             logger.error(e.getMessage() + e);
 
 374             callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION));
 
 379         callback.results.setSpecification(dumpedYaml);
 
 380         return callback.results;
 
 383     private void addNewPolicy(Policy policy) {
 
 384         if (this.controlLoopPolicy.getPolicies() == null) {
 
 385             this.controlLoopPolicy.setPolicies(new LinkedList<>());
 
 387         this.controlLoopPolicy.getPolicies().add(policy);
 
 390     private Policy findPolicy(String id) {
 
 391         if (this.controlLoopPolicy.getPolicies() != null) {
 
 392             for (Policy policy : this.controlLoopPolicy.getPolicies()) {
 
 393                 if (policy.getId().equals(id)) {
 
 402     public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException {
 
 403         if (controlLoopPolicy.getControlLoop().getResources() == null) {
 
 404             throw new BuilderException("No existing resources to remove");
 
 406         for (Resource resource : resources) {
 
 407             if (resource == null) {
 
 408                 throw new BuilderException("Resource must not be null");
 
 410             if (resource.getResourceUuid() == null && Strings.isNullOrEmpty(resource.getResourceName())) {
 
 411                 throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName");
 
 413             boolean removed = controlLoopPolicy.getControlLoop().getResources().remove(resource);
 
 415                 throw new BuilderException("Unknown resource " + resource.getResourceName());
 
 422     public ControlLoopPolicyBuilder removeAllResources() throws BuilderException {
 
 423         controlLoopPolicy.getControlLoop().getResources().clear();
 
 428     public Integer calculateTimeout() {
 
 430         for (Policy policy : this.controlLoopPolicy.getPolicies()) {
 
 431             sum += policy.getTimeout().intValue();
 
 433         return Integer.valueOf(sum);
 
 437     public boolean isOpenLoop() {
 
 438         return this.controlLoopPolicy.getControlLoop().getTrigger_policy()
 
 439                 .equals(FinalResult.FINAL_OPENLOOP.toString());
 
 443     public Policy getTriggerPolicy() throws BuilderException {
 
 444         if (this.controlLoopPolicy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) {
 
 447             return new Policy(this.findPolicy(this.controlLoopPolicy.getControlLoop().getTrigger_policy()));
 
 452     public ControlLoop getControlLoop() {
 
 453         return new ControlLoop(this.controlLoopPolicy.getControlLoop());
 
 457     public boolean removePolicy(String policyId) throws BuilderException {
 
 458         Policy existingPolicy = this.findPolicy(policyId);
 
 459         if (existingPolicy == null) {
 
 460             throw new BuilderException(UNKNOWN_POLICY + policyId);
 
 463         // Check if the policy to remove is trigger_policy
 
 465         if (this.controlLoopPolicy.getControlLoop().getTrigger_policy().equals(policyId)) {
 
 466             this.controlLoopPolicy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString());
 
 468             updateChainedPoliciesForPolicyRemoval(policyId);
 
 473         return this.controlLoopPolicy.getPolicies().remove(existingPolicy);
 
 476     private void updateChainedPoliciesForPolicyRemoval(String idOfPolicyBeingRemoved) {
 
 477         for (Policy policy : this.controlLoopPolicy.getPolicies()) {
 
 478             final int index = this.controlLoopPolicy.getPolicies().indexOf(policy);
 
 479             if (policy.getSuccess().equals(idOfPolicyBeingRemoved)) {
 
 480                 policy.setSuccess(FinalResult.FINAL_SUCCESS.toString());
 
 482             if (policy.getFailure().equals(idOfPolicyBeingRemoved)) {
 
 483                 policy.setFailure(FinalResult.FINAL_FAILURE.toString());
 
 485             if (policy.getFailure_retries().equals(idOfPolicyBeingRemoved)) {
 
 486                 policy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString());
 
 488             if (policy.getFailure_timeout().equals(idOfPolicyBeingRemoved)) {
 
 489                 policy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString());
 
 491             if (policy.getFailure_exception().equals(idOfPolicyBeingRemoved)) {
 
 492                 policy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString());
 
 494             if (policy.getFailure_guard().equals(idOfPolicyBeingRemoved)) {
 
 495                 policy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString());
 
 497             this.controlLoopPolicy.getPolicies().set(index, policy);
 
 502     public Policy resetPolicyResults(String policyId) throws BuilderException {
 
 503         Policy existingPolicy = this.findPolicy(policyId);
 
 504         if (existingPolicy == null) {
 
 505             throw new BuilderException(UNKNOWN_POLICY + policyId);
 
 508         // reset policy results
 
 510         existingPolicy.setSuccess(FinalResult.FINAL_SUCCESS.toString());
 
 511         existingPolicy.setFailure(FinalResult.FINAL_FAILURE.toString());
 
 512         existingPolicy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString());
 
 513         existingPolicy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString());
 
 514         existingPolicy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString());
 
 515         existingPolicy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString());
 
 516         return new Policy(existingPolicy);
 
 520     public ControlLoopPolicyBuilder removeAllPolicies() {
 
 522         // Remove all existing operational policies
 
 524         this.controlLoopPolicy.getPolicies().clear();
 
 526         // Revert controlLoop back to an open loop
 
 528         this.controlLoopPolicy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString());
 
 533     public Policy addOperationsAccumulateParams(String policyId, OperationsAccumulateParams operationsAccumulateParams)
 
 534             throws BuilderException {
 
 535         Policy existingPolicy = this.findPolicy(policyId);
 
 536         if (existingPolicy == null) {
 
 537             throw new BuilderException(UNKNOWN_POLICY + policyId);
 
 540         // Add operationsAccumulateParams to existingPolicy
 
 542         existingPolicy.setOperationsAccumulateParams(operationsAccumulateParams);
 
 543         return new Policy(existingPolicy);