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