Limit statistics record count
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / rest / StatisticsRestProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020-2021 Nordix Foundation.
4  *  Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pap.main.rest;
23
24 import java.time.Instant;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import javax.ws.rs.core.Response;
30 import org.onap.policy.common.utils.services.Registry;
31 import org.onap.policy.models.base.PfModelException;
32 import org.onap.policy.models.base.PfModelRuntimeException;
33 import org.onap.policy.models.pdp.concepts.PdpStatistics;
34 import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters;
35 import org.onap.policy.models.provider.PolicyModelsProvider;
36 import org.onap.policy.pap.main.PapConstants;
37 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
38 import org.onap.policy.pap.main.startstop.PapActivator;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Class to fetch statistics of pap component.
44  *
45  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
46  */
47 public class StatisticsRestProvider {
48     private static final Logger LOGGER = LoggerFactory.getLogger(StatisticsRestProvider.class);
49     private static final String GET_STATISTICS_ERR_MSG = "fetch database failed";
50     private static final String DEFAULT_GROUP = "defaultGroup";
51     private static final int MIN_RECORD_COUNT = 1;
52     private static final int MAX_RECORD_COUNT = 100;
53
54     /**
55      * Returns the current statistics of pap component.
56      *
57      * @return Report containing statistics of pap component
58      */
59     public StatisticsReport fetchCurrentStatistics() {
60         final var report = new StatisticsReport();
61         report.setCode(Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class).isAlive() ? 200 : 500);
62
63         PapStatisticsManager mgr = Registry.get(PapConstants.REG_STATISTICS_MANAGER, PapStatisticsManager.class);
64         report.setTotalPdpCount(mgr.getTotalPdpCount());
65         report.setTotalPdpGroupCount(mgr.getTotalPdpGroupCount());
66         report.setTotalPolicyDownloadCount(mgr.getTotalPolicyDownloadCount());
67         report.setPolicyDownloadSuccessCount(mgr.getPolicyDownloadSuccessCount());
68         report.setPolicyDownloadFailureCount(mgr.getPolicyDownloadFailureCount());
69         report.setTotalPolicyDeployCount(mgr.getTotalPolicyDeployCount());
70         report.setPolicyDeploySuccessCount(mgr.getPolicyDeploySuccessCount());
71         report.setPolicyDeployFailureCount(mgr.getPolicyDeployFailureCount());
72
73         return report;
74     }
75
76     /**
77      * Returns statistics of pdp component from database.
78      *
79      * @param groupName name of the PDP group
80      * @param subType type of the sub PDP group
81      * @param pdpName the name of the PDP
82      * @param recordCount the count to query from database
83      * @return Report containing statistics of pdp component
84      * @throws PfModelException when database can not found
85      */
86     public Map<String, Map<String, List<PdpStatistics>>> fetchDatabaseStatistics(String groupName, String subType,
87             String pdpName, int recordCount) throws PfModelException {
88         final PolicyModelsProviderFactoryWrapper modelProviderWrapper =
89                 Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class);
90         try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) {
91             Instant startTime = null;
92             Instant endTime = null;
93
94             /*
95              * getFilteredPdpStatistics() will throw an NPE if a group name is not specified, so we
96              * provide a default value
97              */
98             String grpnm = (groupName != null ? groupName : DEFAULT_GROUP);
99
100             int nrecords = Math.min(MAX_RECORD_COUNT, Math.max(MIN_RECORD_COUNT, recordCount));
101
102             return generatePdpStatistics(databaseProvider.getFilteredPdpStatistics(
103                             PdpFilterParameters.builder().name(pdpName).group(grpnm)
104                             .subGroup(subType).startTime(startTime).endTime(endTime)
105                             .recordNum(nrecords).build()));
106
107         } catch (final PfModelException exp) {
108             String errorMessage = GET_STATISTICS_ERR_MSG + "groupName:" + groupName + "subType:" + subType + "pdpName:"
109                     + pdpName + exp.getMessage();
110             LOGGER.debug(errorMessage, exp);
111             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
112         }
113     }
114
115     /**
116      * generate the statistics of pap component by group/subgroup.
117      *
118      */
119     private Map<String, Map<String, List<PdpStatistics>>> generatePdpStatistics(List<PdpStatistics> pdpStatisticsList) {
120         Map<String, Map<String, List<PdpStatistics>>> groupMap = new HashMap<>();
121         if (pdpStatisticsList != null) {
122             pdpStatisticsList.stream().forEach(s -> {
123                 String curGroup = s.getPdpGroupName();
124                 String curSubGroup = s.getPdpSubGroupName();
125                 groupMap.computeIfAbsent(curGroup, curGroupMap -> new HashMap<>())
126                         .computeIfAbsent(curSubGroup, curSubGroupList -> new ArrayList<>()).add(s);
127             });
128         }
129         return groupMap;
130     }
131 }
132
133