adnanhemani commented on code in PR #1965:
URL: https://github.com/apache/polaris/pull/1965#discussion_r2274749716


##########
runtime/service/src/main/java/org/apache/polaris/service/events/jsonEventListener/aws/cloudwatch/AwsCloudWatchEventListener.java:
##########
@@ -0,0 +1,181 @@
+/*
+ * 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.polaris.service.events.jsonEventListener.aws.cloudwatch;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.common.annotation.Identifier;
+import jakarta.annotation.PostConstruct;
+import jakarta.annotation.PreDestroy;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.SecurityContext;
+import java.time.Clock;
+import java.util.HashMap;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import org.apache.polaris.core.context.CallContext;
+import org.apache.polaris.service.events.jsonEventListener.JsonEventListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.regions.Region;
+import 
software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsAsyncClient;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogGroupRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogGroupResponse;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogStreamRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogStreamResponse;
+import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsResponse;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.ResourceAlreadyExistsException;
+
+@ApplicationScoped
+@Identifier("aws-cloudwatch")
+public class AwsCloudWatchEventListener extends JsonEventListener {
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(AwsCloudWatchEventListener.class);
+  private final ObjectMapper objectMapper = new ObjectMapper();
+
+  private CloudWatchLogsAsyncClient client;
+
+  private final String logGroup;
+  private final String logStream;
+  private final Region region;
+  private final boolean synchronousMode;
+  private final Clock clock;
+
+  @Inject CallContext callContext;
+
+  @Context SecurityContext securityContext;
+
+  @Inject
+  public AwsCloudWatchEventListener(AwsCloudWatchConfiguration config, Clock 
clock) {
+    this.logStream =
+        config
+            .awsCloudwatchlogStream()
+            .orElseThrow(
+                () -> new IllegalArgumentException("AWS CloudWatch log stream 
must be configured"));
+    this.logGroup =
+        config
+            .awsCloudwatchlogGroup()
+            .orElseThrow(
+                () -> new IllegalArgumentException("AWS CloudWatch log group 
must be configured"));
+    this.region =
+        Region.of(
+            config
+                .awsCloudwatchRegion()
+                .orElseThrow(
+                    () ->
+                        new IllegalArgumentException("AWS CloudWatch region 
must be configured")));
+    this.synchronousMode = config.synchronousMode();
+    this.clock = clock;
+  }
+
+  @PostConstruct
+  void start() {
+    this.client = createCloudWatchAsyncClient();
+    ensureLogGroupAndStream();
+  }
+
+  protected CloudWatchLogsAsyncClient createCloudWatchAsyncClient() {
+    return CloudWatchLogsAsyncClient.builder().region(region).build();
+  }
+
+  private void ensureLogGroupAndStream() {
+    try {
+      CompletableFuture<CreateLogGroupResponse> future =
+          
client.createLogGroup(CreateLogGroupRequest.builder().logGroupName(logGroup).build());
+      future.join();
+    } catch (CompletionException e) {
+      if (e.getCause() instanceof ResourceAlreadyExistsException) {
+        LOGGER.debug("Log group {} already exists", logGroup);
+      } else {
+        throw e;
+      }
+    }
+
+    try {
+      CompletableFuture<CreateLogStreamResponse> future =
+          client.createLogStream(
+              CreateLogStreamRequest.builder()
+                  .logGroupName(logGroup)
+                  .logStreamName(logStream)
+                  .build());
+      future.join();
+    } catch (CompletionException e) {
+      if (e.getCause() instanceof ResourceAlreadyExistsException) {
+        LOGGER.debug("Log stream {} already exists", logStream);
+      } else {
+        throw e;
+      }
+    }
+  }
+
+  @PreDestroy
+  void shutdown() {
+    if (client != null) {
+      client.close();
+    }
+  }
+
+  @Override
+  protected void transformAndSendEvent(HashMap<String, Object> properties) {
+    properties.put("realm", 
callContext.getRealmContext().getRealmIdentifier());
+    properties.put("principal", securityContext.getUserPrincipal().getName());
+    // TODO: Add request ID when it is available
+    String eventAsJson;
+    try {
+      eventAsJson = objectMapper.writeValueAsString(properties);
+    } catch (JsonProcessingException e) {
+      LOGGER.error("Error processing event into JSON string: {}", 
e.getMessage());

Review Comment:
   Good call, added in next revision



##########
runtime/service/src/test/java/org/apache/polaris/service/events/jsonEventListener/aws/cloudwatch/AwsCloudWatchEventListenerTest.java:
##########
@@ -0,0 +1,432 @@
+/*
+ * 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.polaris.service.events.jsonEventListener.aws.cloudwatch;
+
+import static 
org.apache.polaris.containerspec.ContainerSpecHelper.containerSpecHelper;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import jakarta.ws.rs.core.SecurityContext;
+import java.security.Principal;
+import java.time.Clock;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.context.CallContext;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.service.events.AfterTableRefreshedEvent;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.localstack.LocalStackContainer;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import 
software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsAsyncClient;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogGroupRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogStreamRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogGroupsRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogGroupsResponse;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsResponse;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsResponse;
+
+class AwsCloudWatchEventListenerTest {
+  private static final Logger LOGGER =
+      LoggerFactory.getLogger(AwsCloudWatchEventListenerTest.class);
+
+  private static final LocalStackContainer localStack =
+      new LocalStackContainer(
+              containerSpecHelper("localstack", 
AwsCloudWatchEventListenerTest.class)
+                  .dockerImageName(null))
+          .withServices(LocalStackContainer.Service.CLOUDWATCHLOGS);
+
+  private static final String LOG_GROUP = "test-log-group";
+  private static final String LOG_STREAM = "test-log-stream";
+  private static final String REALM = "test-realm";
+  private static final String TEST_USER = "test-user";
+  private static final Clock clock = Clock.systemUTC();
+
+  @Mock private AwsCloudWatchConfiguration config;
+
+  private ExecutorService executorService;
+  private AutoCloseable mockitoContext;
+
+  enum TestMode {
+    LOCALSTACK,
+    MOCKED

Review Comment:
   It was asked from a previous 
[review](https://github.com/apache/polaris/pull/1965#discussion_r2210737076). I 
think the main thing it does is give a way to test the code in a mocked 
fashion, which will be similar to other future CSP product implementations, as 
they do not have a LocalStack equivalence.



##########
runtime/service/src/main/java/org/apache/polaris/service/quarkus/events/jsonEventListener/aws/cloudwatch/QuarkusAwsCloudWatchConfiguration.java:
##########
@@ -0,0 +1,100 @@
+/*
+ * 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.polaris.service.quarkus.events.jsonEventListener.aws.cloudwatch;
+
+import io.quarkus.runtime.annotations.StaticInitSafe;
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import io.smallrye.config.WithName;
+import jakarta.enterprise.context.ApplicationScoped;
+import java.util.Optional;
+import 
org.apache.polaris.service.events.jsonEventListener.aws.cloudwatch.AwsCloudWatchConfiguration;
+
+/**
+ * Quarkus-specific configuration interface for AWS CloudWatch event listener 
integration.
+ *
+ * <p>This interface extends the base {@link AwsCloudWatchConfiguration} and 
provides
+ * Quarkus-specific configuration mappings for AWS CloudWatch logging 
functionality.
+ */
+@StaticInitSafe
+@ConfigMapping(prefix = "polaris.event-listener.aws-cloudwatch")
+@ApplicationScoped
+public interface QuarkusAwsCloudWatchConfiguration extends 
AwsCloudWatchConfiguration {
+
+  /**
+   * Returns the AWS CloudWatch log group name for event logging.
+   *
+   * <p>The log group is a collection of log streams that share the same 
retention, monitoring, and
+   * access control settings. If not specified, defaults to 
"polaris-cloudwatch-default-group".
+   *
+   * <p>Configuration property: {@code 
polaris.event-listener.aws-cloudwatch.log-group}
+   *
+   * @return an Optional containing the log group name, or empty if not 
configured

Review Comment:
   This is a good call - this may be on me due to hangover from a previous 
commit. Adjusting for the next revision.



##########
runtime/service/src/test/java/org/apache/polaris/service/events/jsonEventListener/aws/cloudwatch/AwsCloudWatchEventListenerTest.java:
##########
@@ -0,0 +1,432 @@
+/*
+ * 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.polaris.service.events.jsonEventListener.aws.cloudwatch;
+
+import static 
org.apache.polaris.containerspec.ContainerSpecHelper.containerSpecHelper;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import jakarta.ws.rs.core.SecurityContext;
+import java.security.Principal;
+import java.time.Clock;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.context.CallContext;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.service.events.AfterTableRefreshedEvent;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.localstack.LocalStackContainer;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import 
software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsAsyncClient;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogGroupRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogStreamRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogGroupsRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogGroupsResponse;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsResponse;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest;
+import 
software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsResponse;
+
+class AwsCloudWatchEventListenerTest {
+  private static final Logger LOGGER =
+      LoggerFactory.getLogger(AwsCloudWatchEventListenerTest.class);
+
+  private static final LocalStackContainer localStack =
+      new LocalStackContainer(
+              containerSpecHelper("localstack", 
AwsCloudWatchEventListenerTest.class)
+                  .dockerImageName(null))
+          .withServices(LocalStackContainer.Service.CLOUDWATCHLOGS);
+
+  private static final String LOG_GROUP = "test-log-group";
+  private static final String LOG_STREAM = "test-log-stream";
+  private static final String REALM = "test-realm";
+  private static final String TEST_USER = "test-user";
+  private static final Clock clock = Clock.systemUTC();
+
+  @Mock private AwsCloudWatchConfiguration config;
+
+  private ExecutorService executorService;
+  private AutoCloseable mockitoContext;
+
+  enum TestMode {
+    LOCALSTACK,
+    MOCKED

Review Comment:
   Talked offline with @eric-maynard - he is fine with removing the 
"mocked"-mode tests. Will reflect in the next revision.



-- 
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: issues-unsubscr...@polaris.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to