4cff616a06b13ff389a091b2edb10c7da916b5ab
[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.net.URLDecoder;
26 import java.util.stream.Collectors;
27 import lombok.Getter;
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.models.domain.legacy.LegacyPolicy;
41 import org.onap.policy.drools.models.domain.operational.OperationalPolicy;
42 import org.onap.policy.drools.system.PolicyEngineConstants;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
44 import org.yaml.snakeyaml.Yaml;
45 import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor;
46
47 public class ControlLoopProcessor implements Serializable {
48     private static final long serialVersionUID = 1L;
49
50     private final ControlLoopPolicy policy;
51     private String currentNestedPolicyId = null;
52
53     @Getter
54     private ToscaPolicy toscaOpPolicy;
55
56     @Getter
57     private DroolsPolicy domainOpPolicy;
58
59     /**
60      * Construct an instance from yaml.
61      * 
62      * @param yaml the yaml
63      * @throws ControlLoopException if an error occurs
64      */
65     public ControlLoopProcessor(String yaml) throws ControlLoopException {
66         try {
67             final Yaml y = new Yaml(new CustomClassLoaderConstructor(ControlLoopPolicy.class,
68                     ControlLoopPolicy.class.getClassLoader()));
69             final Object obj = y.load(yaml);
70
71             this.policy = (ControlLoopPolicy) obj;
72             this.currentNestedPolicyId = this.policy.getControlLoop().getTrigger_policy();
73         } catch (final Exception e) {
74             //
75             // Most likely this is a YAML Exception
76             //
77             throw new ControlLoopException(e);
78         }
79     }
80
81     /**
82      * Create an instance from a Tosca Policy.
83      */
84     public ControlLoopProcessor(ToscaPolicy toscaPolicy) throws ControlLoopException {
85         try {
86             // TODO: automate policy type to models mapping
87             this.policy =
88                 ("onap.policies.controlloop.Operational".equals(toscaPolicy.getType()))
89                     ? buildPolicyFromToscaLegacy(toscaPolicy)
90                         : buildPolicyFromToscaCompliant(toscaPolicy);
91
92             this.currentNestedPolicyId = this.policy.getControlLoop().getTrigger_policy();
93             this.toscaOpPolicy = toscaPolicy;
94         } catch (RuntimeException | CoderException | UnsupportedEncodingException e) {
95             throw new ControlLoopException(e);
96         }
97     }
98
99     protected ControlLoopPolicy buildPolicyFromToscaLegacy(ToscaPolicy policy)
100             throws UnsupportedEncodingException, CoderException {
101         LegacyPolicy legacyPolicy =
102                 PolicyEngineConstants.getManager().getDomainMaker().convertTo(policy, LegacyPolicy.class);
103         this.domainOpPolicy = legacyPolicy;
104         String decodedPolicy = URLDecoder.decode(legacyPolicy.getProperties().getContent(), "UTF-8");
105         return new Yaml(
106                 new CustomClassLoaderConstructor(
107                         ControlLoopPolicy.class, ControlLoopPolicy.class.getClassLoader())).load(decodedPolicy);
108     }
109
110     protected ControlLoopPolicy buildPolicyFromToscaCompliant(ToscaPolicy policy) throws CoderException {
111         OperationalPolicy domainPolicy =
112                 PolicyEngineConstants.getManager().getDomainMaker().convertTo(policy, OperationalPolicy.class);
113
114         ControlLoopPolicy backwardsCompatiblePolicy = new ControlLoopPolicy();
115
116         // @formatter:off
117         backwardsCompatiblePolicy.setPolicies(
118             domainPolicy.getProperties().getOperations().stream().map(operation -> new Policy(
119                     PolicyParam.builder()
120                             .id(operation.getId())
121                             .name(operation.getActorOperation().getOperation())
122                             .description(operation.getDescription())
123                             .actor(operation.getActorOperation().getActor())
124                             .payload(operation.getActorOperation().getPayload())
125                             .recipe(operation.getActorOperation().getOperation())
126                             .retries(operation.getRetries())
127                             .timeout(operation.getTimeout())
128                             .target(new Target(TargetType.valueOf(operation.getActorOperation().getTarget().getType()),
129                                     operation.getActorOperation().getTarget().getResourceId())).build()))
130                     .collect(Collectors.toList()));
131         // @formatter:on
132
133         ControlLoop controlLoop = new ControlLoop();
134         controlLoop.setAbatement(domainPolicy.getProperties().isAbatement());
135         controlLoop.setControlLoopName(domainPolicy.getProperties().getId());
136         controlLoop.setTimeout(domainPolicy.getProperties().getTimeout());
137         controlLoop.setTrigger_policy(domainPolicy.getProperties().getTrigger());
138         controlLoop.setVersion(domainPolicy.getVersion());
139
140         backwardsCompatiblePolicy.setControlLoop(controlLoop);
141         this.domainOpPolicy = domainPolicy;
142         return backwardsCompatiblePolicy;
143     }
144
145     /**
146      * Get ControlLoopParams.
147      */
148     public ControlLoopParams getControlLoopParams() {
149         ControlLoopParams controlLoopParams = new ControlLoopParams();
150
151         controlLoopParams.setClosedLoopControlName(this.getControlLoop().getControlLoopName());
152         controlLoopParams.setPolicyScope(domainOpPolicy.getType() + ":" + domainOpPolicy.getTypeVersion());
153         controlLoopParams.setPolicyName(domainOpPolicy.getName());
154         controlLoopParams.setPolicyVersion(domainOpPolicy.getVersion());
155         controlLoopParams.setToscaPolicy(toscaOpPolicy);
156
157         return controlLoopParams;
158     }
159
160     public ControlLoop getControlLoop() {
161         return this.policy.getControlLoop();
162     }
163
164     public FinalResult checkIsCurrentPolicyFinal() {
165         return FinalResult.toResult(this.currentNestedPolicyId);
166     }
167
168     /**
169      * Get the current policy.
170      * 
171      * @return the current policy
172      * @throws ControlLoopException if an error occurs
173      */
174     public Policy getCurrentPolicy() throws ControlLoopException {
175         if (this.policy == null || this.policy.getPolicies() == null) {
176             throw new ControlLoopException("There are no policies defined.");
177         }
178
179         for (final Policy nestedPolicy : this.policy.getPolicies()) {
180             if (nestedPolicy.getId().equals(this.currentNestedPolicyId)) {
181                 return nestedPolicy;
182             }
183         }
184         return null;
185     }
186
187     /**
188      * Get the next policy given a result of the current policy.
189      * 
190      * @param result the result of the current policy
191      * @throws ControlLoopException if an error occurs
192      */
193     public void nextPolicyForResult(PolicyResult result) throws ControlLoopException {
194         final Policy currentPolicy = this.getCurrentPolicy();
195         try {
196             if (currentPolicy == null) {
197                 throw new ControlLoopException("There is no current policy to determine where to go to.");
198             }
199             switch (result) {
200                 case SUCCESS:
201                     this.currentNestedPolicyId = currentPolicy.getSuccess();
202                     break;
203                 case FAILURE:
204                     this.currentNestedPolicyId = currentPolicy.getFailure();
205                     break;
206                 case FAILURE_TIMEOUT:
207                     this.currentNestedPolicyId = currentPolicy.getFailure_timeout();
208                     break;
209                 case FAILURE_RETRIES:
210                     this.currentNestedPolicyId = currentPolicy.getFailure_retries();
211                     break;
212                 case FAILURE_EXCEPTION:
213                     this.currentNestedPolicyId = currentPolicy.getFailure_exception();
214                     break;
215                 case FAILURE_GUARD:
216                 default:
217                     this.currentNestedPolicyId = currentPolicy.getFailure_guard();
218                     break;
219             }
220         } catch (final ControlLoopException e) {
221             this.currentNestedPolicyId = FinalResult.FINAL_FAILURE_EXCEPTION.toString();
222             throw e;
223         }
224     }
225 }