Adding deployment metrics to PAP
[policy/pap.git] / main / src / test / java / org / onap / policy / pap / main / rest / e2e / End2EndBase.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019-2020 Nordix Foundation.
7  * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.rest.e2e;
24
25 import io.micrometer.core.instrument.MeterRegistry;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Optional;
33 import org.junit.After;
34 import org.onap.policy.common.parameters.ValidationResult;
35 import org.onap.policy.common.utils.coder.Coder;
36 import org.onap.policy.common.utils.coder.CoderException;
37 import org.onap.policy.common.utils.coder.StandardCoder;
38 import org.onap.policy.common.utils.resources.PrometheusUtils;
39 import org.onap.policy.common.utils.resources.ResourceUtils;
40 import org.onap.policy.models.base.PfConceptKey;
41 import org.onap.policy.models.base.PfModelException;
42 import org.onap.policy.models.pdp.concepts.PdpGroup;
43 import org.onap.policy.models.pdp.concepts.PdpGroups;
44 import org.onap.policy.models.pdp.concepts.PdpPolicyStatus;
45 import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.State;
46 import org.onap.policy.models.pdp.concepts.PdpStatistics;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
48 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
49 import org.onap.policy.pap.main.PolicyPapRuntimeException;
50 import org.onap.policy.pap.main.repository.ToscaServiceTemplateRepository;
51 import org.onap.policy.pap.main.rest.CommonPapRestServer;
52 import org.onap.policy.pap.main.service.PdpGroupService;
53 import org.onap.policy.pap.main.service.PdpStatisticsService;
54 import org.onap.policy.pap.main.service.PolicyStatusService;
55 import org.onap.policy.pap.main.service.ToscaServiceTemplateService;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.yaml.snakeyaml.Yaml;
60
61 public abstract class End2EndBase extends CommonPapRestServer {
62     private static final Logger logger = LoggerFactory.getLogger(End2EndBase.class);
63
64     private static final Coder coder = new StandardCoder();
65     private static final Yaml yaml = new Yaml();
66
67     /**
68      * Context - should be initialized by setUp() method.
69      */
70     protected End2EndContext context = null;
71
72     @Autowired
73     public PdpGroupService pdpGroupService;
74
75     @Autowired
76     public PdpStatisticsService pdpStatisticsService;
77
78     @Autowired
79     private ToscaServiceTemplateRepository serviceTemplateRepository;
80
81     @Autowired
82     public PolicyStatusService policyStatusService;
83
84     @Autowired
85     public ToscaServiceTemplateService toscaService;
86
87     @Autowired
88     public MeterRegistry meterRegistry;
89
90     public String deploymentsCounterName = "pap_" + PrometheusUtils.POLICY_DEPLOYMENTS_METRIC;
91     public String[] deploymentSuccessTag = {PrometheusUtils.OPERATION_METRIC_LABEL, PrometheusUtils.DEPLOY_OPERATION,
92         PrometheusUtils.STATUS_METRIC_LABEL, State.SUCCESS.name()};
93     public String[] unDeploymentSuccessTag = {PrometheusUtils.OPERATION_METRIC_LABEL,
94         PrometheusUtils.UNDEPLOY_OPERATION, PrometheusUtils.STATUS_METRIC_LABEL, State.SUCCESS.name()};
95
96     /**
97      * Tears down.
98      */
99     @Override
100     @After
101     public void tearDown() {
102         if (context != null) {
103             try {
104                 context.stop();
105             } catch (final Exception e) {
106                 logger.warn("failed to stop end-to-end context", e);
107             }
108             context = null;
109         }
110         meterRegistry.clear();
111         super.tearDown();
112     }
113
114     /**
115      * Adds Tosca Policy Types to the DB.
116      *
117      * @param yamlFile name of the YAML file specifying the data to be loaded
118      * @throws PfModelException if a DAO error occurs
119      */
120     public void addToscaPolicyTypes(final String yamlFile) throws PfModelException {
121         final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
122         JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate);
123         serviceTemplateRepository.save(jpaToscaServiceTemplate);
124     }
125
126     /**
127      * Adds Tosca Policies to the DB.
128      *
129      * @param yamlFile name of the YAML file specifying the data to be loaded
130      * @throws PfModelException if a DAO error occurs
131      */
132     public void addToscaPolicies(final String yamlFile) throws PfModelException {
133         final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
134         JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate);
135         serviceTemplateRepository.save(jpaToscaServiceTemplate);
136     }
137
138     private JpaToscaServiceTemplate mergeWithExistingTemplate(ToscaServiceTemplate serviceTemplate) {
139         JpaToscaServiceTemplate jpaToscaServiceTemplate = new JpaToscaServiceTemplate(serviceTemplate);
140         Optional<JpaToscaServiceTemplate> dbServiceTemplateOpt = serviceTemplateRepository
141             .findById(new PfConceptKey(JpaToscaServiceTemplate.DEFAULT_NAME, JpaToscaServiceTemplate.DEFAULT_VERSION));
142         if (!dbServiceTemplateOpt.isEmpty()) {
143             JpaToscaServiceTemplate dbServiceTemplate = dbServiceTemplateOpt.get();
144             if (dbServiceTemplate.getPolicyTypes() != null) {
145                 jpaToscaServiceTemplate.setPolicyTypes(dbServiceTemplate.getPolicyTypes());
146             }
147             if (dbServiceTemplate.getDataTypes() != null) {
148                 jpaToscaServiceTemplate.setDataTypes(dbServiceTemplate.getDataTypes());
149             }
150             if (dbServiceTemplate.getTopologyTemplate() != null) {
151                 jpaToscaServiceTemplate.setTopologyTemplate(dbServiceTemplate.getTopologyTemplate());
152             }
153         }
154
155         return jpaToscaServiceTemplate;
156     }
157
158     /**
159      * Adds PDP groups to the DB.
160      *
161      * @param jsonFile name of the JSON file specifying the data to be loaded
162      * @throws PfModelException if a DAO error occurs
163      */
164     public void addGroups(final String jsonFile) throws PfModelException {
165         final PdpGroups groups = loadJsonFile(jsonFile, PdpGroups.class);
166
167         final ValidationResult result = groups.validatePapRest();
168         if (!result.isValid()) {
169             throw new PolicyPapRuntimeException("cannot init DB groups from " + jsonFile + ":\n" + result.getResult());
170         }
171
172         pdpGroupService.createPdpGroups(groups.getGroups());
173     }
174
175     /**
176      * Fetch PDP groups from the DB.
177      *
178      * @param name name of the pdpGroup
179      * @throws PfModelException if a DAO error occurs
180      */
181     public List<PdpGroup> fetchGroups(final String name) throws PfModelException {
182         return pdpGroupService.getPdpGroups(name);
183     }
184
185     /**
186      * Fetch PDP statistics from the DB.
187      *
188      * @param instanceId name of the pdpStatistics
189      * @param groupName name of the pdpGroup
190      * @param subGroupName name of the pdpSubGroup
191      * @throws PfModelException if a DAO error occurs
192      */
193     public Map<String, Map<String, List<PdpStatistics>>> fetchPdpStatistics(final String instanceId,
194         final String groupName, final String subGroupName) throws PfModelException {
195         return pdpStatisticsService.fetchDatabaseStatistics(groupName, subGroupName, instanceId, 100, null, null);
196     }
197
198     /**
199      * Adds PdpPolicyStatus records to the DB.
200      *
201      * @param jsonFile name of the JSON file specifying the data to be loaded
202      * @throws PfModelException if a DAO error occurs
203      */
204     public void addPdpPolicyStatus(final String jsonFile) throws PfModelException {
205         final PolicyStatusRecords data = loadJsonFile(jsonFile, PolicyStatusRecords.class);
206         policyStatusService.cudPolicyStatus(data.records, null, null);
207     }
208
209     /**
210      * Loads an object from a YAML file.
211      *
212      * @param fileName name of the file from which to load
213      * @param clazz the class of the object to be loaded
214      * @return the object that was loaded from the file
215      */
216     protected static <T> T loadYamlFile(final String fileName, final Class<T> clazz) {
217         final File propFile = new File(ResourceUtils.getFilePath4Resource("e2e/" + fileName));
218
219         try (FileInputStream input = new FileInputStream(propFile)) {
220             final Object yamlObject = yaml.load(input);
221             final String json = coder.encode(yamlObject);
222             final T result = coder.decode(json, clazz);
223
224             if (result == null) {
225                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
226             }
227
228             return result;
229
230         } catch (final FileNotFoundException e) {
231             throw new PolicyPapRuntimeException("cannot find " + fileName, e);
232
233         } catch (IOException | CoderException e) {
234             throw new PolicyPapRuntimeException("cannot decode " + fileName, e);
235         }
236     }
237
238     /**
239      * Loads an object from a JSON file.
240      *
241      * @param fileName name of the file from which to load
242      * @param clazz the class of the object to be loaded
243      * @return the object that was loaded from the file
244      */
245     protected static <T> T loadJsonFile(final String fileName, final Class<T> clazz) {
246         final String fileName2 = (fileName.startsWith("src/") ? fileName : "e2e/" + fileName);
247         final File propFile = new File(ResourceUtils.getFilePath4Resource(fileName2));
248         try {
249             final T result = coder.decode(propFile, clazz);
250
251             if (result == null) {
252                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
253             }
254
255             return result;
256
257         } catch (final CoderException e) {
258             throw new RuntimeException(e);
259         }
260     }
261
262     public class PolicyStatusRecords {
263         private List<PdpPolicyStatus> records;
264     }
265 }