diff --git a/src/main/java/io/floci/aws/core/common/Gzip.java b/src/main/java/io/floci/aws/core/common/Gzip.java new file mode 100644 index 0000000000..70b0faa7f7 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/Gzip.java @@ -0,0 +1,35 @@ +package io.floci.aws.core.common; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.zip.GZIPOutputStream; + +/** + * Gzips content held in memory, as a service does for a log file or a payload it delivers whole. + * A writer that compresses as it goes, into a file or a stream it hands on, keeps its own + * {@link GZIPOutputStream}. + */ +public final class Gzip { + + private Gzip() { + } + + /** + * {@code data} as one gzip member. Writing to memory cannot fail, so an {@link IOException} + * from the compressor is rethrown unchecked rather than handed to every caller. + * + *
The buffer starts small and grows with the compressed output rather than being sized from + * the input: a log compresses to a small part of its size, and a buffer reserved up front would + * hold memory the result never fills beside the input the caller already holds. + */ + public static byte[] compress(byte[] data) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(out)) { + gzip.write(data); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return out.toByteArray(); + } +} diff --git a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailLogWriter.java b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailLogWriter.java index b1de6e673e..40e6106dff 100644 --- a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailLogWriter.java +++ b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailLogWriter.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Gzip; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.ServicePrincipals; @@ -18,7 +19,6 @@ import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; import org.jboss.logging.Logger; -import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.time.LocalDateTime; @@ -31,7 +31,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; -import java.util.zip.GZIPOutputStream; /** * Periodically drains queued CloudTrail records from {@link CloudTrailService} @@ -250,12 +249,7 @@ public class CloudTrailLogWriter { arr.add(r); } try { - byte[] json = mapper.writeValueAsBytes(envelope); - ByteArrayOutputStream baos = new ByteArrayOutputStream(Math.max(64, json.length / 4)); - try (GZIPOutputStream gz = new GZIPOutputStream(baos)) { - gz.write(json); - } - return baos.toByteArray(); + return Gzip.compress(mapper.writeValueAsBytes(envelope)); } catch (Exception e) { throw new RuntimeException("Failed to serialize CloudTrail records", e); } diff --git a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsSubscriptionDeliveryService.java b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsSubscriptionDeliveryService.java index 952bfe1beb..2c4ac91be1 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsSubscriptionDeliveryService.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsSubscriptionDeliveryService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Gzip; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; @@ -24,14 +25,12 @@ import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; import org.jboss.logging.Logger; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.UUID; -import java.util.zip.GZIPOutputStream; /** * Delivers matching log events to CloudWatch Logs subscription filter destinations @@ -257,7 +256,7 @@ public class CloudWatchLogsSubscriptionDeliveryService { List.of(filter.getFilterName()), slice); byte[] jsonBytes = objectMapper.writeValueAsBytes(payload); - gzippedBytes = gzip(jsonBytes); + gzippedBytes = Gzip.compress(jsonBytes); } catch (Exception e) { LOG.warnv(e, "Cannot serialize subscription payload: filter={0}", filter.getFilterName()); return; @@ -318,12 +317,4 @@ public class CloudWatchLogsSubscriptionDeliveryService { firehoseService.putRecord(targetAccount, targetRegion, streamName, record); LOG.debugv("Subscription filter delivered to Firehose delivery stream: {0}", streamName); } - - static byte[] gzip(byte[] input) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(64, input.length / 2)); - try (GZIPOutputStream gzip = new GZIPOutputStream(out)) { - gzip.write(input); - } - return out.toByteArray(); - } } diff --git a/src/main/java/io/floci/aws/services/ec2/FlowLogService.java b/src/main/java/io/floci/aws/services/ec2/FlowLogService.java index 4cd2e8f117..e4e8f63422 100644 --- a/src/main/java/io/floci/aws/services/ec2/FlowLogService.java +++ b/src/main/java/io/floci/aws/services/ec2/FlowLogService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import io.floci.aws.core.common.AvailabilityZoneIds; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Gzip; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.ec2.model.FlowLog; @@ -20,7 +21,6 @@ import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; import org.jboss.logging.Logger; -import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.ZoneOffset; @@ -37,7 +37,6 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.util.zip.GZIPOutputStream; import static io.floci.aws.services.ec2.Ec2Ids.randomHex; @@ -328,7 +327,7 @@ public class FlowLogService { } } - byte[] gz = gzip(sb.toString()); + byte[] gz = Gzip.compress(sb.toString().getBytes(StandardCharsets.UTF_8)); String key = s3Key(fl, now); try { s3Service.putObject(fl.getBucketName(), key, gz, "application/octet-stream", @@ -570,18 +569,6 @@ public class FlowLogService { fl.getAccountId(), fl.getRegion(), datePath, file); } - private static byte[] gzip(String content) { - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (GZIPOutputStream gz = new GZIPOutputStream(bos)) { - gz.write(content.getBytes(StandardCharsets.UTF_8)); - } - return bos.toByteArray(); - } catch (Exception e) { - throw new RuntimeException("gzip failed", e); - } - } - /** * The LogDestinationType a flow log gets: the requested one, else cloud-watch-logs when a log * group is named directly or by a CloudWatch Logs ARN, else s3. CloudFormation compares an diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java b/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java index b049174971..d7889c1656 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java @@ -3,6 +3,7 @@ package io.floci.aws.services.redshift; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegions; +import io.floci.aws.core.common.Gzip; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.ServiceCallAuthorizer; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService; @@ -16,7 +17,6 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Clock; @@ -31,7 +31,6 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; -import java.util.zip.GZIPOutputStream; @ApplicationScoped public class RedshiftAuditLogPublisher { @@ -361,7 +360,7 @@ public class RedshiftAuditLogPublisher { } String line = formatS3Line(logType, record); - byte[] newMember = compressGzipMember(line); + byte[] newMember = Gzip.compress((line + "\n").getBytes(StandardCharsets.UTF_8)); int stripeIndex = Math.floorMod((bucket + "/" + key).hashCode(), STRIPE_COUNT); Object lock = deliveryStripes[stripeIndex]; synchronized (lock) { @@ -397,15 +396,6 @@ public class RedshiftAuditLogPublisher { } } - private static byte[] compressGzipMember(String newLine) throws IOException { - ByteArrayOutputStream lineGz = new ByteArrayOutputStream(); - try (GZIPOutputStream gos = new GZIPOutputStream(lineGz)) { - gos.write(newLine.getBytes(StandardCharsets.UTF_8)); - gos.write('\n'); - } - return lineGz.toByteArray(); - } - private byte[] appendGzipMember(String bucket, String key, byte[] newMember) throws IOException { byte[] existingBytes = null; try { diff --git a/src/test/java/io/floci/aws/core/common/GzipTest.java b/src/test/java/io/floci/aws/core/common/GzipTest.java new file mode 100644 index 0000000000..334cab06eb --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/GzipTest.java @@ -0,0 +1,47 @@ +package io.floci.aws.core.common; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.zip.GZIPInputStream; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GzipTest { + + @Test + void compressedContentGunzipsBackToTheSameBytes() throws IOException { + byte[] content = "{\"Records\":[{\"eventName\":\"PutObject\"}]}\n".repeat(500).getBytes(StandardCharsets.UTF_8); + + assertArrayEquals(content, gunzip(Gzip.compress(content))); + } + + @Test + void emptyContentIsStillAGzipMember() throws IOException { + byte[] compressed = Gzip.compress(new byte[0]); + + assertEquals((byte) 0x1f, compressed[0]); + assertEquals((byte) 0x8b, compressed[1]); + assertArrayEquals(new byte[0], gunzip(compressed)); + } + + @Test + void membersCompressedApartReadBackAsOneStreamWhenJoined() throws IOException { + // A log file grown one member at a time, as Redshift's audit log is, reads as the lines in order. + ByteArrayOutputStream joined = new ByteArrayOutputStream(); + joined.write(Gzip.compress("first\n".getBytes(StandardCharsets.UTF_8))); + joined.write(Gzip.compress("second\n".getBytes(StandardCharsets.UTF_8))); + + assertEquals("first\nsecond\n", new String(gunzip(joined.toByteArray()), StandardCharsets.UTF_8)); + } + + private static byte[] gunzip(byte[] compressed) throws IOException { + try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed))) { + return in.readAllBytes(); + } + } +}