f578c8a8546b59829ec3df12f487f86255d1f526
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017-2020 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.processor;
22
23 import java.io.Serializable;
24 import java.lang.reflect.InvocationTargetException;
25 import java.util.stream.Collectors;
26 import lombok.Getter;
27 import org.apache.commons.beanutils.BeanUtils;
28 import org.onap.policy.common.utils.coder.CoderException;
29 import org.onap.policy.controlloop.ControlLoopException;
30 import org.onap.policy.controlloop.drl.legacy.ControlLoopParams;
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.Policy;
35 import org.onap.policy.controlloop.policy.PolicyParam;
36 import org.onap.policy.controlloop.policy.PolicyResult;
37 import org.onap.policy.controlloop.policy.Target;
38 import org.onap.policy.controlloop.policy.TargetType;
39 import org.onap.policy.drools.domain.models.DroolsPolicy;
40 import org.onap.policy.drools.domain.models.operational.Operation;
41 import org.onap.policy.drools.domain.models.operational.OperationalPolicy;
42 import org.onap.policy.drools.domain.models.operational.OperationalTarget;
43 import org.onap.policy.drools.system.PolicyEngineConstants;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.yaml.snakeyaml.Yaml;
48 import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor;
49
50 public class ControlLoopProcessor implements Serializable {
51     private static final long serialVersionUID = 1L;
52     private static final Logger logger = LoggerFactory.getLogger(ControlLoopProcessor.class);
53
54     @Getter
55     private final ControlLoopPolicy policy;
56     private String currentNestedPolicyId;
57
58     // not serializable, thus must be transient
59     @Getter
60     private transient ToscaPolicy toscaOpPolicy;
61
62     // not serializable, thus must be transient
63     @Getter
64     private transient DroolsPolicy domainOpPolicy;
65
66     /**
67      * Construct an instance from yaml.
68      *
69      * @param yaml the yaml
70      * @throws ControlLoopException if an error occurs
71      */
72     public ControlLoopProcessor(String yaml) throws ControlLoopException {
73         try {
74             final Yaml y = new Yaml(new CustomClassLoaderConstructor(ControlLoopPolicy.class,
75                     ControlLoopPolicy.class.getClassLoader()));
76             final Object obj = y.load(yaml);
77
78             this.policy = (ControlLoopPolicy) obj;
79             this.currentNestedPolicyId = this.policy.getControlLoop().getTrigger_policy();
80         } catch (final Exception e) {
81             //
82             // Most likely this is a YAML Exception
83             //
84             throw new ControlLoopException(e);
85         }
86     }
87
88     /**
89      * Create an instance from a Tosca Policy.
90      */
91     public ControlLoopProcessor(ToscaPolicy toscaPolicy) throws ControlLoopException {
92         try {
93             this.policy = buildPolicyFromToscaCompliant(toscaPolicy);
94
95             this.currentNestedPolicyId = this.policy.getControlLoop().getTrigger_policy();
96             this.toscaOpPolicy = toscaPolicy;
97         } catch (RuntimeException | CoderException e) {
98             throw new ControlLoopException(e);
99         }
100     }
101
102     private Target toStandardTarget(OperationalTarget opTarget) {
103         Target target = new Target(TargetType.valueOf(opTarget.getTargetType()));
104         try {
105             BeanUtils.populate(target, opTarget.getEntityIds());
106         } catch (IllegalAccessException | InvocationTargetException e) {
107             logger.warn("target entityIds cannot be mapped (unexpected): {}", opTarget, e);
108         }
109         return target;
110     }
111
112     protected ControlLoopPolicy buildPolicyFromToscaCompliant(ToscaPolicy policy) throws CoderException {
113         OperationalPolicy domainPolicy =
114                 PolicyEngineConstants.getManager().getDomainMaker().convertTo(policy, OperationalPolicy.class);
115
116         ControlLoopPolicy backwardsCompatiblePolicy = new ControlLoopPolicy();
117
118         // @formatter:off
119         backwardsCompatiblePolicy.setPolicies(
120             domainPolicy.getProperties().getOperations().stream().map(this::convertPolicy)
121                     .collect(Collectors.toList()));
122         // @formatter:on
123
124         ControlLoop controlLoop = new ControlLoop();
125         controlLoop.setAbatement(domainPolicy.getProperties().isAbatement());
126         controlLoop.setControlLoopName(domainPolicy.getProperties().getId());
127         controlLoop.setTimeout(domainPolicy.getProperties().getTimeout());
128         controlLoop.setTrigger_policy(domainPolicy.getProperties().getTrigger());
129         controlLoop.setVersion(domainPolicy.getVersion());
130
131         backwardsCompatiblePolicy.setControlLoop(controlLoop);
132         this.domainOpPolicy = domainPolicy;
133         return backwardsCompatiblePolicy;
134     }
135
136     private Policy convertPolicy(Operation operation) {
137         // @formatter:off
138         Policy newPolicy = new Policy(PolicyParam.builder()
139                 .id(operation.getId())
140                 .name(operation.getActorOperation().getOperation())
141                 .description(operation.getDescription())
142                 .actor(operation.getActorOperation().getActor())
143                 .payload(operation.getActorOperation().getPayload())
144                 .recipe(operation.getActorOperation().getOperation())
145                 .retries(operation.getRetries())
146                 .timeout(operation.getTimeout())
147                 .target(toStandardTarget(operation.getActorOperation().getTarget()))
148             .build());
149         // @formatter:on
150
151         newPolicy.setSuccess(operation.getSuccess());
152         newPolicy.setFailure(operation.getFailure());
153         newPolicy.setFailure_exception(operation.getFailureException());
154         newPolicy.setFailure_guard(operation.getFailureGuard());
155         newPolicy.setFailure_retries(operation.getFailureRetries());
156         newPolicy.setFailure_timeout(operation.getFailureTimeout());
157
158         return newPolicy;
159     }
160
161     /**
162      * Get ControlLoopParams.
163      */
164     public ControlLoopParams getControlLoopParams() {
165         ControlLoopParams controlLoopParams = new ControlLoopParams();
166
167         controlLoopParams.setClosedLoopControlName(this.getControlLoop().getControlLoopName());
168         controlLoopParams.setPolicyScope(domainOpPolicy.getType() + ":" + domainOpPolicy.getTypeVersion());
169         controlLoopParams.setPolicyName(domainOpPolicy.getName());
170         controlLoopParams.setPolicyVersion(domainOpPolicy.getVersion());
171         controlLoopParams.setToscaPolicy(toscaOpPolicy);
172
173         return controlLoopParams;
174     }
175
176     public ControlLoop getControlLoop() {
177         return this.policy.getControlLoop();
178     }
179
180     public FinalResult checkIsCurrentPolicyFinal() {
181         return FinalResult.toResult(this.currentNestedPolicyId);
182     }
183
184     /**
185      * Get the current policy.
186      *
187      * @return the current policy
188      * @throws ControlLoopException if an error occurs
189      */
190     public Policy getCurrentPolicy() throws ControlLoopException {
191         if (this.policy == null || this.policy.getPolicies() == null) {
192             throw new ControlLoopException("There are no policies defined.");
193         }
194
195         for (final Policy nestedPolicy : this.policy.getPolicies()) {
196             if (nestedPolicy.getId().equals(this.currentNestedPolicyId)) {
197                 return nestedPolicy;
198             }
199         }
200         return null;
201     }
202
203     /**
204      * Get the next policy given a result of the current policy.
205      *
206      * @param result the result of the current policy
207      * @throws ControlLoopException if an error occurs
208      */
209     public void nextPolicyForResult(PolicyResult result) throws ControlLoopException {
210         final Policy currentPolicy = this.getCurrentPolicy();
211         try {
212             if (currentPolicy == null) {
213                 throw new ControlLoopException("There is no current policy to determine where to go to.");
214             }
215             switch (result) {
216                 case SUCCESS:
217                     this.currentNestedPolicyId = currentPolicy.getSuccess();
218                     break;
219                 case FAILURE:
220                     this.currentNestedPolicyId = currentPolicy.getFailure();
221                     break;
222                 case FAILURE_TIMEOUT:
223                     this.currentNestedPolicyId = currentPolicy.getFailure_timeout();
224                     break;
225                 case FAILURE_RETRIES:
226                     this.currentNestedPolicyId = currentPolicy.getFailure_retries();
227                     break;
228                 case FAILURE_EXCEPTION:
229                     this.currentNestedPolicyId = currentPolicy.getFailure_exception();
230                     break;
231                 case FAILURE_GUARD:
232                 default:
233                     this.currentNestedPolicyId = currentPolicy.getFailure_guard();
234                     break;
235             }
236         } catch (final ControlLoopException e) {
237             this.currentNestedPolicyId = FinalResult.FINAL_FAILURE_EXCEPTION.toString();
238             throw e;
239         }
240     }
241 }