mneethiraj commented on code in PR #986: URL: https://github.com/apache/ranger/pull/986#discussion_r3321634742
########## audit-server/audit-dispatcher/dispatcher-opensearch/src/main/java/org/apache/ranger/audit/dispatcher/kafka/AuditOpenSearchDispatcher.java: ########## @@ -0,0 +1,416 @@ +/* + * 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.impl.auth.SPNegoSchemeFactory; +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.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.AuditEventDocMapper; +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.ArrayList; +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; + +public class AuditOpenSearchDispatcher + extends AuditDispatcherBase { + /** Class logger. */ + private static final Logger LOG = + LoggerFactory.getLogger( + AuditOpenSearchDispatcher.class); + + /** Kafka consumer group for this dispatcher. */ + private static final String DEFAULT_GROUP = + "ranger_audit_opensearch_dispatcher_group"; + /** Property prefix for OpenSearch destination config. */ + private static final String ES_DEST_PREFIX = + "xasecure.audit.destination.elasticsearch"; + /** Default OpenSearch index name. */ + private static final String DEFAULT_INDEX = + "ranger_audits"; + /** Sleep duration between retries on batch failure. */ + private static final long RETRY_SLEEP_MS = 5000L; + /** Default OpenSearch HTTP port. */ + private static final int DEFAULT_PORT = 9200; + /** Shared JSON serializer. */ + private static final ObjectMapper OBJECT_MAPPER = + new ObjectMapper(); + /** Type reference for bulk response parsing. */ + private static final TypeReference<Map<String, Object>> + MAP_TYPE = new TypeReference<Map<String, Object>>() { + }; + + /** OpenSearch REST client. */ + private RestClient openSearchClient; + /** Target index for audit documents. */ + private String openSearchIndex; + + /** + * Creates and initializes the OpenSearch dispatcher. + * + * @param props configuration properties + * @param propPrefix property key prefix + * @throws Exception if initialization fails + */ + public AuditOpenSearchDispatcher( + final Properties props, + final String propPrefix) throws Exception { + super(props, propPrefix, DEFAULT_GROUP); + + init(props, propPrefix); + } + + @Override + protected final String getDispatcherName() { + return "OPENSEARCH"; + } + + @Override + protected final DispatcherWorker createDispatcherWorker( + final String workerId, + final List<Integer> assignedPartitions) { + return new OpenSearchDispatcherWorker( + workerId, assignedPartitions); + } + + @Override + protected final void shutdownDestination() { + if (openSearchClient != null) { + try { + openSearchClient.close(); + } catch (Exception e) { + LOG.error( + "Error shutting down OpenSearch REST client", + e); + } + } + } + + private void init( + final Properties props, + final String propPrefix) throws Exception { + LOG.info("==> AuditOpenSearchDispatcher.init()"); + + String pfx = propPrefix + "."; + + this.openSearchIndex = MiscUtil.getStringProperty( + props, ES_DEST_PREFIX + ".index", DEFAULT_INDEX); Review Comment: Why is the hardcoded prefix used here, instead of the one received via method parameter `propPrefix`? Review other references in lines 257 to 265 as well and replace them. Also, remove the constant `ES_DEST_PREFIX` in line 79. ########## audit-server/audit-dispatcher/dispatcher-opensearch/src/main/java/org/apache/ranger/audit/dispatcher/kafka/AuditOpenSearchDispatcher.java: ########## @@ -0,0 +1,416 @@ +/* + * 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.impl.auth.SPNegoSchemeFactory; +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.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.AuditEventDocMapper; +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.ArrayList; +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; + +public class AuditOpenSearchDispatcher + extends AuditDispatcherBase { + /** Class logger. */ + private static final Logger LOG = + LoggerFactory.getLogger( + AuditOpenSearchDispatcher.class); + + /** Kafka consumer group for this dispatcher. */ + private static final String DEFAULT_GROUP = + "ranger_audit_opensearch_dispatcher_group"; + /** Property prefix for OpenSearch destination config. */ + private static final String ES_DEST_PREFIX = + "xasecure.audit.destination.elasticsearch"; + /** Default OpenSearch index name. */ + private static final String DEFAULT_INDEX = + "ranger_audits"; + /** Sleep duration between retries on batch failure. */ + private static final long RETRY_SLEEP_MS = 5000L; + /** Default OpenSearch HTTP port. */ + private static final int DEFAULT_PORT = 9200; + /** Shared JSON serializer. */ + private static final ObjectMapper OBJECT_MAPPER = + new ObjectMapper(); + /** Type reference for bulk response parsing. */ + private static final TypeReference<Map<String, Object>> + MAP_TYPE = new TypeReference<Map<String, Object>>() { + }; + + /** OpenSearch REST client. */ + private RestClient openSearchClient; + /** Target index for audit documents. */ + private String openSearchIndex; + + /** + * Creates and initializes the OpenSearch dispatcher. + * + * @param props configuration properties + * @param propPrefix property key prefix + * @throws Exception if initialization fails + */ + public AuditOpenSearchDispatcher( + final Properties props, + final String propPrefix) throws Exception { + super(props, propPrefix, DEFAULT_GROUP); + + init(props, propPrefix); + } + + @Override + protected final String getDispatcherName() { + return "OPENSEARCH"; + } + + @Override + protected final DispatcherWorker createDispatcherWorker( + final String workerId, + final List<Integer> assignedPartitions) { + return new OpenSearchDispatcherWorker( + workerId, assignedPartitions); + } + + @Override + protected final void shutdownDestination() { + if (openSearchClient != null) { + try { + openSearchClient.close(); + } catch (Exception e) { + LOG.error( + "Error shutting down OpenSearch REST client", + e); + } + } + } + + private void init( + final Properties props, + final String propPrefix) throws Exception { + LOG.info("==> AuditOpenSearchDispatcher.init()"); + + String pfx = propPrefix + "."; + + this.openSearchIndex = MiscUtil.getStringProperty( + props, ES_DEST_PREFIX + ".index", DEFAULT_INDEX); + this.openSearchClient = createOpenSearchClient(props); + + this.dispatcherThreadCount = MiscUtil.getIntProperty( + props, + pfx + AuditServerConstants.PROP_DISPATCHER_THREAD_COUNT, + 1); + this.offsetCommitStrategy = MiscUtil.getStringProperty( + props, + pfx + AuditServerConstants + .PROP_DISPATCHER_OFFSET_COMMIT_STRATEGY, + AuditServerConstants.DEFAULT_OFFSET_COMMIT_STRATEGY); + this.offsetCommitInterval = MiscUtil.getLongProperty( + props, + pfx + AuditServerConstants + .PROP_DISPATCHER_OFFSET_COMMIT_INTERVAL, + AuditServerConstants + .DEFAULT_OFFSET_COMMIT_INTERVAL_MS); + + AuditServerLogFormatter + .builder("AuditOpenSearchDispatcher Configuration") + .add("Index", openSearchIndex) + .add("Thread Count", dispatcherThreadCount) + .add("Commit Strategy", offsetCommitStrategy) + .add("Commit Interval (ms)", + offsetCommitInterval + " (manual mode only)") + .logInfo(LOG); + + LOG.info("<== AuditOpenSearchDispatcher.init()"); + } + + /** + * Sends a batch of audit JSON strings to OpenSearch. + * + * @param audits collection of JSON audit event strings + * @throws Exception if the bulk request fails + */ + public final void processMessageBatch( + final Collection<String> audits) throws Exception { + if (audits == null || audits.isEmpty()) { + throw new Exception( + "Failure in sending audits into OpenSearch"); + } + + StringBuilder bulkBody = new StringBuilder(); + + for (String audit : audits) { + AuthzAuditEvent auditEvent = + MiscUtil.fromJson(audit, AuthzAuditEvent.class); + String id = auditEvent.getEventId(); + Map<String, Object> doc = + AuditEventDocMapper.toDoc(auditEvent); + + if (id == null || id.trim().isEmpty()) { + id = UUID.randomUUID().toString(); + doc.put("id", id); + } + + Map<String, Object> indexProperties = + new HashMap<>(); + indexProperties.put("_index", openSearchIndex); + indexProperties.put("_id", id); + + Map<String, Object> indexMeta = + Collections.singletonMap("index", + indexProperties); + bulkBody.append( + OBJECT_MAPPER.writeValueAsString(indexMeta)) + .append('\n') + .append(OBJECT_MAPPER.writeValueAsString(doc)) + .append('\n'); + } + + Request request = new Request("POST", "/_bulk"); + request.setEntity(new NStringEntity( + bulkBody.toString(), + ContentType.create( + "application/x-ndjson", + StandardCharsets.UTF_8))); + + Response response = + openSearchClient.performRequest(request); + int status = + response.getStatusLine().getStatusCode(); + + if (status >= HttpStatus.SC_BAD_REQUEST) { + throw new Exception( + "OpenSearch bulk request failed with HTTP " + + status); + } + + String responseBody = response.getEntity() != null + ? EntityUtils.toString(response.getEntity()) + : "{}"; + Map<String, Object> responseMap = + OBJECT_MAPPER.readValue(responseBody, MAP_TYPE); + Object hasErrors = responseMap.get("errors"); + + if (Boolean.TRUE.equals(hasErrors)) { + throw new Exception( + "OpenSearch bulk request returned item errors: " + + responseBody); + } + } + + private RestClient createOpenSearchClient( + final Properties props) { + String protocol = MiscUtil.getStringProperty( + props, ES_DEST_PREFIX + ".protocol", "http"); + String urls = MiscUtil.getStringProperty( + props, ES_DEST_PREFIX + ".urls", "localhost"); + int port = MiscUtil.getIntProperty( + props, ES_DEST_PREFIX + ".port", DEFAULT_PORT); + String user = MiscUtil.getStringProperty( + props, ES_DEST_PREFIX + ".user", ""); + String password = MiscUtil.getStringProperty( + props, ES_DEST_PREFIX + ".password", ""); + + HttpHost[] hosts = + MiscUtil.toArray(urls, ",").stream() + .map(h -> new HttpHost(h, port, protocol)) + .toArray(HttpHost[]::new); + + LOG.info("Connecting to OpenSearch: {}://{}:{}/{}", + protocol, urls, port, openSearchIndex); + + RestClientBuilder builder = + RestClient.builder(hosts); + + if (isCredentialConfigured(user) + && isCredentialConfigured(password)) { + if (password.contains("keytab") + && new File(password).exists()) { + KerberosCredentialsProvider creds = + CredentialsProviderUtil + .getKerberosCredentials(user, password); + Lookup<AuthSchemeProvider> authRegistry = + RegistryBuilder.<AuthSchemeProvider>create() + .register(AuthSchemes.SPNEGO, + new SPNegoSchemeFactory()) + .build(); + builder.setHttpClientConfigCallback( + httpClientBuilder -> httpClientBuilder + .setDefaultCredentialsProvider(creds) + .setDefaultAuthSchemeRegistry(authRegistry)); + LOG.info("OpenSearch client configured with" + + " Kerberos credentials for user: {}", user); + } else { + CredentialsProvider creds = + new BasicCredentialsProvider(); + creds.setCredentials(AuthScope.ANY, + new UsernamePasswordCredentials( + user, password)); + builder.setHttpClientConfigCallback( + httpClientBuilder -> httpClientBuilder + .setDefaultCredentialsProvider(creds)); + LOG.info("OpenSearch client configured with" + + " basic auth for user: {}", user); + } + } + + return builder.build(); + } + + private boolean isCredentialConfigured(final String value) { + return StringUtils.isNotBlank(value) + && !"NONE".equalsIgnoreCase(value.trim()); + } + + private class OpenSearchDispatcherWorker + extends DispatcherWorker { + OpenSearchDispatcherWorker( + final String workerId, + final List<Integer> assignedPartitions) { + super(workerId, assignedPartitions); + } + + @Override + protected void processRecordBatch( + final ConsumerRecords<String, String> + records) { + List<String> auditBatch = new ArrayList<>(); + List<ConsumerRecord<String, String>> + recordList = new ArrayList<>(); + Review Comment: Consider using `ConsumerRecords.partitions()` to iterate and commit. `recordList` created here is not necessary with this approach. ``` for (TopicPartition tp : records.partitions()) { List<ConsumerRecord<String, String>> tpRecords = records.records(tp); if (tpRecords.isEmpty()) { continue; } try { List<String> auditBatch = tpRecords.streams().map(ConsumerRecord<String, String>::value).collect(Collectors.toList()); processMessageBatch(auditBatch); ConsumerRecord<String, String> last = tpRecords.get(tpRecords.size() - 1); pendingOffsets.put(tp, new OffsetAndMetadata(last.offset() + 1)); messagesProcessedSinceLastCommit.addAndGet(tpRecords.size()); } catch (Exception ex) { ConsumerRecord<String, String> first = tpRecords.get(0); pendingOffsets.put(tp, new OffsetAndMetadata(first.offset())); try { workerDispatcher.seek(tp, first.offset()); } catch (Exception e) { ... } } } ``` ########## audit-server/audit-dispatcher/dispatcher-common/src/main/java/org/apache/ranger/audit/dispatcher/AuditEventDocMapper.java: ########## @@ -0,0 +1,98 @@ +/* + * 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; + +import org.apache.ranger.audit.model.AuthzAuditEvent; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; + +/** + * Maps {@link AuthzAuditEvent} to an OpenSearch document. + */ +public final class AuditEventDocMapper { Review Comment: `AuditEventDocMapper` class is referenced only in `dispatcher-opensearch` project. I suggest moving this class from `dispatcher-common` to `dispatcher-opensearch` module. ########## audit-server/audit-dispatcher/dispatcher-opensearch/src/main/java/org/apache/ranger/audit/dispatcher/OpenSearchDispatcherManager.java: ########## @@ -0,0 +1,317 @@ +/* + * 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; + +import org.apache.ranger.audit.dispatcher.kafka.AuditDispatcher; +import org.apache.ranger.audit.dispatcher.kafka.AuditDispatcherTracker; +import org.apache.ranger.audit.provider.MiscUtil; +import org.apache.ranger.audit.server.AuditServerConstants; +import org.apache.ranger.audit.utils.AuditServerLogFormatter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Properties; + +/** + * Manages the lifecycle of the OpenSearch dispatcher. + */ +public final class OpenSearchDispatcherManager { + /** Class logger. */ + private static final Logger LOG = + LoggerFactory.getLogger( + OpenSearchDispatcherManager.class); + /** System property for dispatcher type selection. */ + private static final String CONFIG_DISPATCHER_TYPE = + AuditServerConstants.PROP_DISPATCHER_TYPE; + /** Dispatcher type identifier. */ + private static final String TYPE_OPENSEARCH = + "opensearch"; + /** Property controlling OpenSearch destination. */ + private static final String ES_DEST_PROP = + "xasecure.audit.destination.elasticsearch"; + /** Maximum initialization retry attempts. */ + private static final int MAX_INIT_ATTEMPTS = 5; + /** Base delay between initialization retries. */ + private static final long INIT_RETRY_MS = 5000L; + /** Maximum wait for dispatcher thread shutdown. */ + private static final long SHUTDOWN_WAIT_MS = 10000L; + + /** Tracks active dispatchers for health reporting. */ + private final AuditDispatcherTracker tracker = + AuditDispatcherTracker.getInstance(); + /** The active OpenSearch dispatcher instance. */ + private AuditDispatcher dispatcher; + /** Thread running the dispatcher's consume loop. */ + private Thread dispatcherThread; + + /** + * Initializes the OpenSearch dispatcher from properties. + * + * @param props configuration properties + */ + public void init(final Properties props) { + LOG.info("==> OpenSearchDispatcherManager.init()"); + + String dispatcherType = + System.getProperty(CONFIG_DISPATCHER_TYPE); + if (dispatcherType != null + && !dispatcherType.equalsIgnoreCase( + TYPE_OPENSEARCH)) { + LOG.info("Skipping OpenSearchDispatcherManager" + + " initialization since dispatcher" + + " type is {}", dispatcherType); + return; + } + + try { + if (props == null) { + LOG.error("Configuration properties are null"); + throw new RuntimeException( + "Failed to load configuration"); + } + + boolean isEnabled = MiscUtil.getBooleanProperty( + props, ES_DEST_PROP, false); + if (!isEnabled) { + String clsName = MiscUtil.getStringProperty( + props, + AuditServerConstants.PROP_DISPATCHER_CLASS); + if (clsName != null && clsName.contains( + "AuditOpenSearchDispatcher")) { + isEnabled = true; + } + } + + if (!isEnabled) { + LOG.warn("OpenSearch destination is disabled" + + " ({}=false). No dispatchers" + + " will be created.", ES_DEST_PROP); + return; + } + + initializeDispatcher(props, + AuditServerConstants.PROP_DISPATCHER_PREFIX); + + if (dispatcher == null) { + throw new RuntimeException( + "No OpenSearch dispatcher was created." + + " Verify that " + ES_DEST_PROP + "=true" + + " and classes are configured" + + " correctly."); + } else { + LOG.info("Created OpenSearch dispatcher"); + + Runtime.getRuntime().addShutdownHook( + new Thread(() -> { + LOG.info("JVM shutdown detected," + + " stopping" + + " OpenSearchDispatcherManager"); + shutdown(); + }, "OpenSearchDispatcher-ShutdownHook")); + + startDispatcher(); + } + } catch (Exception e) { + LOG.error("Failed to initialize" + + " OpenSearchDispatcherManager", e); + throw new RuntimeException( + "Failed to initialize" + + " OpenSearchDispatcherManager", e); + } + + LOG.info( + "<== OpenSearchDispatcherManager.init()"); + } + + private void initializeDispatcher( + final Properties props, + final String propPrefix) { + LOG.info("==> OpenSearchDispatcherManager" + + ".initializeDispatcher()"); + + String clsStr = MiscUtil.getStringProperty( + props, + AuditServerConstants.PROP_DISPATCHER_CLASS, + "org.apache.ranger.audit.dispatcher" Review Comment: I suggest replacing `"org.apache.ranger.audit.dispatcher.kafka.AuditOpenSearchDispatcher"` with `AuditOpenSearchDispatcher.class.getName()` ########## audit-server/audit-dispatcher/dispatcher-common/src/main/java/org/apache/ranger/audit/dispatcher/AuditEventDocMapper.java: ########## @@ -0,0 +1,98 @@ +/* + * 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; + +import org.apache.ranger.audit.model.AuthzAuditEvent; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; + +/** + * Maps {@link AuthzAuditEvent} to an OpenSearch document. + */ +public final class AuditEventDocMapper { + /** Thread-safe ISO-8601 UTC date formatter. */ + private static final ThreadLocal<DateFormat> DATE_FORMAT = + ThreadLocal.withInitial(() -> { + SimpleDateFormat format = new SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + format.setTimeZone(TimeZone.getTimeZone("UTC")); + return format; + }); + + private AuditEventDocMapper() { + } + + /** + * Converts an audit event to a document map. + * + * @param auditEvent the audit event to convert + * @return map of field names to values + */ + public static Map<String, Object> toDoc( Review Comment: @paras200 - please avoid breaking statements into multiple lines. Such splits make it harder to read the code. Days of 80-character max width are long gone! Let's make it a little easier for folks to read the code in widescreens that are easily capable of 200+ characters :-). Please review and update entire contents of this PR. ``` LOG.info("Skipping OpenSearchDispatcherManager" + " initialization since dispatcher" + " type is {}", dispatcherType); ``` vs ``` LOG.info("Skipping OpenSearchDispatcherManager initialization since dispatcher type is {}", dispatcherType); ``` -- 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]
