|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package org.apache.polaris.service.events.jsonEventListener.aws.cloudwatch; |
| 21 | + |
| 22 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 23 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 24 | +import io.smallrye.common.annotation.Identifier; |
| 25 | +import jakarta.annotation.PostConstruct; |
| 26 | +import jakarta.annotation.PreDestroy; |
| 27 | +import jakarta.enterprise.context.ApplicationScoped; |
| 28 | +import jakarta.inject.Inject; |
| 29 | +import jakarta.ws.rs.core.Context; |
| 30 | +import jakarta.ws.rs.core.SecurityContext; |
| 31 | +import java.time.Clock; |
| 32 | +import java.util.HashMap; |
| 33 | +import java.util.List; |
| 34 | +import java.util.concurrent.CompletableFuture; |
| 35 | +import java.util.function.Supplier; |
| 36 | +import org.apache.polaris.core.auth.PolarisPrincipal; |
| 37 | +import org.apache.polaris.core.context.CallContext; |
| 38 | +import org.apache.polaris.service.config.PolarisIcebergObjectMapperCustomizer; |
| 39 | +import org.apache.polaris.service.events.jsonEventListener.PropertyMapEventListener; |
| 40 | +import org.slf4j.Logger; |
| 41 | +import org.slf4j.LoggerFactory; |
| 42 | +import software.amazon.awssdk.regions.Region; |
| 43 | +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsAsyncClient; |
| 44 | +import software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogGroupRequest; |
| 45 | +import software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogStreamRequest; |
| 46 | +import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogGroupsRequest; |
| 47 | +import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest; |
| 48 | +import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent; |
| 49 | +import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest; |
| 50 | +import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsResponse; |
| 51 | + |
| 52 | +@ApplicationScoped |
| 53 | +@Identifier("aws-cloudwatch") |
| 54 | +public class AwsCloudWatchEventListener extends PropertyMapEventListener { |
| 55 | + private static final Logger LOGGER = LoggerFactory.getLogger(AwsCloudWatchEventListener.class); |
| 56 | + final ObjectMapper objectMapper = new ObjectMapper(); |
| 57 | + |
| 58 | + private CloudWatchLogsAsyncClient client; |
| 59 | + |
| 60 | + private final String logGroup; |
| 61 | + private final String logStream; |
| 62 | + private final Region region; |
| 63 | + private final boolean synchronousMode; |
| 64 | + private final Clock clock; |
| 65 | + |
| 66 | + @Inject CallContext callContext; |
| 67 | + |
| 68 | + @Context SecurityContext securityContext; |
| 69 | + |
| 70 | + @Inject |
| 71 | + public AwsCloudWatchEventListener( |
| 72 | + AwsCloudWatchConfiguration config, |
| 73 | + Clock clock, |
| 74 | + PolarisIcebergObjectMapperCustomizer customizer) { |
| 75 | + this.logStream = config.awsCloudWatchLogStream(); |
| 76 | + this.logGroup = config.awsCloudWatchLogGroup(); |
| 77 | + this.region = Region.of(config.awsCloudWatchRegion()); |
| 78 | + this.synchronousMode = config.synchronousMode(); |
| 79 | + this.clock = clock; |
| 80 | + customizer.customize(this.objectMapper); |
| 81 | + } |
| 82 | + |
| 83 | + @PostConstruct |
| 84 | + void start() { |
| 85 | + this.client = createCloudWatchAsyncClient(); |
| 86 | + ensureLogGroupAndStream(); |
| 87 | + } |
| 88 | + |
| 89 | + protected CloudWatchLogsAsyncClient createCloudWatchAsyncClient() { |
| 90 | + return CloudWatchLogsAsyncClient.builder().region(region).build(); |
| 91 | + } |
| 92 | + |
| 93 | + private void ensureLogGroupAndStream() { |
| 94 | + ensureResourceExists( |
| 95 | + () -> |
| 96 | + client |
| 97 | + .describeLogGroups( |
| 98 | + DescribeLogGroupsRequest.builder().logGroupNamePrefix(logGroup).build()) |
| 99 | + .join() |
| 100 | + .logGroups() |
| 101 | + .stream() |
| 102 | + .anyMatch(g -> g.logGroupName().equals(logGroup)), |
| 103 | + () -> |
| 104 | + client |
| 105 | + .createLogGroup(CreateLogGroupRequest.builder().logGroupName(logGroup).build()) |
| 106 | + .join(), |
| 107 | + "group", |
| 108 | + logGroup); |
| 109 | + ensureResourceExists( |
| 110 | + () -> |
| 111 | + client |
| 112 | + .describeLogStreams( |
| 113 | + DescribeLogStreamsRequest.builder() |
| 114 | + .logGroupName(logGroup) |
| 115 | + .logStreamNamePrefix(logStream) |
| 116 | + .build()) |
| 117 | + .join() |
| 118 | + .logStreams() |
| 119 | + .stream() |
| 120 | + .anyMatch(s -> s.logStreamName().equals(logStream)), |
| 121 | + () -> |
| 122 | + client |
| 123 | + .createLogStream( |
| 124 | + CreateLogStreamRequest.builder() |
| 125 | + .logGroupName(logGroup) |
| 126 | + .logStreamName(logStream) |
| 127 | + .build()) |
| 128 | + .join(), |
| 129 | + "stream", |
| 130 | + logStream); |
| 131 | + } |
| 132 | + |
| 133 | + private static void ensureResourceExists( |
| 134 | + Supplier<Boolean> existsCheck, |
| 135 | + Runnable createAction, |
| 136 | + String resourceType, |
| 137 | + String resourceName) { |
| 138 | + if (existsCheck.get()) { |
| 139 | + LOGGER.debug("Log {} [{}] already exists", resourceType, resourceName); |
| 140 | + } else { |
| 141 | + LOGGER.debug("Attempting to create log {}: {}", resourceType, resourceName); |
| 142 | + createAction.run(); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + @PreDestroy |
| 147 | + void shutdown() { |
| 148 | + if (client != null) { |
| 149 | + client.close(); |
| 150 | + client = null; |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + @Override |
| 155 | + protected void transformAndSendEvent(HashMap<String, Object> properties) { |
| 156 | + properties.put("realm_id", callContext.getRealmContext().getRealmIdentifier()); |
| 157 | + properties.put("principal", securityContext.getUserPrincipal().getName()); |
| 158 | + properties.put( |
| 159 | + "activated_roles", ((PolarisPrincipal) securityContext.getUserPrincipal()).getRoles()); |
| 160 | + // TODO: Add request ID when it is available |
| 161 | + String eventAsJson; |
| 162 | + try { |
| 163 | + eventAsJson = objectMapper.writeValueAsString(properties); |
| 164 | + } catch (JsonProcessingException e) { |
| 165 | + LOGGER.error("Error processing event into JSON string: ", e); |
| 166 | + LOGGER.debug("Failed to convert the following object into JSON string: {}", properties); |
| 167 | + return; |
| 168 | + } |
| 169 | + InputLogEvent inputLogEvent = |
| 170 | + InputLogEvent.builder().message(eventAsJson).timestamp(clock.millis()).build(); |
| 171 | + PutLogEventsRequest.Builder requestBuilder = |
| 172 | + PutLogEventsRequest.builder() |
| 173 | + .logGroupName(logGroup) |
| 174 | + .logStreamName(logStream) |
| 175 | + .logEvents(List.of(inputLogEvent)); |
| 176 | + CompletableFuture<PutLogEventsResponse> future = |
| 177 | + client |
| 178 | + .putLogEvents(requestBuilder.build()) |
| 179 | + .whenComplete( |
| 180 | + (resp, err) -> { |
| 181 | + if (err != null) { |
| 182 | + LOGGER.error( |
| 183 | + "Error writing log to CloudWatch. Event: {}, Error: ", inputLogEvent, err); |
| 184 | + } |
| 185 | + }); |
| 186 | + if (synchronousMode) { |
| 187 | + future.join(); |
| 188 | + } |
| 189 | + } |
| 190 | +} |
0 commit comments