mneethiraj commented on code in PR #986:
URL: https://github.com/apache/ranger/pull/986#discussion_r3467391226


##########
agents-audit/dest-os/src/main/java/org/apache/ranger/audit/destination/OpenSearchAuditDestination.java:
##########
@@ -0,0 +1,243 @@
+/*
+ * 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.destination;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.entity.ContentType;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.apache.http.nio.entity.NStringEntity;
+import org.apache.http.util.EntityUtils;
+import org.apache.ranger.audit.model.AuditEventBase;
+import org.apache.ranger.audit.model.AuthzAuditEvent;
+import org.apache.ranger.audit.provider.MiscUtil;
+import org.elasticsearch.client.Request;
+import org.elasticsearch.client.Response;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.charset.StandardCharsets;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TimeZone;
+import java.util.UUID;
+
+public class OpenSearchAuditDestination extends AuditDestination {
+    private static final Logger LOG = 
LoggerFactory.getLogger(OpenSearchAuditDestination.class);
+
+    public static final String CONFIG_PREFIX   = "ranger.audit.opensearch";
+    public static final String CONFIG_URLS     = "urls";
+    public static final String CONFIG_PORT     = "port";
+    public static final String CONFIG_USER     = "user";
+    public static final String CONFIG_PASSWORD = "password";
+    public static final String CONFIG_PROTOCOL = "protocol";
+    public static final String CONFIG_INDEX    = "index";
+    public static final String DEFAULT_INDEX   = "ranger_audits";
+
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+    private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT = 
ThreadLocal.withInitial(() -> {
+        SimpleDateFormat sdf = new 
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
+        return sdf;
+    });
+
+    private volatile RestClient client;
+    private String index;
+    private String user;
+    private String password;
+    private String protocol;
+    private String urls;
+    private int    port;
+
+    public OpenSearchAuditDestination() {
+        propPrefix = CONFIG_PREFIX;
+    }
+
+    @Override
+    public void init(Properties props, String propPrefix) {
+        super.init(props, propPrefix);
+
+        this.urls     = MiscUtil.getStringProperty(props, propPrefix + "." + 
CONFIG_URLS, "localhost");
+        this.port     = MiscUtil.getIntProperty(props, propPrefix + "." + 
CONFIG_PORT, 9200);
+        this.protocol = MiscUtil.getStringProperty(props, propPrefix + "." + 
CONFIG_PROTOCOL, "http");
+        this.user     = MiscUtil.getStringProperty(props, propPrefix + "." + 
CONFIG_USER, "");
+        this.password = MiscUtil.getStringProperty(props, propPrefix + "." + 
CONFIG_PASSWORD, "");
+        this.index    = MiscUtil.getStringProperty(props, propPrefix + "." + 
CONFIG_INDEX, DEFAULT_INDEX);
+
+        LOG.info("OpenSearchAuditDestination.init(): urls={}, port={}, 
index={}", urls, port, index);
+
+        getClient();
+    }
+
+    @Override
+    public void stop() {
+        logStatus();
+
+        if (client != null) {
+            try {
+                client.close();
+            } catch (Exception e) {
+                LOG.error("Error closing OpenSearch client", e);
+            }
+        }
+    }
+
+    @Override
+    public void flush() {
+    }
+
+    @Override
+    public boolean log(Collection<AuditEventBase> events) {
+        if (events == null || events.isEmpty()) {
+            return true;
+        }
+
+        RestClient currentClient = getClient();
+
+        if (currentClient == null) {
+            LOG.error("OpenSearch client is null. Cannot write audit events.");
+            return false;
+        }
+
+        try {
+            StringBuilder bulk = new StringBuilder();
+
+            for (AuditEventBase event : events) {
+                AuthzAuditEvent auditEvent = (AuthzAuditEvent) event;
+                Map<String, Object> doc = toDoc(auditEvent);
+                String id = (String) doc.get("id");
+
+                if (StringUtils.isBlank(id)) {
+                    id = UUID.randomUUID().toString();
+                    doc.put("id", id);
+                }
+
+                Map<String, Object> indexProps = new HashMap<>();
+                indexProps.put("_index", index);
+                indexProps.put("_id", id);
+
+                bulk.append(MAPPER.writeValueAsString(Map.of("index", 
indexProps))).append('\n');
+                bulk.append(MAPPER.writeValueAsString(doc)).append('\n');
+            }
+
+            Request request = new Request("POST", "/_bulk");
+            request.setEntity(new NStringEntity(bulk.toString(), 
ContentType.create("application/x-ndjson", StandardCharsets.UTF_8)));
+
+            Response response = currentClient.performRequest(request);
+
+            if (response.getStatusLine().getStatusCode() >= 400) {
+                LOG.error("OpenSearch bulk request failed: HTTP {}", 
response.getStatusLine().getStatusCode());
+                return false;
+            }
+
+            String responseBody = EntityUtils.toString(response.getEntity());
+            @SuppressWarnings("unchecked")
+            Map<String, Object> responseMap = MAPPER.readValue(responseBody, 
Map.class);
+
+            if (Boolean.TRUE.equals(responseMap.get("errors"))) {
+                LOG.error("OpenSearch bulk response contains item-level 
errors");
+                return false;
+            }
+
+            addSuccessCount(events.size());
+            return true;
+        } catch (Exception e) {
+            addFailedCount(events.size());

Review Comment:
   Shouldn't `addFailedCount()` be called for earlier occurrences of `return 
false;`? Consider having a single `return` statement in the method to make it 
simpler to handle this.



##########
audit-server/audit-dispatcher/dispatcher-opensearch/src/main/java/org/apache/ranger/audit/dispatcher/kafka/AuditOpenSearchDispatcher.java:
##########
@@ -0,0 +1,252 @@
+/*
+ * 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.dispatcher.kafka;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpHost;
+import org.apache.http.HttpStatus;
+import org.apache.http.auth.AuthSchemeProvider;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.client.config.AuthSchemes;
+import org.apache.http.config.Lookup;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.entity.ContentType;
+import org.apache.http.impl.auth.SPNegoSchemeFactory;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.apache.http.nio.entity.NStringEntity;
+import org.apache.http.util.EntityUtils;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.ranger.audit.dispatcher.AuditEventOpenSearchDocMapper;
+import org.apache.ranger.audit.model.AuthzAuditEvent;
+import org.apache.ranger.audit.provider.MiscUtil;
+import org.apache.ranger.audit.server.AuditServerConstants;
+import org.apache.ranger.audit.utils.AuditServerLogFormatter;
+import org.apache.ranger.authorization.credutils.CredentialsProviderUtil;
+import 
org.apache.ranger.authorization.credutils.kerberos.KerberosCredentialsProvider;
+import org.elasticsearch.client.Request;
+import org.elasticsearch.client.Response;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+public class AuditOpenSearchDispatcher extends AuditDispatcherBase {
+    private static final Logger LOG = 
LoggerFactory.getLogger(AuditOpenSearchDispatcher.class);
+    private static final String DEFAULT_GROUP = 
"ranger_audit_opensearch_dispatcher_group";
+    private static final String DEFAULT_INDEX = "ranger_audits";
+    private static final long   RETRY_SLEEP_MS = 5000L;
+    private static final int    DEFAULT_PORT   = 9200;
+    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+    private static final TypeReference<Map<String, Object>> MAP_TYPE = new 
TypeReference<Map<String, Object>>() { };
+
+    private RestClient openSearchClient;

Review Comment:
   How about using `OpenSearchAuditDestination` instead of `RestClient` 
directly here? Similar to how `AuditSolrDispatcher` uses 
`SolrAuditDestination`. With this approach, `AuditEventOpenSearchDocMapper` 
will not be necessary as well.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to