0015e4dd7f4a5e8f0e1b7e0c36cdd45eb739fdc7
[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.OperationalPolicy;
44 import org.onap.policy.drools.models.domain.operational.OperationalTarget;
45 import org.onap.policy.drools.system.PolicyEngineConstants;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.yaml.snakeyaml.Yaml;
50 import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor;
51
52 public class ControlLoopProcessor implements Serializable {
53     private static final long serialVersionUID = 1L;
54     private static final Logger logger = LoggerFactory.getLogger(ControlLoopProcessor.class);
55
56     private final ControlLoopPolicy policy;
57     private String currentNestedPolicyId = null;
58
59     @Getter
60     private ToscaPolicy toscaOpPolicy;
61
62     @Getter
63     private DroolsPolicy domainOpPolicy;
64
65     /**
66      * Construct an instance from yaml.
67      * 
68      * @param yaml the yaml
69      * @throws ControlLoopException if an error occurs
70      */
71     public ControlLoopProcessor(String yaml) throws ControlLoopException {
72         try {
73             final Yaml y = new Yaml(new CustomClassLoaderConstructor(ControlLoopPolicy.class,
74                     ControlLoopPolicy.class.getClassLoader()));
75             final Object obj = y.load(yaml);
76
77             this.policy = (ControlLoopPolicy) obj;
78             this.currentNestedPolicyId = this.policy.getControlLoop().getTrigger_policy();
79         } catch (final Exception e) {
80             //
81             // Most likely this is a YAML Exception
82             //
83             throw new ControlLoopException(e);
84         }
85     }
86
87     /**
88      * Create an instance from a Tosca Policy.
89      */
90     public ControlLoopProcessor(ToscaPolicy toscaPolicy) throws ControlLoopException {
91         try {
92             // TODO: automate policy type to models mapping
93             this.policy =
94                 ("onap.policies.controlloop.Operational".equals(toscaPolicy.getType()))
95                     ? buildPolicyFromToscaLegacy(toscaPolicy)
96                         : buildPolicyFromToscaCompliant(toscaPolicy);
97
98             this.currentNestedPolicyId = this.policy.getControlLoop().getTrigger_policy();
99             this.toscaOpPolicy = toscaPolicy;
100         } catch (RuntimeException | CoderException | UnsupportedEncodingException e) {
101             throw new ControlLoopException(e);
102         }
103     }
104
105     protected ControlLoopPolicy buildPolicyFromToscaLegacy(ToscaPolicy policy)
106             throws UnsupportedEncodingException, CoderException {
107         LegacyPolicy legacyPolicy =
108                 PolicyEngineConstants.getManager().getDomainMaker().convertTo(policy, LegacyPolicy.class);
109         this.domainOpPolicy = legacyPolicy;
110         String decodedPolicy = URLDecoder.decode(legacyPolicy.getProperties().getContent(), "UTF-8");
111         return new Yaml(
112                 new CustomClassLoaderConstructor(
113                         ControlLoopPolicy.class, ControlLoopPolicy.class.getClassLoader())).load(decodedPolicy);
114     }
115
116     private Target toStandardTarget(OperationalTarget opTarget) {
117         Target target = new Target(TargetType.valueOf(opTarget.getTargetType()));
118         try {
119             BeanUtils.populate(target, opTarget.getEntityIds());
120         } catch (IllegalAccessException | InvocationTargetException e) {
121             logger.warn("target entityIds cannot be mapped (unexpected): {}", opTarget, e);
122         }
123         return target;
124     }
125
126     protected ControlLoopPolicy buildPolicyFromToscaCompliant(ToscaPolicy policy) throws CoderException {
127         OperationalPolicy domainPolicy =
128                 PolicyEngineConstants.getManager().getDomainMaker().convertTo(policy, OperationalPolicy.class);
129
130         ControlLoopPolicy backwardsCompatiblePolicy = new ControlLoopPolicy();
131
132         // @formatter:off
133         backwardsCompatiblePolicy.setPolicies(
134             domainPolicy.getProperties().getOperations().stream().map(operation -> new Policy(
135                         PolicyParam.builder()
136                                 .id(operation.getId())
137                                 .name(operation.getActorOperation().getOperation())
138                                 .description(operation.getDescription())
139                                 .actor(operation.getActorOperation().getActor())
140                                 .payload(operation.getActorOperation().getPayload())
141                                 .recipe(operation.getActorOperation().getOperation())
142                                 .retries(operation.getRetries())
143                                 .timeout(operation.getTimeout())
144                                 .target(toStandardTarget(operation.getActorOperation().getTarget()))
145                                 .build()))
146                     .collect(Collectors.toList()));
147         // @formatter:on
148
149         ControlLoop controlLoop = new ControlLoop();
150         controlLoop.setAbatement(domainPolicy.getProperties().isAbatement());
151         controlLoop.setControlLoopName(domainPolicy.getProperties().getId());
152         controlLoop.setTimeout(domainPolicy.getProperties().getTimeout());
153         controlLoop.setTrigger_policy(domainPolicy.getProperties().getTrigger());
154         controlLoop.setVersion(domainPolicy.getVersion());
155
156         backwardsCompatiblePolicy.setControlLoop(controlLoop);
157         this.domainOpPolicy = domainPolicy;
158         return backwardsCompatiblePolicy;
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 }