Add changes for safe delete in policy-models
[policy/api.git] / main / src / test / java / org / onap / policy / api / main / rest / provider / TestLegacyOperationalPolicyProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy API
4  * ================================================================================
5  * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019-2020 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.api.main.rest.provider;
25
26 import static org.assertj.core.api.Assertions.assertThatCode;
27 import static org.assertj.core.api.Assertions.assertThatThrownBy;
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertFalse;
30 import static org.junit.Assert.assertNotNull;
31 import static org.junit.Assert.assertTrue;
32 import static org.junit.Assert.fail;
33
34 import java.util.ArrayList;
35 import java.util.Base64;
36 import java.util.Collections;
37 import java.util.List;
38
39 import org.junit.After;
40 import org.junit.Before;
41 import org.junit.Test;
42 import org.onap.policy.api.main.parameters.ApiParameterGroup;
43 import org.onap.policy.common.parameters.ParameterService;
44 import org.onap.policy.common.utils.coder.StandardCoder;
45 import org.onap.policy.common.utils.coder.StandardYamlCoder;
46 import org.onap.policy.common.utils.resources.ResourceUtils;
47 import org.onap.policy.models.base.PfModelException;
48 import org.onap.policy.models.pdp.concepts.Pdp;
49 import org.onap.policy.models.pdp.concepts.PdpGroup;
50 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
51 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
52 import org.onap.policy.models.pdp.enums.PdpHealthStatus;
53 import org.onap.policy.models.pdp.enums.PdpState;
54 import org.onap.policy.models.provider.PolicyModelsProvider;
55 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
56 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
57 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
58 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
59 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
60 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
61
62 /**
63  * This class performs unit test of {@link LegacyOperationalPolicyProvider}.
64  *
65  * @author Chenfei Gao (cgao@research.att.com)
66  */
67 public class TestLegacyOperationalPolicyProvider {
68
69     private static LegacyOperationalPolicyProvider operationalPolicyProvider;
70     private static PolicyTypeProvider policyTypeProvider;
71     private static PolicyModelsProviderParameters providerParams;
72     private static ApiParameterGroup apiParamGroup;
73     private static StandardCoder standardCoder;
74     private static StandardYamlCoder standardYamlCoder;
75
76     private static final String POLICY_RESOURCE = "policies/vCPE.policy.operational.legacy.input.json";
77     private static final String POLICY_RESOURCE_WITH_NO_VERSION =
78             "policies/vDNS.policy.operational.no.policyversion.json";
79     private static final String POLICY_TYPE_RESOURCE = "policytypes/onap.policies.controlloop.Operational.yaml";
80     private static final String POLICY_TYPE_ID = "onap.policies.controlloop.Operational:1.0.0";
81     private static final String POLICY_NAME = "operational.restart";
82     private static final String POLICY_VERSION = "1";
83     private static final String POLICY_TYPE_NAME = "onap.policies.controlloop.Operational";
84     private static final String POLICY_TYPE_VERSION = "1.0.0";
85     private static final String LEGACY_MINOR_PATCH_SUFFIX = ".0.0";
86
87     /**
88      * Initializes parameters.
89      *
90      * @throws PfModelException the PfModel parsing exception
91      */
92     @Before
93     public void setupParameters() throws PfModelException {
94
95         standardCoder = new StandardCoder();
96         standardYamlCoder = new StandardYamlCoder();
97         providerParams = new PolicyModelsProviderParameters();
98         providerParams.setDatabaseDriver("org.h2.Driver");
99         providerParams.setDatabaseUrl("jdbc:h2:mem:testdb");
100         providerParams.setDatabaseUser("policy");
101         providerParams.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
102         providerParams.setPersistenceUnit("ToscaConceptTest");
103         apiParamGroup = new ApiParameterGroup("ApiGroup", null, providerParams, Collections.emptyList());
104         ParameterService.register(apiParamGroup, true);
105         operationalPolicyProvider = new LegacyOperationalPolicyProvider();
106         policyTypeProvider = new PolicyTypeProvider();
107     }
108
109     /**
110      * Closes up DB connections and deregisters API parameter group.
111      *
112      * @throws PfModelException the PfModel parsing exception
113      */
114     @After
115     public void tearDown() throws PfModelException {
116
117         operationalPolicyProvider.close();
118         policyTypeProvider.close();
119         ParameterService.deregister(apiParamGroup);
120     }
121
122     @Test
123     public void testFetchOperationalPolicy() throws Exception {
124
125         assertThatThrownBy(() -> {
126             operationalPolicyProvider.fetchOperationalPolicy("dummy", null);
127         }).hasMessage("no policy found for policy: dummy:null");
128
129         assertThatThrownBy(() -> {
130             operationalPolicyProvider.fetchOperationalPolicy("dummy", "dummy");
131         }).hasMessageContaining("parameter \"version\": value \"dummy.0.0\", does not match regular expression");
132
133         ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder
134                 .decode(ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
135         policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
136
137         String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
138         LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
139         LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate);
140         assertNotNull(createdPolicy);
141
142         LegacyOperationalPolicy firstVersion =
143                 operationalPolicyProvider.fetchOperationalPolicy("operational.restart", "1");
144         assertNotNull(firstVersion);
145         assertEquals("1", firstVersion.getPolicyVersion());
146
147         LegacyOperationalPolicy latestVersion =
148                 operationalPolicyProvider.fetchOperationalPolicy("operational.restart", null);
149         assertNotNull(latestVersion);
150         assertEquals("1", latestVersion.getPolicyVersion());
151
152         assertThatThrownBy(() -> {
153             operationalPolicyProvider.fetchOperationalPolicy("operational.restart", "1.0.0");
154         }).hasMessageContaining("parameter \"version\": value \"1.0.0.0.0\", does not match regular expression");
155
156         assertThatThrownBy(() -> {
157             operationalPolicyProvider.fetchOperationalPolicy("operational.restart", "latest");
158             ;
159         }).hasMessageContaining("parameter \"version\": value \"latest.0.0\", does not match regular expression");
160
161         operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "1");
162         policyTypeProvider.deletePolicyType("onap.policies.controlloop.Operational", "1.0.0");
163     }
164
165     @Test
166     public void testFetchDeployedOperationalPolicies() {
167
168         assertThatThrownBy(() -> {
169             operationalPolicyProvider.fetchDeployedOperationalPolicies("dummy");
170         }).hasMessage("could not find policy with ID dummy and type " + POLICY_TYPE_ID + " deployed in any pdp group");
171
172         try (PolicyModelsProvider databaseProvider =
173                 new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParams)) {
174             assertEquals(0, databaseProvider.getPdpGroups("name").size());
175             assertEquals(0, databaseProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).size());
176
177             assertNotNull(databaseProvider.createPdpGroups(new ArrayList<>()));
178             assertNotNull(databaseProvider.updatePdpGroups(new ArrayList<>()));
179
180             PdpGroup pdpGroup = new PdpGroup();
181             pdpGroup.setName("group");
182             pdpGroup.setVersion("1.2.3");
183             pdpGroup.setPdpGroupState(PdpState.ACTIVE);
184             pdpGroup.setPdpSubgroups(new ArrayList<>());
185             List<PdpGroup> groupList = new ArrayList<>();
186             groupList.add(pdpGroup);
187
188             PdpSubGroup pdpSubGroup = new PdpSubGroup();
189             pdpSubGroup.setPdpType("type");
190             pdpSubGroup.setDesiredInstanceCount(123);
191             pdpSubGroup.setSupportedPolicyTypes(new ArrayList<>());
192             pdpSubGroup.getSupportedPolicyTypes()
193                     .add(new ToscaPolicyTypeIdentifier(POLICY_TYPE_NAME, POLICY_TYPE_VERSION));
194             pdpGroup.getPdpSubgroups().add(pdpSubGroup);
195
196             Pdp pdp = new Pdp();
197             pdp.setInstanceId("type-0");
198             pdp.setMessage("Hello");
199             pdp.setPdpState(PdpState.ACTIVE);
200             pdp.setHealthy(PdpHealthStatus.UNKNOWN);
201             pdpSubGroup.setPdpInstances(new ArrayList<>());
202             pdpSubGroup.getPdpInstances().add(pdp);
203
204             // Create Pdp Groups
205             assertEquals(123, databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0)
206                     .getDesiredInstanceCount());
207             assertEquals(1, databaseProvider.getPdpGroups("group").size());
208
209             // Create Policy Type
210             assertThatCode(() -> {
211                 ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder
212                         .decode(ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
213                 policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
214             }).doesNotThrowAnyException();
215
216             // Create Policy
217             assertThatCode(() -> {
218                 String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
219                 LegacyOperationalPolicy policyToCreate =
220                         standardCoder.decode(policyString, LegacyOperationalPolicy.class);
221                 LegacyOperationalPolicy policyCreated =
222                         operationalPolicyProvider.createOperationalPolicy(policyToCreate);
223                 assertEquals("operational.restart", policyCreated.getPolicyId());
224                 assertEquals("1", policyCreated.getPolicyVersion());
225                 assertFalse(policyCreated.getContent() == null);
226             }).doesNotThrowAnyException();
227
228             // Test fetchDeployedPolicies (deployedPolicyMap.isEmpty())==true
229             assertThatThrownBy(() -> {
230                 operationalPolicyProvider.fetchDeployedOperationalPolicies(POLICY_NAME);
231             }).hasMessage("could not find policy with ID " + POLICY_NAME + " and type " + POLICY_TYPE_ID
232                     + " deployed in any pdp group");
233
234             // Update pdpSubGroup
235             pdpSubGroup.setPolicies(new ArrayList<>());
236             pdpSubGroup.getPolicies()
237                     .add(new ToscaPolicyIdentifier(POLICY_NAME, POLICY_VERSION + LEGACY_MINOR_PATCH_SUFFIX));
238             assertEquals(1,
239                     databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0).getPolicies().size());
240
241             // Test fetchDeployedPolicies
242             assertThatCode(() -> {
243                 operationalPolicyProvider.fetchDeployedOperationalPolicies(POLICY_NAME);
244             }).doesNotThrowAnyException();
245
246             // Test validateDeleteEligibility exception path(!pdpGroups.isEmpty())
247             assertThatThrownBy(() -> {
248                 operationalPolicyProvider.deleteOperationalPolicy(POLICY_NAME, POLICY_VERSION);
249             }).hasMessageContaining("policy is in use, it is deployed in PDP group group subgroup type");
250         } catch (Exception exc) {
251             fail("Test should not throw an exception");
252         }
253     }
254
255     @Test
256     public void testCreateOperationalPolicy() throws Exception {
257
258         assertThatThrownBy(() -> {
259             String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
260             LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
261             operationalPolicyProvider.createOperationalPolicy(policyToCreate);
262         }).hasMessageContaining(
263                 "no policy types are defined on the service template for the policies in the topology template");
264
265         ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder
266                 .decode(ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
267         policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
268
269         String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
270         LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
271         LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate);
272         assertNotNull(createdPolicy);
273         assertEquals("operational.restart", createdPolicy.getPolicyId());
274         assertTrue(createdPolicy.getContent().startsWith("controlLoop%3A%0A%20%20version%3A%202.0.0%0A%20%20"));
275
276         String defaultPolicyVersionString = ResourceUtils.getResourceAsString(POLICY_RESOURCE_WITH_NO_VERSION);
277         LegacyOperationalPolicy defaultPolicyVersionPolicy =
278                 standardCoder.decode(defaultPolicyVersionString, LegacyOperationalPolicy.class);
279         createdPolicy = operationalPolicyProvider.createOperationalPolicy(defaultPolicyVersionPolicy);
280         assertEquals("1", createdPolicy.getPolicyVersion());
281
282         assertThatCode(() -> {
283             String duplicatePolicyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
284             LegacyOperationalPolicy duplicatePolicyToCreate =
285                     standardCoder.decode(duplicatePolicyString, LegacyOperationalPolicy.class);
286             operationalPolicyProvider.createOperationalPolicy(duplicatePolicyToCreate);
287         }).doesNotThrowAnyException();
288
289         assertThatThrownBy(() -> {
290             String duplicatePolicyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
291             LegacyOperationalPolicy duplicatePolicyToCreate =
292                     standardCoder.decode(duplicatePolicyString, LegacyOperationalPolicy.class);
293             duplicatePolicyToCreate.setContent("some other content");
294             operationalPolicyProvider.createOperationalPolicy(duplicatePolicyToCreate);
295         }).hasMessageContaining("INVALID:entity in incoming fragment does not equal existing entity");
296     }
297
298     @Test
299     public void testDeleteOperationalPolicyException() {
300         String policyId = "operational.restart";
301         String policyVersion = "1";
302         String policyTypeVersion = "1.0.0";
303         String policyTypeId = "onap.policies.controlloop.Operational";
304         String legacyMinorPatchSuffix = ".0.0";
305
306         try (PolicyModelsProvider databaseProvider =
307                 new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParams)) {
308             assertEquals(0, databaseProvider.getPdpGroups("name").size());
309             assertEquals(0, databaseProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).size());
310
311             assertNotNull(databaseProvider.createPdpGroups(new ArrayList<>()));
312             assertNotNull(databaseProvider.updatePdpGroups(new ArrayList<>()));
313
314             PdpGroup pdpGroup = new PdpGroup();
315             pdpGroup.setName("group");
316             pdpGroup.setVersion("1.2.3");
317             pdpGroup.setPdpGroupState(PdpState.ACTIVE);
318             pdpGroup.setPdpSubgroups(new ArrayList<>());
319             List<PdpGroup> groupList = new ArrayList<>();
320             groupList.add(pdpGroup);
321
322             PdpSubGroup pdpSubGroup = new PdpSubGroup();
323             pdpSubGroup.setPdpType("type");
324             pdpSubGroup.setDesiredInstanceCount(123);
325             pdpSubGroup.setSupportedPolicyTypes(new ArrayList<>());
326             pdpSubGroup.getSupportedPolicyTypes().add(new ToscaPolicyTypeIdentifier(policyTypeId, policyTypeVersion));
327             pdpGroup.getPdpSubgroups().add(pdpSubGroup);
328
329             Pdp pdp = new Pdp();
330             pdp.setInstanceId("type-0");
331             pdp.setMessage("Hello");
332             pdp.setPdpState(PdpState.ACTIVE);
333             pdp.setHealthy(PdpHealthStatus.UNKNOWN);
334             pdpSubGroup.setPdpInstances(new ArrayList<>());
335             pdpSubGroup.getPdpInstances().add(pdp);
336
337             // Create Pdp Groups
338             assertEquals(123, databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0)
339                     .getDesiredInstanceCount());
340             assertEquals(1, databaseProvider.getPdpGroups("group").size());
341
342             // Create Policy Type
343             assertThatCode(() -> {
344                 ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder
345                         .decode(ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
346                 policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
347             }).doesNotThrowAnyException();
348
349             // Create Policy
350             assertThatCode(() -> {
351                 String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
352                 LegacyOperationalPolicy policyToCreate =
353                         standardCoder.decode(policyString, LegacyOperationalPolicy.class);
354                 LegacyOperationalPolicy createdPolicy =
355                         operationalPolicyProvider.createOperationalPolicy(policyToCreate);
356                 assertNotNull(createdPolicy);
357             }).doesNotThrowAnyException();
358
359             // Update pdpSubGroup
360             pdpSubGroup.setPolicies(new ArrayList<>());
361             pdpSubGroup.getPolicies().add(new ToscaPolicyIdentifier(policyId, policyVersion + legacyMinorPatchSuffix));
362             assertEquals(1,
363                     databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0).getPolicies().size());
364             assertThatThrownBy(() -> {
365                 operationalPolicyProvider.deleteOperationalPolicy(policyId, policyVersion);
366             }).hasMessageContaining("policy is in use, it is deployed in PDP group group subgroup type");
367         } catch (Exception exc) {
368             fail("Test should not throw an exception");
369         }
370     }
371
372     @Test
373     public void testDeleteOperationalPolicy() {
374
375         assertThatThrownBy(() -> {
376             operationalPolicyProvider.deleteOperationalPolicy("dummy", null);
377         }).hasMessageMatching("^policyVersion is marked .*on.*ull but is null$");
378
379         assertThatThrownBy(() -> {
380             operationalPolicyProvider.deleteOperationalPolicy("dummy", "dummy");
381         }).hasMessageContaining("parameter \"version\": value \"dummy.0.0\", does not match regular expression");
382
383         assertThatCode(() -> {
384             ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder
385                     .decode(ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
386             policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
387
388             String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
389             LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
390             LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate);
391             assertNotNull(createdPolicy);
392
393             LegacyOperationalPolicy deletedPolicy =
394                     operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "1");
395             assertNotNull(deletedPolicy);
396             assertEquals("operational.restart", deletedPolicy.getPolicyId());
397             assertTrue(deletedPolicy.getContent().startsWith("controlLoop%3A%0A%20%20version%3A%202.0.0%0A%20%20"));
398         }).doesNotThrowAnyException();
399
400         assertThatThrownBy(() -> {
401             operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "1");
402         }).hasMessage("no policy found for policy: operational.restart:1");
403
404         assertThatCode(() -> {
405             policyTypeProvider.deletePolicyType("onap.policies.controlloop.Operational", "1.0.0");
406         }).doesNotThrowAnyException();
407     }
408 }