ae6af6c074a2561e0c4d578f7916c2df927cbd7a
[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 static org.assertj.core.api.Assertions.assertThatThrownBy;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertNull;
26
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.nio.charset.StandardCharsets;
32 import java.nio.file.Files;
33 import java.nio.file.Paths;
34 import org.apache.commons.io.IOUtils;
35 import org.apache.commons.lang3.StringUtils;
36 import org.junit.Test;
37 import org.onap.policy.common.utils.coder.CoderException;
38 import org.onap.policy.common.utils.coder.StandardCoder;
39 import org.onap.policy.common.utils.resources.ResourceUtils;
40 import org.onap.policy.controlloop.ControlLoopException;
41 import org.onap.policy.controlloop.policy.FinalResult;
42 import org.onap.policy.controlloop.policy.Policy;
43 import org.onap.policy.controlloop.policy.PolicyResult;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class ControlLoopProcessorTest {
50     private static final Logger logger = LoggerFactory.getLogger(ControlLoopProcessorTest.class);
51     private static final StandardCoder coder = new StandardCoder();
52
53     @Test
54     public void testControlLoopProcessor() throws IOException, ControlLoopException {
55         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
56         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
57         this.testSuccess(yamlString);
58         this.testFailure(yamlString);
59     }
60
61     private ToscaPolicy getPolicyFromResource(String resourcePath, String policyName) throws CoderException {
62         String policyJson = ResourceUtils.getResourceAsString(resourcePath);
63         ToscaServiceTemplate serviceTemplate = coder.decode(policyJson, ToscaServiceTemplate.class);
64         ToscaPolicy policy = serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyName);
65         assertNotNull(policy);
66
67         /*
68          * name and version are used within a drl.  api component and drools core will ensure that these
69          * are populated.
70          */
71         if (StringUtils.isBlank(policy.getName())) {
72             policy.setName(policyName);
73         }
74
75         if (StringUtils.isBlank(policy.getVersion())) {
76             policy.setVersion(policy.getTypeVersion());
77         }
78
79         return serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyName);
80     }
81
82     @Test
83     public void testControlLoopFromToscaLegacy() throws IOException, CoderException, ControlLoopException {
84         String policy =
85                 new String(Files.readAllBytes(Paths.get("src/test/resources/tosca-policy-legacy-vcpe.json")));
86         assertNotNull(
87                 new ControlLoopProcessor(coder.decode(policy, ToscaPolicy.class)).getCurrentPolicy());
88
89         policy =
90                 new String(Files.readAllBytes(Paths.get("src/test/resources/tosca-policy-legacy-vdns.json")));
91         assertNotNull(
92                 new ControlLoopProcessor(coder.decode(policy, ToscaPolicy.class)).getCurrentPolicy());
93     }
94
95     @Test
96     public void testControlLoopFromToscaCompliant()
97             throws CoderException, ControlLoopException {
98         assertNotNull(
99                 new ControlLoopProcessor(
100                         getPolicyFromResource(
101                                 "policies/vCPE.policy.operational.input.tosca.json", "operational.restart")
102                 ).getCurrentPolicy());
103
104
105         assertNotNull(
106                 new ControlLoopProcessor(
107                         getPolicyFromResource(
108                                 "policies/vFirewall.policy.operational.input.tosca.json", "operational.modifyconfig")
109                 ).getCurrentPolicy());
110
111         assertNotNull(
112                 new ControlLoopProcessor(
113                         getPolicyFromResource(
114                                 "policies/vDNS.policy.operational.input.tosca.json", "operational.scaleout")
115                 ).getCurrentPolicy());
116     }
117
118     @Test
119     public void testControlLoopFromToscaCompliantBad() throws CoderException {
120         ToscaPolicy toscaPolicy = getPolicyFromResource(
121                 "policies/vCPE.policy.operational.input.tosca.json", "operational.restart");
122         toscaPolicy.setType("onap.policies.controlloop.Operational");
123         assertThatThrownBy(() -> new ControlLoopProcessor(toscaPolicy)).hasCauseInstanceOf(CoderException.class);
124     }
125
126     @Test
127     public void testControlLoopProcessorBadYaml() throws IOException {
128         InputStream is = new FileInputStream(new File("src/test/resources/string.yaml"));
129         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
130
131         assertThatThrownBy(() -> new ControlLoopProcessor(yamlString))
132             .hasMessageStartingWith("Cannot create property=string for JavaBean=ControlLoopPolicy");
133     }
134
135     @Test
136     public void testControlLoopProcessorBadTriggerYaml() throws IOException, ControlLoopException {
137         InputStream is = new FileInputStream(new File("src/test/resources/badtriggerpolicy.yaml"));
138         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
139
140         ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString);
141         assertNull(clProcessor.getCurrentPolicy());
142
143         assertThatThrownBy(() -> clProcessor.nextPolicyForResult(PolicyResult.SUCCESS))
144             .hasMessageStartingWith("There is no current policy to determine where to go to.");
145     }
146
147     @Test
148     public void testControlLoopProcessorNoPolicyYaml() throws IOException, ControlLoopException {
149         InputStream is = new FileInputStream(new File("src/test/resources/nopolicy.yaml"));
150         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
151
152         ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString);
153         assertThatThrownBy(clProcessor::getCurrentPolicy)
154             .hasMessage("There are no policies defined.");
155     }
156
157     @Test
158     public void testControlLoopProcessorNextPolicyForResult() throws IOException, ControlLoopException {
159         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
160         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
161
162         ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString);
163         clProcessor.getCurrentPolicy();
164         clProcessor.nextPolicyForResult(PolicyResult.SUCCESS);
165
166         clProcessor = new ControlLoopProcessor(yamlString);
167         clProcessor.getCurrentPolicy();
168         clProcessor.nextPolicyForResult(PolicyResult.FAILURE);
169
170         clProcessor = new ControlLoopProcessor(yamlString);
171         clProcessor.getCurrentPolicy();
172         clProcessor.nextPolicyForResult(PolicyResult.FAILURE_EXCEPTION);
173
174         clProcessor = new ControlLoopProcessor(yamlString);
175         clProcessor.getCurrentPolicy();
176         clProcessor.nextPolicyForResult(PolicyResult.FAILURE_GUARD);
177
178         clProcessor = new ControlLoopProcessor(yamlString);
179         clProcessor.getCurrentPolicy();
180         clProcessor.nextPolicyForResult(PolicyResult.FAILURE_RETRIES);
181
182         clProcessor = new ControlLoopProcessor(yamlString);
183         clProcessor.getCurrentPolicy();
184         clProcessor.nextPolicyForResult(PolicyResult.FAILURE_TIMEOUT);
185     }
186
187     /**
188      * Test policies in the given yaml following the successful path.
189      *
190      * @param yaml yaml containing the policies to test
191      * @throws ControlLoopException if an error occurs
192      */
193     public void testSuccess(String yaml) throws ControlLoopException {
194         ControlLoopProcessor processor = new ControlLoopProcessor(yaml);
195         logger.debug("testSuccess: {}", processor.getControlLoop());
196         while (true) {
197             FinalResult result = processor.checkIsCurrentPolicyFinal();
198             if (result != null) {
199                 logger.debug("{}", result);
200                 break;
201             }
202             Policy policy = processor.getCurrentPolicy();
203             assertNotNull(policy);
204             logger.debug("current policy is: {} {}", policy.getId(), policy.getName());
205             processor.nextPolicyForResult(PolicyResult.SUCCESS);
206         }
207     }
208
209     /**
210      * Test policies in the given yaml following the failure path.
211      *
212      * @param yaml yaml containing the policies to test
213      * @throws ControlLoopException if an error occurs
214      */
215     public void testFailure(String yaml) throws ControlLoopException {
216         ControlLoopProcessor processor = new ControlLoopProcessor(yaml);
217         logger.debug("testFailure: {}", processor.getControlLoop());
218         while (true) {
219             FinalResult result = processor.checkIsCurrentPolicyFinal();
220             if (result != null) {
221                 logger.debug("{}", result);
222                 break;
223             }
224             Policy policy = processor.getCurrentPolicy();
225             assertNotNull(policy);
226             logger.debug("current policy is: {} {}", policy.getId(), policy.getName());
227             processor.nextPolicyForResult(PolicyResult.FAILURE);
228         }
229     }
230 }