You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@ranger.apache.org by "RakeshGuptaDev (via GitHub)" <gi...@apache.org> on 2026/09/22 18:00:00 UTC
[PR] RANGER-5804: Support Ranger Admin for displaying audit metrics from OpenSearch [ranger]
RakeshGuptaDev opened a new pull request, #1251:
URL: https://github.com/apache/ranger/pull/1251
## What changes were proposed in this pull request?
This patch adds OpenSearch support for Ranger Admin audit metrics APIs and refactors shared metrics logic used by Solr and OpenSearch.
## How was this patch tested?
**Testing:**
Configured Ranger Admin with OpenSearch as the audit store and verified that all five audit metrics endpoints return the expected JSON responses.
**Endpoints covered:**
- GET /audit/metrics
- GET /audit/metrics/{id}
- GET /audit/metrics/servicetype/{type}/servicename/{name}
- GET /audit/dailymetrics
- GET /audit/daysmetrics
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@ranger.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] RANGER-5804: Support Ranger Admin for displaying audit metrics from OpenSearch [ranger]
Posted by "rameeshm (via GitHub)" <gi...@apache.org>.
rameeshm commented on code in PR #1251:
URL: https://github.com/apache/ranger/pull/1251#discussion_r4088486140
##########
security-admin/src/main/java/org/apache/ranger/opensearch/OpenSearchAuditMetricsHelper.java:
##########
@@ -0,0 +1,513 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.opensearch;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.entity.ContentType;
+import org.apache.http.nio.entity.NStringEntity;
+import org.apache.http.util.EntityUtils;
+import org.apache.ranger.audit.metrics.AuditMetricsHelper;
+import org.apache.ranger.audit.metrics.AuditMetricsHelper.FilterParams;
+import org.apache.ranger.common.MessageEnums;
+import org.apache.ranger.common.RESTErrorUtil;
+import org.apache.ranger.entity.XXService;
+import org.apache.ranger.plugin.model.RangerAuditMetrics;
+import org.apache.ranger.plugin.model.RangerAuditMetricsByDays;
+import org.apache.ranger.plugin.model.RangerAuditMetricsByHours;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.elasticsearch.client.Request;
+import org.elasticsearch.client.Response;
+import org.elasticsearch.client.RestClient;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.io.IOException;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+@Component
+public class OpenSearchAuditMetricsHelper {
+ private static final Logger LOGGER = LoggerFactory.getLogger(OpenSearchAuditMetricsHelper.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static final String FACET_REPO = "per_repo";
+ private static final String FACET_AGENT = "per_agent";
+ private static final String FACET_CLIIP = "per_cliip";
+ private static final String FACET_CLUSTER = "per_cluster";
+ private static final int AGG_SIZE = 10000;
+ private static final String MISSING_BUCKET = "";
+
+ @Autowired
+ OpenSearchMgr openSearchMgr;
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ AuditMetricsHelper auditMetricsHelper;
+
+ public RangerAuditMetrics getLatestAuditMetrics(String serviceType, String serviceName, String timezone) {
+ SearchFilter filter = auditMetricsHelper.buildSearchFilter(serviceType, serviceName, null, null, null);
+ List<Map<String, Object>> filters = buildMetricsFilters(filter);
+
+ applyLatestRangeFilter(filters, timezone);
+
+ Map<String, Object> queryBody = buildMetricsQueryBody(filters, null);
+ JsonNode response = runMetricsSearch(queryBody, "latest audit metrics");
+ long count = response.at("/hits/total/value").asLong(0L);
+
+ return auditMetricsHelper.buildAuditMetrics(serviceType, serviceName, null, null, null, count);
+ }
+
+ public List<RangerAuditMetrics> getLatestAuditMetricsList(SearchFilter filter, String timezone) {
+ List<Map<String, Object>> filters = buildMetricsFilters(filter);
+
+ applyLatestRangeFilter(filters, timezone);
+
+ Map<String, Object> aggregations = buildAuditMetricsListAggregation();
+ Map<String, Object> queryBody = buildMetricsQueryBody(filters, aggregations);
+ JsonNode response = runMetricsSearch(queryBody, "audit metrics list");
+
+ return extractAuditMetricsList(response, filter);
+ }
+
+ public List<RangerAuditMetricsByDays> getAuditMetricsByDays(int olderThanInDays, SearchFilter filter, String timezone) {
+ List<Map<String, Object>> filters = buildMetricsFilters(filter);
+
+ applyDaysRangeFilter(filters, olderThanInDays, timezone);
+
+ Map<String, Object> aggregations = buildDayAggregation(timezone);
+ Map<String, Object> queryBody = buildMetricsQueryBody(filters, aggregations);
+ JsonNode response = runMetricsSearch(queryBody, "audit metrics by days");
+
+ return extractAuditMetricsByDays(response, filter, timezone);
+ }
+
+ public String resolveServiceType(XXService service) {
+ return auditMetricsHelper.resolveServiceType(service);
+ }
+
+ public List<RangerAuditMetricsByHours> getAuditMetricsByHours(SearchFilter filter, String timezone) {
+ List<Map<String, Object>> filters = buildMetricsFilters(filter);
+
+ applyTodayRangeFilter(filters, timezone);
+
+ Map<String, Object> aggregations = buildHourAggregation(timezone);
+ Map<String, Object> queryBody = buildMetricsQueryBody(filters, aggregations);
+ JsonNode response = runMetricsSearch(queryBody, "audit metrics by hours");
+
+ return extractAuditMetricsByHours(response, filter, timezone);
+ }
+
+ private Map<String, Object> buildMetricsQueryBody(List<Map<String, Object>> filters, Map<String, Object> aggregations) {
+ Map<String, Object> queryBody = new LinkedHashMap<>();
+
+ queryBody.put("size", 0);
+
+ Map<String, Object> boolQuery = new LinkedHashMap<>();
+
+ boolQuery.put("filter", filters.isEmpty() ? List.of(Map.of("match_all", Map.of())) : filters);
+ queryBody.put("query", Map.of("bool", boolQuery));
+
+ if (aggregations != null) {
+ queryBody.put("aggs", aggregations);
+ }
+
+ return queryBody;
+ }
+
+ private List<Map<String, Object>> buildMetricsFilters(SearchFilter filter) {
+ List<Map<String, Object>> filters = new ArrayList<>();
+
+ if (filter == null) {
+ return filters;
+ }
+
+ addMatchFilter(filters, "repo", filter.getParam(SearchFilter.SERVICE_NAME));
+ addMatchFilter(filters, "cluster", filter.getParam(SearchFilter.CLUSTER_NAME));
+ addMatchFilter(filters, "cliIP", filter.getParam(SearchFilter.CLIENT_IP));
+ addMatchFilter(filters, "agent", filter.getParam(SearchFilter.PLUGIN_APP_ID));
+
+ String serviceType = filter.getParam(SearchFilter.SERVICE_TYPE);
+
+ if (StringUtils.isNotBlank(serviceType)) {
+ long repoType = auditMetricsHelper.resolveRepoType(serviceType);
+
+ if (repoType == AuditMetricsHelper.MISSING_REPO_TYPE_SENTINEL) {
+ filters.add(Map.of("term", Map.of("repoType", -1)));
+ } else {
+ filters.add(Map.of("term", Map.of("repoType", repoType)));
+ }
+ }
+
+ return filters;
+ }
+
+ private void addMatchFilter(List<Map<String, Object>> filters, String field, String value) {
+ if (filters == null || StringUtils.isBlank(value)) {
+ return;
+ }
+
+ filters.add(Map.of("match_phrase", Map.of(field, value.trim().toLowerCase())));
+ }
+
+ private void applyLatestRangeFilter(List<Map<String, Object>> filters, String timezone) {
+ applyRangeFilter(filters, "now-1d", "now", timezone);
+ }
+
+ private void applyTodayRangeFilter(List<Map<String, Object>> filters, String timezone) {
+ applyRangeFilter(filters, "now/d", "now", timezone);
+ }
+
+ private void applyDaysRangeFilter(List<Map<String, Object>> filters, int olderThanInDays, String timezone) {
+ int daysBack = olderThanInDays - 1;
+
+ applyRangeFilter(filters, "now-" + daysBack + "d/d", "now", timezone);
+ }
+
+ private void applyRangeFilter(List<Map<String, Object>> filters, String from, String to, String timezone) {
+ if (filters == null) {
+ return;
+ }
+
+ Map<String, Object> rangeParams = new LinkedHashMap<>();
+
+ rangeParams.put("from", from);
+ rangeParams.put("to", to);
+
+ ZoneId zoneId = auditMetricsHelper.parseZoneId(timezone);
+
+ if (zoneId != null) {
+ rangeParams.put("time_zone", zoneId.getId());
+ }
+
+ filters.add(Map.of("range", Map.of("evtTime", rangeParams)));
+ }
+
+ private Map<String, Object> buildAuditMetricsListAggregation() {
+ Map<String, Object> perClusterTerms = new LinkedHashMap<>();
+
+ perClusterTerms.put("field", "cluster");
+ perClusterTerms.put("size", AGG_SIZE);
+ perClusterTerms.put("missing", MISSING_BUCKET);
+
+ Map<String, Object> perCluster = new LinkedHashMap<>();
+
+ perCluster.put("terms", perClusterTerms);
+
+ Map<String, Object> perCliIpAggs = new LinkedHashMap<>();
+
+ perCliIpAggs.put(FACET_CLUSTER, perCluster);
+
+ Map<String, Object> perCliIpTerms = new LinkedHashMap<>();
+
+ perCliIpTerms.put("field", "cliIP");
+ perCliIpTerms.put("size", AGG_SIZE);
+ perCliIpTerms.put("missing", MISSING_BUCKET);
+
+ Map<String, Object> perCliIp = new LinkedHashMap<>();
+
+ perCliIp.put("terms", perCliIpTerms);
+ perCliIp.put("aggs", perCliIpAggs);
+
+ Map<String, Object> perAgentAggs = new LinkedHashMap<>();
+
+ perAgentAggs.put(FACET_CLIIP, perCliIp);
+
+ Map<String, Object> perAgentTerms = new LinkedHashMap<>();
+
+ perAgentTerms.put("field", "agent");
+ perAgentTerms.put("size", AGG_SIZE);
+ perAgentTerms.put("missing", MISSING_BUCKET);
+
+ Map<String, Object> perAgent = new LinkedHashMap<>();
+
+ perAgent.put("terms", perAgentTerms);
+ perAgent.put("aggs", perAgentAggs);
+
+ Map<String, Object> perRepoAggs = new LinkedHashMap<>();
+
+ perRepoAggs.put(FACET_AGENT, perAgent);
+
+ Map<String, Object> perRepoTerms = new LinkedHashMap<>();
+
+ perRepoTerms.put("field", "repo");
+ perRepoTerms.put("size", AGG_SIZE);
+ perRepoTerms.put("order", Map.of("_count", "desc"));
+
+ Map<String, Object> perRepo = new LinkedHashMap<>();
+
+ perRepo.put("terms", perRepoTerms);
+ perRepo.put("aggs", perRepoAggs);
+
+ Map<String, Object> aggregations = new LinkedHashMap<>();
+
+ aggregations.put(FACET_REPO, perRepo);
+
+ return aggregations;
+ }
+
+ private Map<String, Object> buildDayAggregation(String timezone) {
+ Map<String, Object> dateHistogram = new LinkedHashMap<>();
+
+ dateHistogram.put("field", "evtTime");
+ dateHistogram.put("calendar_interval", "1d");
+
+ ZoneId zoneId = auditMetricsHelper.parseZoneId(timezone);
+
+ if (zoneId != null) {
+ dateHistogram.put("time_zone", zoneId.getId());
+ }
+
+ return Map.of("per_day", Map.of("date_histogram", dateHistogram));
+ }
+
+ private Map<String, Object> buildHourAggregation(String timezone) {
+ Map<String, Object> dateHistogram = new LinkedHashMap<>();
+
+ dateHistogram.put("field", "evtTime");
+ dateHistogram.put("fixed_interval", "1h");
+
+ ZoneId zoneId = auditMetricsHelper.parseZoneId(timezone);
+
+ if (zoneId != null) {
+ dateHistogram.put("time_zone", zoneId.getId());
+ }
+
+ return Map.of("per_hour", Map.of("date_histogram", dateHistogram));
+ }
+
+ private JsonNode runMetricsSearch(Map<String, Object> queryBody, String context) {
+ RestClient client = openSearchMgr.getClient();
+
+ if (client == null) {
+ LOGGER.warn("OpenSearch client is null, so not running the query.");
+
+ throw restErrorUtil.createRESTException("Error connecting to search engine", MessageEnums.ERROR_SYSTEM);
+ }
+
+ JsonNode result;
+
+ try {
+ String body = MAPPER.writeValueAsString(queryBody);
+ Request request = new Request("POST", "/" + openSearchMgr.getIndex() + "/_search");
+
+ request.setEntity(new NStringEntity(body, ContentType.APPLICATION_JSON));
+
+ Response response = client.performRequest(request);
Review Comment:
Do we need this check? line 336 will catch the IOException right?
##########
security-admin/src/main/java/org/apache/ranger/rest/AuditMetricsREST.java:
##########
@@ -104,7 +116,11 @@ public RangerAuditMetrics getAuditMetrics(@PathParam("id") Long id, @QueryParam(
LOG.debug("==> AuditMetricsREST.getAuditMetrics(id={})", id);
RangerAuditMetrics ret;
try {
- ret = solrAccessAuditsService.getAuditMetrics(id, timezone);
+ if (RangerBizUtil.AUDIT_STORE_OPENSEARCH.equalsIgnoreCase(rangerBizUtil.getAuditDBType())) {
Review Comment:
Can we introduce AccessAuditsMetricsService interface and use the implementation of it to refer solrAccessAuditsService, openSearchAccessAuditsService and other implementation like cloudwatchAccessAuditsService etc. allowing the controller to depend on a factory or the correctly autowired bean
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@ranger.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] RANGER-5804: Support Ranger Admin for displaying audit metrics from OpenSearch [ranger]
Posted by "rameeshm (via GitHub)" <gi...@apache.org>.
rameeshm commented on code in PR #1251:
URL: https://github.com/apache/ranger/pull/1251#discussion_r4088405069
##########
security-admin/src/main/java/org/apache/ranger/audit/metrics/AuditMetricsHelper.java:
##########
@@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.audit.metrics;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.ranger.db.RangerDaoManager;
+import org.apache.ranger.entity.XXService;
+import org.apache.ranger.entity.XXServiceDef;
+import org.apache.ranger.plugin.model.RangerAuditMetrics;
+import org.apache.ranger.plugin.model.RangerAuditMetricsByDays;
+import org.apache.ranger.plugin.model.RangerAuditMetricsByHours;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.time.DateTimeException;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeParseException;
+import java.util.Date;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+@Component
+public class AuditMetricsHelper {
+ private static final Logger LOGGER = LoggerFactory.getLogger(AuditMetricsHelper.class);
+
+ public static final long MISSING_REPO_TYPE_SENTINEL = -1L;
+
+ private final Map<String, Long> repoTypeByServiceType = new ConcurrentHashMap<>();
+
+ @Autowired
+ RangerDaoManager daoManager;
+
+ public SearchFilter buildSearchFilter(String serviceType, String serviceName, String appId, String clusterName, String clientIP) {
+ SearchFilter filter = new SearchFilter();
+
+ filter.setParam(SearchFilter.SERVICE_TYPE, serviceType);
+ filter.setParam(SearchFilter.SERVICE_NAME, serviceName);
+ filter.setParam(SearchFilter.PLUGIN_APP_ID, appId);
+ filter.setParam(SearchFilter.CLUSTER_NAME, clusterName);
+ filter.setParam(SearchFilter.CLIENT_IP, clientIP);
+
+ return filter;
+ }
+
+ public FilterParams getFilterParams(SearchFilter filter) {
+ FilterParams params = new FilterParams();
+
+ if (filter != null) {
+ params.serviceType = filter.getParam(SearchFilter.SERVICE_TYPE);
+ params.serviceName = filter.getParam(SearchFilter.SERVICE_NAME);
+ params.appId = filter.getParam(SearchFilter.PLUGIN_APP_ID);
+ params.clusterName = filter.getParam(SearchFilter.CLUSTER_NAME);
+ params.clientIP = filter.getParam(SearchFilter.CLIENT_IP);
+ }
+
+ return params;
+ }
+
+ public RangerAuditMetrics buildAuditMetrics(String serviceType, String serviceName, String appId, String clusterName, String clientIP, long count) {
+ RangerAuditMetrics metric = new RangerAuditMetrics();
+
+ metric.setServiceName(serviceName);
+ metric.setServiceType(resolveServiceType(serviceType, serviceName));
+ metric.setAppId(appId);
+ metric.setClusterName(clusterName);
+ metric.setClientIP(clientIP);
+ metric.setNumberOfAudits(count);
+
+ Long serviceId = resolveServiceId(serviceName);
+
+ if (serviceId != null) {
+ metric.setId(serviceId);
+ }
+
+ return metric;
+ }
+
+ public RangerAuditMetricsByDays buildAuditMetricsByDays(FilterParams params, Long auditDate, long count) {
+ return new RangerAuditMetricsByDays(params.serviceType, params.serviceName, params.appId, params.clusterName, params.clientIP, auditDate, count);
+ }
+
+ public RangerAuditMetricsByHours buildAuditMetricsByHours(FilterParams params, int hour, long count) {
+ return new RangerAuditMetricsByHours(params.serviceType, params.serviceName, params.appId, params.clusterName, params.clientIP, hour, count);
+ }
+
+ public Long resolveServiceId(String serviceName) {
+ Long ret = null;
+
+ if (StringUtils.isNotBlank(serviceName) && daoManager != null && daoManager.getXXService() != null) {
+ XXService service = daoManager.getXXService().findByName(serviceName);
+
+ if (service != null) {
+ ret = service.getId();
+ }
+ }
+
+ return ret;
+ }
+
+ public String resolveServiceType(XXService service) {
+ String ret = null;
+
+ if (service != null && daoManager != null && daoManager.getXXServiceDef() != null) {
+ XXServiceDef serviceDef = daoManager.getXXServiceDef().getById(service.getType());
+
+ if (serviceDef != null) {
+ ret = serviceDef.getName();
+ }
+ }
+
+ return ret;
+ }
+
+ public String resolveServiceType(String serviceType, String serviceName) {
+ String ret = serviceType;
+
+ if (StringUtils.isBlank(ret)) {
+ if (StringUtils.isNotBlank(serviceName) && daoManager != null && daoManager.getXXService() != null) {
+ XXService service = daoManager.getXXService().findByName(serviceName);
+ ret = resolveServiceType(service);
+ } else {
+ ret = null;
+ }
+ }
+
+ return ret;
+ }
+
+ public long resolveRepoType(String serviceType) {
+ if (StringUtils.isBlank(serviceType)) {
+ return MISSING_REPO_TYPE_SENTINEL;
Review Comment:
Please do long ret = MISSING_REPO_TYPE_SENTINEL and return "ret" like how other methods does
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@ranger.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] RANGER-5804: Support Ranger Admin for displaying audit metrics from OpenSearch [ranger]
Posted by "RakeshGuptaDev (via GitHub)" <gi...@apache.org>.
RakeshGuptaDev commented on code in PR #1251:
URL: https://github.com/apache/ranger/pull/1251#discussion_r4092073914
##########
security-admin/src/main/java/org/apache/ranger/opensearch/OpenSearchAuditMetricsHelper.java:
##########
@@ -0,0 +1,513 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.opensearch;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.entity.ContentType;
+import org.apache.http.nio.entity.NStringEntity;
+import org.apache.http.util.EntityUtils;
+import org.apache.ranger.audit.metrics.AuditMetricsHelper;
+import org.apache.ranger.audit.metrics.AuditMetricsHelper.FilterParams;
+import org.apache.ranger.common.MessageEnums;
+import org.apache.ranger.common.RESTErrorUtil;
+import org.apache.ranger.entity.XXService;
+import org.apache.ranger.plugin.model.RangerAuditMetrics;
+import org.apache.ranger.plugin.model.RangerAuditMetricsByDays;
+import org.apache.ranger.plugin.model.RangerAuditMetricsByHours;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.elasticsearch.client.Request;
+import org.elasticsearch.client.Response;
+import org.elasticsearch.client.RestClient;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.io.IOException;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+@Component
+public class OpenSearchAuditMetricsHelper {
+ private static final Logger LOGGER = LoggerFactory.getLogger(OpenSearchAuditMetricsHelper.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static final String FACET_REPO = "per_repo";
+ private static final String FACET_AGENT = "per_agent";
+ private static final String FACET_CLIIP = "per_cliip";
+ private static final String FACET_CLUSTER = "per_cluster";
+ private static final int AGG_SIZE = 10000;
+ private static final String MISSING_BUCKET = "";
+
+ @Autowired
+ OpenSearchMgr openSearchMgr;
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ AuditMetricsHelper auditMetricsHelper;
+
+ public RangerAuditMetrics getLatestAuditMetrics(String serviceType, String serviceName, String timezone) {
+ SearchFilter filter = auditMetricsHelper.buildSearchFilter(serviceType, serviceName, null, null, null);
+ List<Map<String, Object>> filters = buildMetricsFilters(filter);
+
+ applyLatestRangeFilter(filters, timezone);
+
+ Map<String, Object> queryBody = buildMetricsQueryBody(filters, null);
+ JsonNode response = runMetricsSearch(queryBody, "latest audit metrics");
+ long count = response.at("/hits/total/value").asLong(0L);
+
+ return auditMetricsHelper.buildAuditMetrics(serviceType, serviceName, null, null, null, count);
+ }
+
+ public List<RangerAuditMetrics> getLatestAuditMetricsList(SearchFilter filter, String timezone) {
+ List<Map<String, Object>> filters = buildMetricsFilters(filter);
+
+ applyLatestRangeFilter(filters, timezone);
+
+ Map<String, Object> aggregations = buildAuditMetricsListAggregation();
+ Map<String, Object> queryBody = buildMetricsQueryBody(filters, aggregations);
+ JsonNode response = runMetricsSearch(queryBody, "audit metrics list");
+
+ return extractAuditMetricsList(response, filter);
+ }
+
+ public List<RangerAuditMetricsByDays> getAuditMetricsByDays(int olderThanInDays, SearchFilter filter, String timezone) {
+ List<Map<String, Object>> filters = buildMetricsFilters(filter);
+
+ applyDaysRangeFilter(filters, olderThanInDays, timezone);
+
+ Map<String, Object> aggregations = buildDayAggregation(timezone);
+ Map<String, Object> queryBody = buildMetricsQueryBody(filters, aggregations);
+ JsonNode response = runMetricsSearch(queryBody, "audit metrics by days");
+
+ return extractAuditMetricsByDays(response, filter, timezone);
+ }
+
+ public String resolveServiceType(XXService service) {
+ return auditMetricsHelper.resolveServiceType(service);
+ }
+
+ public List<RangerAuditMetricsByHours> getAuditMetricsByHours(SearchFilter filter, String timezone) {
+ List<Map<String, Object>> filters = buildMetricsFilters(filter);
+
+ applyTodayRangeFilter(filters, timezone);
+
+ Map<String, Object> aggregations = buildHourAggregation(timezone);
+ Map<String, Object> queryBody = buildMetricsQueryBody(filters, aggregations);
+ JsonNode response = runMetricsSearch(queryBody, "audit metrics by hours");
+
+ return extractAuditMetricsByHours(response, filter, timezone);
+ }
+
+ private Map<String, Object> buildMetricsQueryBody(List<Map<String, Object>> filters, Map<String, Object> aggregations) {
+ Map<String, Object> queryBody = new LinkedHashMap<>();
+
+ queryBody.put("size", 0);
+
+ Map<String, Object> boolQuery = new LinkedHashMap<>();
+
+ boolQuery.put("filter", filters.isEmpty() ? List.of(Map.of("match_all", Map.of())) : filters);
+ queryBody.put("query", Map.of("bool", boolQuery));
+
+ if (aggregations != null) {
+ queryBody.put("aggs", aggregations);
+ }
+
+ return queryBody;
+ }
+
+ private List<Map<String, Object>> buildMetricsFilters(SearchFilter filter) {
+ List<Map<String, Object>> filters = new ArrayList<>();
+
+ if (filter == null) {
+ return filters;
+ }
+
+ addMatchFilter(filters, "repo", filter.getParam(SearchFilter.SERVICE_NAME));
+ addMatchFilter(filters, "cluster", filter.getParam(SearchFilter.CLUSTER_NAME));
+ addMatchFilter(filters, "cliIP", filter.getParam(SearchFilter.CLIENT_IP));
+ addMatchFilter(filters, "agent", filter.getParam(SearchFilter.PLUGIN_APP_ID));
+
+ String serviceType = filter.getParam(SearchFilter.SERVICE_TYPE);
+
+ if (StringUtils.isNotBlank(serviceType)) {
+ long repoType = auditMetricsHelper.resolveRepoType(serviceType);
+
+ if (repoType == AuditMetricsHelper.MISSING_REPO_TYPE_SENTINEL) {
+ filters.add(Map.of("term", Map.of("repoType", -1)));
+ } else {
+ filters.add(Map.of("term", Map.of("repoType", repoType)));
+ }
+ }
+
+ return filters;
+ }
+
+ private void addMatchFilter(List<Map<String, Object>> filters, String field, String value) {
+ if (filters == null || StringUtils.isBlank(value)) {
+ return;
+ }
+
+ filters.add(Map.of("match_phrase", Map.of(field, value.trim().toLowerCase())));
+ }
+
+ private void applyLatestRangeFilter(List<Map<String, Object>> filters, String timezone) {
+ applyRangeFilter(filters, "now-1d", "now", timezone);
+ }
+
+ private void applyTodayRangeFilter(List<Map<String, Object>> filters, String timezone) {
+ applyRangeFilter(filters, "now/d", "now", timezone);
+ }
+
+ private void applyDaysRangeFilter(List<Map<String, Object>> filters, int olderThanInDays, String timezone) {
+ int daysBack = olderThanInDays - 1;
+
+ applyRangeFilter(filters, "now-" + daysBack + "d/d", "now", timezone);
+ }
+
+ private void applyRangeFilter(List<Map<String, Object>> filters, String from, String to, String timezone) {
+ if (filters == null) {
+ return;
+ }
+
+ Map<String, Object> rangeParams = new LinkedHashMap<>();
+
+ rangeParams.put("from", from);
+ rangeParams.put("to", to);
+
+ ZoneId zoneId = auditMetricsHelper.parseZoneId(timezone);
+
+ if (zoneId != null) {
+ rangeParams.put("time_zone", zoneId.getId());
+ }
+
+ filters.add(Map.of("range", Map.of("evtTime", rangeParams)));
+ }
+
+ private Map<String, Object> buildAuditMetricsListAggregation() {
+ Map<String, Object> perClusterTerms = new LinkedHashMap<>();
+
+ perClusterTerms.put("field", "cluster");
+ perClusterTerms.put("size", AGG_SIZE);
+ perClusterTerms.put("missing", MISSING_BUCKET);
+
+ Map<String, Object> perCluster = new LinkedHashMap<>();
+
+ perCluster.put("terms", perClusterTerms);
+
+ Map<String, Object> perCliIpAggs = new LinkedHashMap<>();
+
+ perCliIpAggs.put(FACET_CLUSTER, perCluster);
+
+ Map<String, Object> perCliIpTerms = new LinkedHashMap<>();
+
+ perCliIpTerms.put("field", "cliIP");
+ perCliIpTerms.put("size", AGG_SIZE);
+ perCliIpTerms.put("missing", MISSING_BUCKET);
+
+ Map<String, Object> perCliIp = new LinkedHashMap<>();
+
+ perCliIp.put("terms", perCliIpTerms);
+ perCliIp.put("aggs", perCliIpAggs);
+
+ Map<String, Object> perAgentAggs = new LinkedHashMap<>();
+
+ perAgentAggs.put(FACET_CLIIP, perCliIp);
+
+ Map<String, Object> perAgentTerms = new LinkedHashMap<>();
+
+ perAgentTerms.put("field", "agent");
+ perAgentTerms.put("size", AGG_SIZE);
+ perAgentTerms.put("missing", MISSING_BUCKET);
+
+ Map<String, Object> perAgent = new LinkedHashMap<>();
+
+ perAgent.put("terms", perAgentTerms);
+ perAgent.put("aggs", perAgentAggs);
+
+ Map<String, Object> perRepoAggs = new LinkedHashMap<>();
+
+ perRepoAggs.put(FACET_AGENT, perAgent);
+
+ Map<String, Object> perRepoTerms = new LinkedHashMap<>();
+
+ perRepoTerms.put("field", "repo");
+ perRepoTerms.put("size", AGG_SIZE);
+ perRepoTerms.put("order", Map.of("_count", "desc"));
+
+ Map<String, Object> perRepo = new LinkedHashMap<>();
+
+ perRepo.put("terms", perRepoTerms);
+ perRepo.put("aggs", perRepoAggs);
+
+ Map<String, Object> aggregations = new LinkedHashMap<>();
+
+ aggregations.put(FACET_REPO, perRepo);
+
+ return aggregations;
+ }
+
+ private Map<String, Object> buildDayAggregation(String timezone) {
+ Map<String, Object> dateHistogram = new LinkedHashMap<>();
+
+ dateHistogram.put("field", "evtTime");
+ dateHistogram.put("calendar_interval", "1d");
+
+ ZoneId zoneId = auditMetricsHelper.parseZoneId(timezone);
+
+ if (zoneId != null) {
+ dateHistogram.put("time_zone", zoneId.getId());
+ }
+
+ return Map.of("per_day", Map.of("date_histogram", dateHistogram));
+ }
+
+ private Map<String, Object> buildHourAggregation(String timezone) {
+ Map<String, Object> dateHistogram = new LinkedHashMap<>();
+
+ dateHistogram.put("field", "evtTime");
+ dateHistogram.put("fixed_interval", "1h");
+
+ ZoneId zoneId = auditMetricsHelper.parseZoneId(timezone);
+
+ if (zoneId != null) {
+ dateHistogram.put("time_zone", zoneId.getId());
+ }
+
+ return Map.of("per_hour", Map.of("date_histogram", dateHistogram));
+ }
+
+ private JsonNode runMetricsSearch(Map<String, Object> queryBody, String context) {
+ RestClient client = openSearchMgr.getClient();
+
+ if (client == null) {
+ LOGGER.warn("OpenSearch client is null, so not running the query.");
+
+ throw restErrorUtil.createRESTException("Error connecting to search engine", MessageEnums.ERROR_SYSTEM);
+ }
+
+ JsonNode result;
+
+ try {
+ String body = MAPPER.writeValueAsString(queryBody);
+ Request request = new Request("POST", "/" + openSearchMgr.getIndex() + "/_search");
+
+ request.setEntity(new NStringEntity(body, ContentType.APPLICATION_JSON));
+
+ Response response = client.performRequest(request);
Review Comment:
Thanks for raising this — valid point to clarify.
You're right that catch (IOException) handles connection-level failures. However, performRequest() can return normally for HTTP 4xx/5xx responses with an error JSON body, without throwing an IOException. Without the status check, we could end up parsing the error response and returning empty/zero metrics instead of surfacing the failure.
So the two checks handle different failure scenarios:
- Status check — OpenSearch application-level errors (404 missing index, 400 bad query, 401/403 authentication, 503 cluster issues)
- catch (IOException) — Network/transport failures (host unreachable, timeout, connection reset)
I've kept the status validation and moved it into parseMetricsSearchResponse() to make this separation clearer.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@ranger.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] RANGER-5804: Support Ranger Admin for displaying audit metrics from OpenSearch [ranger]
Posted by "RakeshGuptaDev (via GitHub)" <gi...@apache.org>.
RakeshGuptaDev commented on code in PR #1251:
URL: https://github.com/apache/ranger/pull/1251#discussion_r4092026299
##########
security-admin/src/main/java/org/apache/ranger/audit/metrics/AuditMetricsHelper.java:
##########
@@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.audit.metrics;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.ranger.db.RangerDaoManager;
+import org.apache.ranger.entity.XXService;
+import org.apache.ranger.entity.XXServiceDef;
+import org.apache.ranger.plugin.model.RangerAuditMetrics;
+import org.apache.ranger.plugin.model.RangerAuditMetricsByDays;
+import org.apache.ranger.plugin.model.RangerAuditMetricsByHours;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.time.DateTimeException;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeParseException;
+import java.util.Date;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+@Component
+public class AuditMetricsHelper {
+ private static final Logger LOGGER = LoggerFactory.getLogger(AuditMetricsHelper.class);
+
+ public static final long MISSING_REPO_TYPE_SENTINEL = -1L;
+
+ private final Map<String, Long> repoTypeByServiceType = new ConcurrentHashMap<>();
+
+ @Autowired
+ RangerDaoManager daoManager;
+
+ public SearchFilter buildSearchFilter(String serviceType, String serviceName, String appId, String clusterName, String clientIP) {
+ SearchFilter filter = new SearchFilter();
+
+ filter.setParam(SearchFilter.SERVICE_TYPE, serviceType);
+ filter.setParam(SearchFilter.SERVICE_NAME, serviceName);
+ filter.setParam(SearchFilter.PLUGIN_APP_ID, appId);
+ filter.setParam(SearchFilter.CLUSTER_NAME, clusterName);
+ filter.setParam(SearchFilter.CLIENT_IP, clientIP);
+
+ return filter;
+ }
+
+ public FilterParams getFilterParams(SearchFilter filter) {
+ FilterParams params = new FilterParams();
+
+ if (filter != null) {
+ params.serviceType = filter.getParam(SearchFilter.SERVICE_TYPE);
+ params.serviceName = filter.getParam(SearchFilter.SERVICE_NAME);
+ params.appId = filter.getParam(SearchFilter.PLUGIN_APP_ID);
+ params.clusterName = filter.getParam(SearchFilter.CLUSTER_NAME);
+ params.clientIP = filter.getParam(SearchFilter.CLIENT_IP);
+ }
+
+ return params;
+ }
+
+ public RangerAuditMetrics buildAuditMetrics(String serviceType, String serviceName, String appId, String clusterName, String clientIP, long count) {
+ RangerAuditMetrics metric = new RangerAuditMetrics();
+
+ metric.setServiceName(serviceName);
+ metric.setServiceType(resolveServiceType(serviceType, serviceName));
+ metric.setAppId(appId);
+ metric.setClusterName(clusterName);
+ metric.setClientIP(clientIP);
+ metric.setNumberOfAudits(count);
+
+ Long serviceId = resolveServiceId(serviceName);
+
+ if (serviceId != null) {
+ metric.setId(serviceId);
+ }
+
+ return metric;
+ }
+
+ public RangerAuditMetricsByDays buildAuditMetricsByDays(FilterParams params, Long auditDate, long count) {
+ return new RangerAuditMetricsByDays(params.serviceType, params.serviceName, params.appId, params.clusterName, params.clientIP, auditDate, count);
+ }
+
+ public RangerAuditMetricsByHours buildAuditMetricsByHours(FilterParams params, int hour, long count) {
+ return new RangerAuditMetricsByHours(params.serviceType, params.serviceName, params.appId, params.clusterName, params.clientIP, hour, count);
+ }
+
+ public Long resolveServiceId(String serviceName) {
+ Long ret = null;
+
+ if (StringUtils.isNotBlank(serviceName) && daoManager != null && daoManager.getXXService() != null) {
+ XXService service = daoManager.getXXService().findByName(serviceName);
+
+ if (service != null) {
+ ret = service.getId();
+ }
+ }
+
+ return ret;
+ }
+
+ public String resolveServiceType(XXService service) {
+ String ret = null;
+
+ if (service != null && daoManager != null && daoManager.getXXServiceDef() != null) {
+ XXServiceDef serviceDef = daoManager.getXXServiceDef().getById(service.getType());
+
+ if (serviceDef != null) {
+ ret = serviceDef.getName();
+ }
+ }
+
+ return ret;
+ }
+
+ public String resolveServiceType(String serviceType, String serviceName) {
+ String ret = serviceType;
+
+ if (StringUtils.isBlank(ret)) {
+ if (StringUtils.isNotBlank(serviceName) && daoManager != null && daoManager.getXXService() != null) {
+ XXService service = daoManager.getXXService().findByName(serviceName);
+ ret = resolveServiceType(service);
+ } else {
+ ret = null;
+ }
+ }
+
+ return ret;
+ }
+
+ public long resolveRepoType(String serviceType) {
+ if (StringUtils.isBlank(serviceType)) {
+ return MISSING_REPO_TYPE_SENTINEL;
Review Comment:
Thanks for the suggestion. Updated resolveRepoType() to use long ret = MISSING_REPO_TYPE_SENTINEL and return ret, consistent with the other methods in AuditMetricsHelper.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@ranger.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] RANGER-5804: Support Ranger Admin for displaying audit metrics from OpenSearch [ranger]
Posted by "RakeshGuptaDev (via GitHub)" <gi...@apache.org>.
RakeshGuptaDev commented on code in PR #1251:
URL: https://github.com/apache/ranger/pull/1251#discussion_r4092047328
##########
security-admin/src/main/java/org/apache/ranger/rest/AuditMetricsREST.java:
##########
@@ -104,7 +116,11 @@ public RangerAuditMetrics getAuditMetrics(@PathParam("id") Long id, @QueryParam(
LOG.debug("==> AuditMetricsREST.getAuditMetrics(id={})", id);
RangerAuditMetrics ret;
try {
- ret = solrAccessAuditsService.getAuditMetrics(id, timezone);
+ if (RangerBizUtil.AUDIT_STORE_OPENSEARCH.equalsIgnoreCase(rangerBizUtil.getAuditDBType())) {
Review Comment:
Thanks for the suggestion.
I've introduced:
- AccessAuditsMetricsService interface
- AccessAuditsMetricsServiceFactory to resolve the implementation based on audit store type
- SolrAccessAuditsService and OpenSearchAccessAuditsService implementing the interface
- AuditMetricsREST now delegates through the factory
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@ranger.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] RANGER-5804: Support Ranger Admin for displaying audit metrics from OpenSearch [ranger]
Posted by "pradeepagrawal8184 (via GitHub)" <gi...@apache.org>.
pradeepagrawal8184 merged PR #1251:
URL: https://github.com/apache/ranger/pull/1251
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@ranger.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org