yifan-c commented on code in PR #249: URL: https://github.com/apache/cassandra-sidecar/pull/249#discussion_r2283538543
########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/jmx/StorageJmxOperations.java: ########## @@ -198,4 +198,37 @@ public interface StorageJmxOperations * Triggers start gossip */ void startGossiping(); + + /** + * Returns the number of concurrent compactors configured for the node + * @return number of concurrent compactors + */ + int getConcurrentCompactors(); + + /** + * Returns the compaction throughput limit in MiB per second as a double + * @return compaction throughput limit + */ + double getCompactionThroughputMbPerSec(); Review Comment: not used. Please explain if it is needed ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/jmx/StorageJmxOperations.java: ########## @@ -198,4 +198,37 @@ public interface StorageJmxOperations * Triggers start gossip */ void startGossiping(); + + /** + * Returns the number of concurrent compactors configured for the node + * @return number of concurrent compactors + */ + int getConcurrentCompactors(); + + /** + * Returns the compaction throughput limit in MiB per second as a double + * @return compaction throughput limit + */ + double getCompactionThroughputMbPerSec(); + + /** + * Returns the compaction throughput limit in MiB per second as a double (alternative method name) + * @return compaction throughput limit + */ + double getCompactionThroughtputMibPerSecAsDouble(); Review Comment: not used. Please explain if it is needed ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/jmx/CompactionManagerJmxOperations.java: ########## @@ -0,0 +1,48 @@ +/* + * 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.cassandra.sidecar.adapters.base.jmx; + +import java.util.List; +import java.util.Map; + +/** + * An interface that pulls methods from the Cassandra CompactionManager JMX proxy + */ +public interface CompactionManagerJmxOperations +{ + String COMPACTION_MANAGER_OBJ_NAME = "org.apache.cassandra.db:type=CompactionManager"; + + /** + * Returns the number of concurrent compactors configured for the node. + * @return number of concurrent compactors + */ + int getCoreCompactorThreads(); + + /** + * Returns active compactions as a list of compaction info maps + * @return list of compaction info maps + */ + List<Map<String, String>> getCompactions(); + + /** + * Returns compaction throughput in bytes per second + * @return compaction throughput in bytes per second + */ + long getCompactionThroughputMbPerSec(); +} Review Comment: new line at the end of file per sytle guide ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/CassandraMetricsOperations.java: ########## @@ -250,4 +278,187 @@ private List<ClientConnectionEntry> statsToEntries(Stream<ConnectedClientStats> stat.authenticationMode, stat.authenticationMetadata); } + + /** + * Represents the metrics related to compaction stats that are supported by the Sidecar + */ + public enum CompactionStatsMetrics + { + TOTAL_COMPACTIONS_COMPLETED("TotalCompactionsCompleted", MetricType.COUNTER), + BYTES_COMPACTED("BytesCompacted", MetricType.COUNTER), + COMPACTIONS_ABORTED("CompactionsAborted", MetricType.COUNTER), + COMPACTIONS_REDUCED("CompactionsReduced", MetricType.COUNTER), + SSTABLES_DROPPED_FROM_COMPACTION("SSTablesDroppedFromCompaction", MetricType.COUNTER), + PENDING_TASKS_BY_TABLE_NAME("PendingTasksByTableName", MetricType.GAUGE); + + private final String metricName; + private final MetricType type; + + CompactionStatsMetrics(String metricName, MetricType type) + { + this.metricName = metricName; + this.type = type; + } + + String metricName() + { + return metricName; + } + } + /** + * {@inheritDoc} + */ + @Override + public CompactionStatsResponse compactionStats() + { + // Get compaction manager and storage service proxies + CompactionManagerJmxOperations compactionManager = jmxClient.proxy(CompactionManagerJmxOperations.class, COMPACTION_MANAGER_OBJ_NAME); + StorageJmxOperations storageService = jmxClient.proxy(StorageJmxOperations.class, STORAGE_SERVICE_OBJ_NAME); + + // Get concurrent compactors from StorageService as per specification + long concurrentCompactors = storageService.getConcurrentCompactors(); + + // Get pending tasks grouped by keyspace and table + Map<String, Map<String, Integer>> pendingTasks = getPendingCompactionTasksByTable(); + long totalPendingTasks = pendingTasks.values().stream() + .mapToLong(tableMap -> tableMap.values().stream().mapToInt(Integer::intValue).sum()) + .sum(); + + // Get compaction metrics from JMX counters and meters + long completedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.TOTAL_COMPACTIONS_COMPLETED)); + long dataCompacted = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.BYTES_COMPACTED)); + long abortedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_ABORTED)); + long reducedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_REDUCED)); + long sstablesDroppedFromCompaction = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.SSTABLES_DROPPED_FROM_COMPACTION)); + + // Get completed compactions rate with proper time conversions + CompactionStatsResponse.CompletedCompactionsRate completedCompactionsRate = getCompletedCompactionsRate(); + + // Get active compactions with all required fields + List<ActiveCompactionEntry> activeCompactions = getActiveCompactions(compactionManager.getCompactions()); + long activeCompactionsCount = activeCompactions.size(); + + // Calculate remaining time in seconds based on throughput and remaining bytes + String activeCompactionsRemainingTime = calculateRemainingTimeSeconds(activeCompactions, storageService); + + return new CompactionStatsResponse(concurrentCompactors, pendingTasks, totalPendingTasks, + completedCompactions, dataCompacted, abortedCompactions, + reducedCompactions, sstablesDroppedFromCompaction, + completedCompactionsRate, + activeCompactions, activeCompactionsCount, activeCompactionsRemainingTime); + } + + private Map<String, Map<String, Integer>> getPendingCompactionTasksByTable() + { + // Get pending tasks by table name from Gauge metric + Object value = getCompactionMetric(CompactionStatsMetrics.PENDING_TASKS_BY_TABLE_NAME); + return parsePendingTasksMap(value); + } + + private Map<String, Map<String, Integer>> parsePendingTasksMap(final Object value) + { + Map<?, ?> rawMap = safeCast(value, Map.class, "pending tasks"); + Map<String, Map<String, Integer>> result = new HashMap<>(); + + for (Map.Entry<?, ?> entry : rawMap.entrySet()) + { + String keyspace = safeCast(entry.getKey(), String.class, "keyspace name"); + Map<?, ?> rawTableMap = safeCast(entry.getValue(), Map.class, "table data"); + Map<String, Integer> tableMap = new HashMap<>(); + + for (Map.Entry<?, ?> tableEntry : rawTableMap.entrySet()) + { + String tableName = safeCast(tableEntry.getKey(), String.class, "table name"); + Number taskCount = safeCast(tableEntry.getValue(), Number.class, "task count"); + tableMap.put(tableName, taskCount.intValue()); + } + + result.put(keyspace, tableMap); + } + + return result; + } + + private Object getCompactionMetric(final CompactionStatsMetrics metric) + { + String metricObjectType = String.format(METRICS_OBJ_TYPE_COMPACTION, metric.metricName()); + return queryMetric(metricObjectType, metric.type); + } + + private CompactionStatsResponse.CompletedCompactionsRate getCompletedCompactionsRate() + { + // Get rates from meter metric for TotalCompactionsCompleted + String metricObjectType = String.format(METRICS_OBJ_TYPE_COMPACTION, "TotalCompactionsCompleted"); + MeterMetricsJmxOperations metricsProxy = jmxClient.proxy(MeterMetricsJmxOperations.class, metricObjectType); + + // Convert rates according to specification: Review Comment: ```suggestion // Convert per-second rates to the specification: ``` ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/CassandraMetricsOperations.java: ########## @@ -61,6 +67,27 @@ public class CassandraMetricsOperations implements MetricsOperations private final ConnectedClientStatsDatabaseAccessor dbAccessor; protected final JmxClient jmxClient; + private static final String METRICS_OBJ_TYPE_KEYSPACE_TABLE_FORMAT = "org.apache.cassandra.metrics:type=Table,keyspace=%s,scope=%s,name=%s"; + private static final String METRICS_OBJ_TYPE_COMPACTION = "org.apache.cassandra.metrics:type=Compaction,name=%s"; + + // Constants for compaction info map keys + public static final String ID = "id"; + public static final String KEYSPACE = "keyspace"; + public static final String COLUMNFAMILY = "columnfamily"; + public static final String COMPLETED = "completed"; + public static final String TOTAL = "total"; + public static final String TASK_TYPE = "taskType"; + public static final String COMPACTION_ID = "compactionId"; + public static final String SSTABLES = "sstables"; + public static final String TARGET_DIRECTORY = "targetDirectory"; + + public static final String TIME_FORMAT = "%dh%02dm%02ds"; + + // Default values + public static final String DEFAULTVAL_STRING = "unknown"; + public static final String DEFAULTVAL_NUMBER = "-1"; + public static final String DEFAULTVAL_N_A = "n/a"; Review Comment: `DEFAULT_STRING_VALUE`? and so on. ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/CassandraMetricsOperations.java: ########## @@ -250,4 +278,187 @@ private List<ClientConnectionEntry> statsToEntries(Stream<ConnectedClientStats> stat.authenticationMode, stat.authenticationMetadata); } + + /** + * Represents the metrics related to compaction stats that are supported by the Sidecar + */ + public enum CompactionStatsMetrics + { + TOTAL_COMPACTIONS_COMPLETED("TotalCompactionsCompleted", MetricType.COUNTER), + BYTES_COMPACTED("BytesCompacted", MetricType.COUNTER), + COMPACTIONS_ABORTED("CompactionsAborted", MetricType.COUNTER), + COMPACTIONS_REDUCED("CompactionsReduced", MetricType.COUNTER), + SSTABLES_DROPPED_FROM_COMPACTION("SSTablesDroppedFromCompaction", MetricType.COUNTER), + PENDING_TASKS_BY_TABLE_NAME("PendingTasksByTableName", MetricType.GAUGE); + + private final String metricName; + private final MetricType type; + + CompactionStatsMetrics(String metricName, MetricType type) + { + this.metricName = metricName; + this.type = type; + } + + String metricName() + { + return metricName; + } + } + /** + * {@inheritDoc} + */ + @Override + public CompactionStatsResponse compactionStats() + { + // Get compaction manager and storage service proxies + CompactionManagerJmxOperations compactionManager = jmxClient.proxy(CompactionManagerJmxOperations.class, COMPACTION_MANAGER_OBJ_NAME); + StorageJmxOperations storageService = jmxClient.proxy(StorageJmxOperations.class, STORAGE_SERVICE_OBJ_NAME); + + // Get concurrent compactors from StorageService as per specification + long concurrentCompactors = storageService.getConcurrentCompactors(); + + // Get pending tasks grouped by keyspace and table + Map<String, Map<String, Integer>> pendingTasks = getPendingCompactionTasksByTable(); + long totalPendingTasks = pendingTasks.values().stream() + .mapToLong(tableMap -> tableMap.values().stream().mapToInt(Integer::intValue).sum()) + .sum(); + + // Get compaction metrics from JMX counters and meters + long completedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.TOTAL_COMPACTIONS_COMPLETED)); + long dataCompacted = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.BYTES_COMPACTED)); + long abortedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_ABORTED)); + long reducedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_REDUCED)); + long sstablesDroppedFromCompaction = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.SSTABLES_DROPPED_FROM_COMPACTION)); + + // Get completed compactions rate with proper time conversions + CompactionStatsResponse.CompletedCompactionsRate completedCompactionsRate = getCompletedCompactionsRate(); + + // Get active compactions with all required fields + List<ActiveCompactionEntry> activeCompactions = getActiveCompactions(compactionManager.getCompactions()); + long activeCompactionsCount = activeCompactions.size(); + + // Calculate remaining time in seconds based on throughput and remaining bytes + String activeCompactionsRemainingTime = calculateRemainingTimeSeconds(activeCompactions, storageService); + + return new CompactionStatsResponse(concurrentCompactors, pendingTasks, totalPendingTasks, + completedCompactions, dataCompacted, abortedCompactions, + reducedCompactions, sstablesDroppedFromCompaction, + completedCompactionsRate, + activeCompactions, activeCompactionsCount, activeCompactionsRemainingTime); Review Comment: strongly -1 on returning Http response object from this layer (jmx). It should return a data structure (say, `CompactionStats`) can be shared by other server components. The handlers are to return the http response object (converting from `CompactionStats`) ########## client-common/src/main/java/org/apache/cassandra/sidecar/common/response/CompactionStatsResponse.java: ########## @@ -0,0 +1,194 @@ +/* + * 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.cassandra.sidecar.common.response; + +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.cassandra.sidecar.common.response.data.ActiveCompactionEntry; + +/** + * Response class for the CompactionStats API + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CompactionStatsResponse +{ + private final long concurrentCompactors; + private final Map<String, Map<String, Integer>> pendingTasks; + private final long totalPendingTasks; + private final long completedCompactions; + private final long dataCompacted; + private final long abortedCompactions; + private final long reducedCompactions; + private final long sstablesDroppedFromCompaction; + private final CompletedCompactionsRate completedCompactionsRate; + private final List<ActiveCompactionEntry> activeCompactions; + private final long activeCompactionsCount; + private final String activeCompactionsRemainingTime; + + /** + * Represents the completed compactions rate + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public static class CompletedCompactionsRate + { + private final String meanRate; + private final String fifteenMinuteRate; + + @JsonCreator + public CompletedCompactionsRate(@JsonProperty("meanRate") final String meanRate, + @JsonProperty("fifteenMinuteRate") final String fifteenMinuteRate) + { + this.meanRate = meanRate; + this.fifteenMinuteRate = fifteenMinuteRate; + } + + @JsonProperty("meanRate") + public String meanRate() + { + return meanRate; + } + + @JsonProperty("fifteenMinuteRate") + public String fifteenMinuteRate() + { + return fifteenMinuteRate; + } + } + + /** + * Constructs a new {@link CompactionStatsResponse}. + * + * @param concurrentCompactors number of concurrent compactors + * @param pendingTasks pending compaction tasks by keyspace and table + * @param totalPendingTasks total number of pending tasks + * @param completedCompactions total compactions completed + * @param dataCompacted total data compacted in bytes + * @param abortedCompactions total compactions aborted + * @param reducedCompactions total compactions reduced + * @param sstablesDroppedFromCompaction total SSTables dropped from compaction + * @param completedCompactionsRate completed compactions rate statistics + * @param activeCompactions list of active compactions + * @param activeCompactionsCount number of active compactions + * @param activeCompactionsRemainingTime estimated remaining time for active compactions formatted as "XhYYmZZs" + */ + @JsonCreator + public CompactionStatsResponse(@JsonProperty("concurrentCompactors") final long concurrentCompactors, + @JsonProperty("pendingTasks") final Map<String, Map<String, Integer>> pendingTasks, + @JsonProperty("totalPendingTasks") final long totalPendingTasks, + @JsonProperty("completedCompactions") final long completedCompactions, + @JsonProperty("dataCompacted") final long dataCompacted, + @JsonProperty("abortedCompactions") final long abortedCompactions, + @JsonProperty("reducedCompactions") final long reducedCompactions, + @JsonProperty("sstablesDroppedFromCompaction") final long sstablesDroppedFromCompaction, + @JsonProperty("completedCompactionsRate") final CompletedCompactionsRate completedCompactionsRate, + @JsonProperty("activeCompactions") final List<ActiveCompactionEntry> activeCompactions, + @JsonProperty("activeCompactionsCount") final long activeCompactionsCount, + @JsonProperty("activeCompactionsRemainingTime") final String activeCompactionsRemainingTime) + { + this.concurrentCompactors = concurrentCompactors; + this.pendingTasks = pendingTasks; + this.totalPendingTasks = totalPendingTasks; + this.completedCompactions = completedCompactions; + this.dataCompacted = dataCompacted; + this.abortedCompactions = abortedCompactions; + this.reducedCompactions = reducedCompactions; + this.sstablesDroppedFromCompaction = sstablesDroppedFromCompaction; + this.completedCompactionsRate = completedCompactionsRate; + this.activeCompactions = activeCompactions; + this.activeCompactionsCount = activeCompactionsCount; + this.activeCompactionsRemainingTime = activeCompactionsRemainingTime; + } + + @JsonProperty("concurrentCompactors") + public long concurrentCompactors() + { + return concurrentCompactors; + } + + @JsonProperty("pendingTasks") + public Map<String, Map<String, Integer>> pendingTasks() + { + return pendingTasks; + } + + @JsonProperty("totalPendingTasks") + public long totalPendingTasks() + { + return totalPendingTasks; + } + + @JsonProperty("completedCompactions") + public long completedCompactions() + { + return completedCompactions; + } + + @JsonProperty("dataCompacted") + public long dataCompacted() + { + return dataCompacted; + } + + @JsonProperty("abortedCompactions") + public long abortedCompactions() + { + return abortedCompactions; + } + + @JsonProperty("reducedCompactions") + public long reducedCompactions() + { + return reducedCompactions; + } + + @JsonProperty("sstablesDroppedFromCompaction") + public long sstablesDroppedFromCompaction() + { + return sstablesDroppedFromCompaction; + } + + @JsonProperty("completedCompactionsRate") + public CompletedCompactionsRate completedCompactionsRate() + { + return completedCompactionsRate; + } + + + @JsonProperty("activeCompactions") + public List<ActiveCompactionEntry> activeCompactions() + { + return activeCompactions; + } + + @JsonProperty("activeCompactionsCount") + public long activeCompactionsCount() + { + return activeCompactionsCount; + } + + @JsonProperty("activeCompactionsRemainingTime") + public String activeCompactionsRemainingTime() + { + return activeCompactionsRemainingTime; + } +} Review Comment: new line ########## integration-tests/src/integrationTest/org/apache/cassandra/sidecar/routes/CompactionStatsIntegrationTest.java: ########## @@ -0,0 +1,337 @@ +/* + * 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.cassandra.sidecar.routes; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; + +import io.vertx.core.buffer.Buffer; +import io.vertx.core.http.HttpResponseExpectation; +import io.vertx.ext.web.client.HttpResponse; +import org.apache.cassandra.sidecar.common.response.CompactionStatsResponse; +import org.apache.cassandra.sidecar.common.response.data.ActiveCompactionEntry; +import org.apache.cassandra.sidecar.testing.QualifiedName; +import org.apache.cassandra.sidecar.testing.SharedClusterSidecarIntegrationTestBase; + +import static org.apache.cassandra.testing.TestUtils.DC1_RF1; +import static org.apache.cassandra.testing.TestUtils.TEST_KEYSPACE; +import static org.apache.cassandra.testing.TestUtils.TEST_TABLE_PREFIX; +import static org.apache.cassandra.testing.utils.AssertionUtils.getBlocking; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Integration tests for the Compaction Statistics API endpoint. + * + * <p>Tests the compaction statistics functionality by generating large-scale SSTable data across + * multiple tables, triggering concurrent compactions, and validating API responses in both active + * and completed compaction scenarios.</p> + * + * <h2>Testing Mechanism</h2> + * <ul> + * <li><strong>Data Setup:</strong> Creates 5 tables with 100 SSTables each (500 total, 1000 records per SSTable)</li> + * <li><strong>Concurrency:</strong> Triggers compactions simultaneously using separate threads</li> + * <li><strong>Active Detection:</strong> Polls API immediately with retry logic to catch in-progress compactions</li> + * <li><strong>Comprehensive Validation:</strong> Validates all response fields including statistics, rates, + * pending tasks, and detailed active compaction data when available</li> + * <li><strong>Dual Success:</strong> Test passes whether active compactions are captured or completed</li> + * </ul> + */ +class CompactionStatsIntegrationTest extends SharedClusterSidecarIntegrationTestBase +{ + private static final String COMPACTION_STATS_ROUTE = "/api/v1/cassandra/stats/compaction"; + private static final List<QualifiedName> TEST_TABLES = new ArrayList<>(); + private static final int TABLE_COUNT = 5; + + @Override + protected void initializeSchemaForTest() + { + createTestKeyspace(TEST_KEYSPACE, DC1_RF1); + + for (int i = 1; i <= TABLE_COUNT; i++) { + TEST_TABLES.add(new QualifiedName(TEST_KEYSPACE, TEST_TABLE_PREFIX + "_compaction_" + i)); + } + + // Create test tables for compaction activity + for (QualifiedName tableName : TEST_TABLES) { + createTestTable(tableName, + "CREATE TABLE %s ( \n" + + " id int PRIMARY KEY, \n" + + " data text \n" + + ");"); + } + } Review Comment: left curly brace at new line (this and others in this file) ########## server/src/main/java/org/apache/cassandra/sidecar/handlers/CompactionStatsHandler.java: ########## @@ -0,0 +1,82 @@ +/* + * 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.cassandra.sidecar.handlers; + +import java.util.Collections; +import java.util.Set; + +import com.google.inject.Inject; +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.net.SocketAddress; +import io.vertx.ext.auth.authorization.Authorization; +import io.vertx.ext.web.RoutingContext; +import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions; +import org.apache.cassandra.sidecar.acl.authorization.CassandraPermissions; +import org.apache.cassandra.sidecar.common.server.MetricsOperations; +import org.apache.cassandra.sidecar.concurrent.ExecutorPools; +import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher; +import org.jetbrains.annotations.NotNull; + +import static org.apache.cassandra.sidecar.acl.authorization.ResourceScopes.DATA_SCOPE; + +/** + * Handler for retrieving compaction statistics + */ +public class CompactionStatsHandler extends AbstractHandler<Void> implements AccessProtected +{ + /** + * Constructs a handler with the provided {@code metadataFetcher} + * + * @param metadataFetcher the metadata fetcher + * @param executorPools executor pools for blocking executions + */ + @Inject + protected CompactionStatsHandler(final InstanceMetadataFetcher metadataFetcher, final ExecutorPools executorPools) + { + super(metadataFetcher, executorPools, null); + } + + @Override + public Set<Authorization> requiredAuthorizations() + { + return Collections.singleton(BasicPermissions.STATS_CLUSTER_SCOPED.toAuthorization()); + } + + /** + * {@inheritDoc} + */ + @Override + public void handleInternal(RoutingContext context, + HttpServerRequest httpRequest, + @NotNull String host, + SocketAddress remoteAddress, + Void request) + { + MetricsOperations operations = metadataFetcher.delegate(host).metricsOperations(); + executorPools.service() + .executeBlocking(operations::compactionStats) + .onSuccess(context::json) + .onFailure(cause -> processFailure(cause, context, host, remoteAddress, request)); + } + + protected Void extractParamsOrThrow(RoutingContext context) + { + return null; + } +} Review Comment: new line ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/data/CompositeDataUtil.java: ########## @@ -50,4 +50,55 @@ public static <T> T extractValue(CompositeData data, String key) throw new RuntimeException("Value type mismatched of key: " + key, cce); } } + + /** + * Safely casts an object to the specified type with descriptive error handling. + * This method performs a runtime type check before casting to prevent ClassCastException + * and provides meaningful error messages when the cast fails. + * + * @param value the object to be cast + * @param expectedType the expected type to cast to + * @param contextDescription descriptive context for error messages (e.g., "keyspace name", "table data") + * @param <T> the target type + * @return the cast object of type T + * @throws IllegalStateException if the value is not an instance of the expected type, + * with a descriptive message indicating what was expected vs what was received + */ + public static <T> T safeCast(Object value, Class<T> expectedType, String contextDescription) + { + if (!expectedType.isInstance(value)) + { + throw new IllegalStateException("Expected " + expectedType.getSimpleName() + " for " + contextDescription + " but got: " + + (value == null ? "null" : value.getClass().getSimpleName())); + } + return expectedType.cast(value); + } + + /** + * Safely parses a string to a long with descriptive error handling. + * This method handles null values and provides meaningful error messages when parsing fails. + * + * @param value the string value to be parsed + * @param contextDescription descriptive context for error messages (e.g., "completed bytes", "total bytes") + * @return the parsed long value + * @throws IllegalStateException if the value cannot be parsed as a long, + * with a descriptive message indicating what failed to parse + */ + public static long safeParseLong(final String value, final String contextDescription) + { + if (value == null) + { + throw new IllegalStateException("Cannot parse null value for " + contextDescription); + } + + try + { + return Long.parseLong(value); + } + catch (NumberFormatException e) + { + throw new IllegalStateException("Failed to parse long value '" + value + "' for " + contextDescription + ": " + e.getMessage(), e); Review Comment: re-throw `NumberFormatException` with better description? ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/jmx/StorageJmxOperations.java: ########## @@ -198,4 +198,37 @@ public interface StorageJmxOperations * Triggers start gossip */ void startGossiping(); + + /** + * Returns the number of concurrent compactors configured for the node + * @return number of concurrent compactors + */ + int getConcurrentCompactors(); + + /** + * Returns the compaction throughput limit in MiB per second as a double + * @return compaction throughput limit + */ + double getCompactionThroughputMbPerSec(); + + /** + * Returns the compaction throughput limit in MiB per second as a double (alternative method name) + * @return compaction throughput limit + */ + double getCompactionThroughtputMibPerSecAsDouble(); + + /** + * Returns current compaction throughput measurements in MiB per second for different time windows + * @return map of time windows to throughput measurements + */ + Map<String, String> getCurrentCompactionThroughputMebibytesPerSec(); + + /** + * Returns the current compaction throughput in bytes per second. + * This method provides the throughput measurement in bytes per second, which is useful + * for calculating estimated completion times and remaining work for active compactions. + * + * @return the current compaction throughput in bytes per second, or 0 if throughput cannot be determined + */ + long getCompactionThroughtputBytesPerSec(); Review Comment: Please add a comment why there is a typo. Otherwise, it might be corrected by mistake in the future. ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/jmx/StorageJmxOperations.java: ########## @@ -198,4 +198,37 @@ public interface StorageJmxOperations * Triggers start gossip */ void startGossiping(); + + /** + * Returns the number of concurrent compactors configured for the node + * @return number of concurrent compactors + */ + int getConcurrentCompactors(); + + /** + * Returns the compaction throughput limit in MiB per second as a double + * @return compaction throughput limit + */ + double getCompactionThroughputMbPerSec(); + + /** + * Returns the compaction throughput limit in MiB per second as a double (alternative method name) + * @return compaction throughput limit + */ + double getCompactionThroughtputMibPerSecAsDouble(); + + /** + * Returns current compaction throughput measurements in MiB per second for different time windows + * @return map of time windows to throughput measurements + */ + Map<String, String> getCurrentCompactionThroughputMebibytesPerSec(); Review Comment: not used. Please explain if it is needed ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/data/CompositeDataUtil.java: ########## @@ -50,4 +50,55 @@ public static <T> T extractValue(CompositeData data, String key) throw new RuntimeException("Value type mismatched of key: " + key, cce); } } + + /** + * Safely casts an object to the specified type with descriptive error handling. + * This method performs a runtime type check before casting to prevent ClassCastException + * and provides meaningful error messages when the cast fails. + * + * @param value the object to be cast + * @param expectedType the expected type to cast to + * @param contextDescription descriptive context for error messages (e.g., "keyspace name", "table data") + * @param <T> the target type + * @return the cast object of type T + * @throws IllegalStateException if the value is not an instance of the expected type, + * with a descriptive message indicating what was expected vs what was received + */ + public static <T> T safeCast(Object value, Class<T> expectedType, String contextDescription) + { + if (!expectedType.isInstance(value)) + { + throw new IllegalStateException("Expected " + expectedType.getSimpleName() + " for " + contextDescription + " but got: " + + (value == null ? "null" : value.getClass().getSimpleName())); Review Comment: Should it throw `ClassCastException` instead? Looks like the type check here is to prepare a better description of the error. ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/CassandraMetricsOperations.java: ########## @@ -250,4 +278,187 @@ private List<ClientConnectionEntry> statsToEntries(Stream<ConnectedClientStats> stat.authenticationMode, stat.authenticationMetadata); } + + /** + * Represents the metrics related to compaction stats that are supported by the Sidecar + */ + public enum CompactionStatsMetrics + { + TOTAL_COMPACTIONS_COMPLETED("TotalCompactionsCompleted", MetricType.COUNTER), + BYTES_COMPACTED("BytesCompacted", MetricType.COUNTER), + COMPACTIONS_ABORTED("CompactionsAborted", MetricType.COUNTER), + COMPACTIONS_REDUCED("CompactionsReduced", MetricType.COUNTER), + SSTABLES_DROPPED_FROM_COMPACTION("SSTablesDroppedFromCompaction", MetricType.COUNTER), + PENDING_TASKS_BY_TABLE_NAME("PendingTasksByTableName", MetricType.GAUGE); + + private final String metricName; + private final MetricType type; + + CompactionStatsMetrics(String metricName, MetricType type) + { + this.metricName = metricName; + this.type = type; + } + + String metricName() + { + return metricName; + } + } + /** + * {@inheritDoc} + */ + @Override + public CompactionStatsResponse compactionStats() + { + // Get compaction manager and storage service proxies + CompactionManagerJmxOperations compactionManager = jmxClient.proxy(CompactionManagerJmxOperations.class, COMPACTION_MANAGER_OBJ_NAME); + StorageJmxOperations storageService = jmxClient.proxy(StorageJmxOperations.class, STORAGE_SERVICE_OBJ_NAME); + + // Get concurrent compactors from StorageService as per specification + long concurrentCompactors = storageService.getConcurrentCompactors(); + + // Get pending tasks grouped by keyspace and table + Map<String, Map<String, Integer>> pendingTasks = getPendingCompactionTasksByTable(); + long totalPendingTasks = pendingTasks.values().stream() + .mapToLong(tableMap -> tableMap.values().stream().mapToInt(Integer::intValue).sum()) + .sum(); + + // Get compaction metrics from JMX counters and meters + long completedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.TOTAL_COMPACTIONS_COMPLETED)); + long dataCompacted = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.BYTES_COMPACTED)); + long abortedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_ABORTED)); + long reducedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_REDUCED)); + long sstablesDroppedFromCompaction = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.SSTABLES_DROPPED_FROM_COMPACTION)); + + // Get completed compactions rate with proper time conversions + CompactionStatsResponse.CompletedCompactionsRate completedCompactionsRate = getCompletedCompactionsRate(); + + // Get active compactions with all required fields + List<ActiveCompactionEntry> activeCompactions = getActiveCompactions(compactionManager.getCompactions()); + long activeCompactionsCount = activeCompactions.size(); + + // Calculate remaining time in seconds based on throughput and remaining bytes + String activeCompactionsRemainingTime = calculateRemainingTimeSeconds(activeCompactions, storageService); + + return new CompactionStatsResponse(concurrentCompactors, pendingTasks, totalPendingTasks, + completedCompactions, dataCompacted, abortedCompactions, + reducedCompactions, sstablesDroppedFromCompaction, + completedCompactionsRate, + activeCompactions, activeCompactionsCount, activeCompactionsRemainingTime); + } + + private Map<String, Map<String, Integer>> getPendingCompactionTasksByTable() + { + // Get pending tasks by table name from Gauge metric + Object value = getCompactionMetric(CompactionStatsMetrics.PENDING_TASKS_BY_TABLE_NAME); + return parsePendingTasksMap(value); + } + + private Map<String, Map<String, Integer>> parsePendingTasksMap(final Object value) + { + Map<?, ?> rawMap = safeCast(value, Map.class, "pending tasks"); + Map<String, Map<String, Integer>> result = new HashMap<>(); + + for (Map.Entry<?, ?> entry : rawMap.entrySet()) + { + String keyspace = safeCast(entry.getKey(), String.class, "keyspace name"); + Map<?, ?> rawTableMap = safeCast(entry.getValue(), Map.class, "table data"); + Map<String, Integer> tableMap = new HashMap<>(); + + for (Map.Entry<?, ?> tableEntry : rawTableMap.entrySet()) + { + String tableName = safeCast(tableEntry.getKey(), String.class, "table name"); + Number taskCount = safeCast(tableEntry.getValue(), Number.class, "task count"); + tableMap.put(tableName, taskCount.intValue()); + } + + result.put(keyspace, tableMap); + } + + return result; + } + + private Object getCompactionMetric(final CompactionStatsMetrics metric) + { + String metricObjectType = String.format(METRICS_OBJ_TYPE_COMPACTION, metric.metricName()); + return queryMetric(metricObjectType, metric.type); + } + + private CompactionStatsResponse.CompletedCompactionsRate getCompletedCompactionsRate() + { + // Get rates from meter metric for TotalCompactionsCompleted + String metricObjectType = String.format(METRICS_OBJ_TYPE_COMPACTION, "TotalCompactionsCompleted"); + MeterMetricsJmxOperations metricsProxy = jmxClient.proxy(MeterMetricsJmxOperations.class, metricObjectType); + + // Convert rates according to specification: + // meanRate: compactions per hour + // fifteenMinuteRate: compactions per minute for last 15 minutes + double meanRateValue = metricsProxy.getMeanRate() * 3600; // Convert per second to per hour + double fifteenMinuteRateValue = metricsProxy.getFifteenMinuteRate() * 60; // Convert per second to per minute + + String meanRate = String.format("%.2f/hour", meanRateValue); + String fifteenMinuteRate = String.format("%.2f/minute", fifteenMinuteRateValue); + + return new CompactionStatsResponse.CompletedCompactionsRate(meanRate, fifteenMinuteRate); + } + + + private List<ActiveCompactionEntry> getActiveCompactions(final List<Map<String, String>> compactions) + { + return compactions.stream().map(compactionInfo -> { + // Extract fields according to specification + String id = compactionInfo.getOrDefault(COMPACTION_ID, DEFAULTVAL_STRING); + String keyspace = compactionInfo.getOrDefault(KEYSPACE, DEFAULTVAL_STRING); + String columnFamily = compactionInfo.getOrDefault(COLUMNFAMILY, DEFAULTVAL_STRING); + String taskType = compactionInfo.getOrDefault(TASK_TYPE, DEFAULTVAL_STRING); + + // Parse byte values + long completedBytes = safeParseLong(compactionInfo.getOrDefault(COMPLETED, DEFAULTVAL_NUMBER), "completed bytes"); + long totalBytes = safeParseLong(compactionInfo.getOrDefault(TOTAL, DEFAULTVAL_NUMBER), "total bytes"); + + // Calculate percentage completed + double percentCompleted = totalBytes == -1 ? 0.0 : (double) completedBytes / totalBytes * 100.0; + + // Parse SSTables list + String ssTablesStr = compactionInfo.getOrDefault(SSTABLES, DEFAULTVAL_STRING); Review Comment: Does it return `List("unknown")` when there is no sstable? Should it return empty list instead? ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/data/CompositeDataUtil.java: ########## @@ -50,4 +50,55 @@ public static <T> T extractValue(CompositeData data, String key) throw new RuntimeException("Value type mismatched of key: " + key, cce); } } + + /** + * Safely casts an object to the specified type with descriptive error handling. + * This method performs a runtime type check before casting to prevent ClassCastException + * and provides meaningful error messages when the cast fails. + * + * @param value the object to be cast + * @param expectedType the expected type to cast to + * @param contextDescription descriptive context for error messages (e.g., "keyspace name", "table data") + * @param <T> the target type + * @return the cast object of type T + * @throws IllegalStateException if the value is not an instance of the expected type, + * with a descriptive message indicating what was expected vs what was received + */ + public static <T> T safeCast(Object value, Class<T> expectedType, String contextDescription) + { + if (!expectedType.isInstance(value)) + { + throw new IllegalStateException("Expected " + expectedType.getSimpleName() + " for " + contextDescription + " but got: " + + (value == null ? "null" : value.getClass().getSimpleName())); + } + return expectedType.cast(value); + } + + /** + * Safely parses a string to a long with descriptive error handling. + * This method handles null values and provides meaningful error messages when parsing fails. + * + * @param value the string value to be parsed + * @param contextDescription descriptive context for error messages (e.g., "completed bytes", "total bytes") + * @return the parsed long value + * @throws IllegalStateException if the value cannot be parsed as a long, + * with a descriptive message indicating what failed to parse + */ + public static long safeParseLong(final String value, final String contextDescription) Review Comment: remove `final` ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/data/CompositeDataUtil.java: ########## @@ -50,4 +50,55 @@ public static <T> T extractValue(CompositeData data, String key) throw new RuntimeException("Value type mismatched of key: " + key, cce); } } + + /** + * Safely casts an object to the specified type with descriptive error handling. + * This method performs a runtime type check before casting to prevent ClassCastException + * and provides meaningful error messages when the cast fails. + * + * @param value the object to be cast + * @param expectedType the expected type to cast to + * @param contextDescription descriptive context for error messages (e.g., "keyspace name", "table data") + * @param <T> the target type + * @return the cast object of type T + * @throws IllegalStateException if the value is not an instance of the expected type, + * with a descriptive message indicating what was expected vs what was received + */ + public static <T> T safeCast(Object value, Class<T> expectedType, String contextDescription) + { + if (!expectedType.isInstance(value)) + { + throw new IllegalStateException("Expected " + expectedType.getSimpleName() + " for " + contextDescription + " but got: " + + (value == null ? "null" : value.getClass().getSimpleName())); + } + return expectedType.cast(value); + } + + /** + * Safely parses a string to a long with descriptive error handling. + * This method handles null values and provides meaningful error messages when parsing fails. + * + * @param value the string value to be parsed + * @param contextDescription descriptive context for error messages (e.g., "completed bytes", "total bytes") + * @return the parsed long value + * @throws IllegalStateException if the value cannot be parsed as a long, + * with a descriptive message indicating what failed to parse + */ + public static long safeParseLong(final String value, final String contextDescription) + { + if (value == null) + { + throw new IllegalStateException("Cannot parse null value for " + contextDescription); + } + + try + { + return Long.parseLong(value); + } + catch (NumberFormatException e) + { + throw new IllegalStateException("Failed to parse long value '" + value + "' for " + contextDescription + ": " + e.getMessage(), e); + } + } + Review Comment: nit: remove empty line. ########## client-common/src/main/java/org/apache/cassandra/sidecar/common/request/CompactionStatsRequest.java: ########## @@ -0,0 +1,46 @@ +/* + * 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.cassandra.sidecar.common.request; + +import io.netty.handler.codec.http.HttpMethod; +import org.apache.cassandra.sidecar.common.ApiEndpointsV1; +import org.apache.cassandra.sidecar.common.response.CompactionStatsResponse; + +/** + * Represents a request to get compaction statistics from the node + */ +public class CompactionStatsRequest extends JsonRequest<CompactionStatsResponse> +{ + /** + * Constructs a request to retrieve the Cassandra node compaction statistics + */ + public CompactionStatsRequest() + { + super(ApiEndpointsV1.COMPACTION_STATS_ROUTE); + } + + /** + * {@inheritDoc} + */ + @Override + public HttpMethod method() + { + return HttpMethod.GET; + } +} Review Comment: new line at the EOF ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/CassandraMetricsOperations.java: ########## @@ -250,4 +278,187 @@ private List<ClientConnectionEntry> statsToEntries(Stream<ConnectedClientStats> stat.authenticationMode, stat.authenticationMetadata); } + + /** + * Represents the metrics related to compaction stats that are supported by the Sidecar + */ + public enum CompactionStatsMetrics + { + TOTAL_COMPACTIONS_COMPLETED("TotalCompactionsCompleted", MetricType.COUNTER), + BYTES_COMPACTED("BytesCompacted", MetricType.COUNTER), + COMPACTIONS_ABORTED("CompactionsAborted", MetricType.COUNTER), + COMPACTIONS_REDUCED("CompactionsReduced", MetricType.COUNTER), + SSTABLES_DROPPED_FROM_COMPACTION("SSTablesDroppedFromCompaction", MetricType.COUNTER), + PENDING_TASKS_BY_TABLE_NAME("PendingTasksByTableName", MetricType.GAUGE); + + private final String metricName; + private final MetricType type; + + CompactionStatsMetrics(String metricName, MetricType type) + { + this.metricName = metricName; + this.type = type; + } + + String metricName() + { + return metricName; + } + } + /** + * {@inheritDoc} + */ + @Override + public CompactionStatsResponse compactionStats() + { + // Get compaction manager and storage service proxies + CompactionManagerJmxOperations compactionManager = jmxClient.proxy(CompactionManagerJmxOperations.class, COMPACTION_MANAGER_OBJ_NAME); + StorageJmxOperations storageService = jmxClient.proxy(StorageJmxOperations.class, STORAGE_SERVICE_OBJ_NAME); + + // Get concurrent compactors from StorageService as per specification + long concurrentCompactors = storageService.getConcurrentCompactors(); + + // Get pending tasks grouped by keyspace and table + Map<String, Map<String, Integer>> pendingTasks = getPendingCompactionTasksByTable(); + long totalPendingTasks = pendingTasks.values().stream() + .mapToLong(tableMap -> tableMap.values().stream().mapToInt(Integer::intValue).sum()) + .sum(); + + // Get compaction metrics from JMX counters and meters + long completedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.TOTAL_COMPACTIONS_COMPLETED)); + long dataCompacted = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.BYTES_COMPACTED)); + long abortedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_ABORTED)); + long reducedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_REDUCED)); + long sstablesDroppedFromCompaction = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.SSTABLES_DROPPED_FROM_COMPACTION)); + + // Get completed compactions rate with proper time conversions + CompactionStatsResponse.CompletedCompactionsRate completedCompactionsRate = getCompletedCompactionsRate(); + + // Get active compactions with all required fields + List<ActiveCompactionEntry> activeCompactions = getActiveCompactions(compactionManager.getCompactions()); + long activeCompactionsCount = activeCompactions.size(); + + // Calculate remaining time in seconds based on throughput and remaining bytes + String activeCompactionsRemainingTime = calculateRemainingTimeSeconds(activeCompactions, storageService); + + return new CompactionStatsResponse(concurrentCompactors, pendingTasks, totalPendingTasks, + completedCompactions, dataCompacted, abortedCompactions, + reducedCompactions, sstablesDroppedFromCompaction, + completedCompactionsRate, + activeCompactions, activeCompactionsCount, activeCompactionsRemainingTime); + } + + private Map<String, Map<String, Integer>> getPendingCompactionTasksByTable() + { + // Get pending tasks by table name from Gauge metric + Object value = getCompactionMetric(CompactionStatsMetrics.PENDING_TASKS_BY_TABLE_NAME); + return parsePendingTasksMap(value); + } + + private Map<String, Map<String, Integer>> parsePendingTasksMap(final Object value) + { + Map<?, ?> rawMap = safeCast(value, Map.class, "pending tasks"); + Map<String, Map<String, Integer>> result = new HashMap<>(); + + for (Map.Entry<?, ?> entry : rawMap.entrySet()) + { + String keyspace = safeCast(entry.getKey(), String.class, "keyspace name"); + Map<?, ?> rawTableMap = safeCast(entry.getValue(), Map.class, "table data"); + Map<String, Integer> tableMap = new HashMap<>(); + + for (Map.Entry<?, ?> tableEntry : rawTableMap.entrySet()) + { + String tableName = safeCast(tableEntry.getKey(), String.class, "table name"); + Number taskCount = safeCast(tableEntry.getValue(), Number.class, "task count"); + tableMap.put(tableName, taskCount.intValue()); + } + + result.put(keyspace, tableMap); + } + + return result; + } + + private Object getCompactionMetric(final CompactionStatsMetrics metric) + { + String metricObjectType = String.format(METRICS_OBJ_TYPE_COMPACTION, metric.metricName()); + return queryMetric(metricObjectType, metric.type); + } + + private CompactionStatsResponse.CompletedCompactionsRate getCompletedCompactionsRate() + { + // Get rates from meter metric for TotalCompactionsCompleted + String metricObjectType = String.format(METRICS_OBJ_TYPE_COMPACTION, "TotalCompactionsCompleted"); + MeterMetricsJmxOperations metricsProxy = jmxClient.proxy(MeterMetricsJmxOperations.class, metricObjectType); + + // Convert rates according to specification: + // meanRate: compactions per hour + // fifteenMinuteRate: compactions per minute for last 15 minutes + double meanRateValue = metricsProxy.getMeanRate() * 3600; // Convert per second to per hour + double fifteenMinuteRateValue = metricsProxy.getFifteenMinuteRate() * 60; // Convert per second to per minute + + String meanRate = String.format("%.2f/hour", meanRateValue); + String fifteenMinuteRate = String.format("%.2f/minute", fifteenMinuteRateValue); + + return new CompactionStatsResponse.CompletedCompactionsRate(meanRate, fifteenMinuteRate); + } + + + private List<ActiveCompactionEntry> getActiveCompactions(final List<Map<String, String>> compactions) + { + return compactions.stream().map(compactionInfo -> { + // Extract fields according to specification + String id = compactionInfo.getOrDefault(COMPACTION_ID, DEFAULTVAL_STRING); + String keyspace = compactionInfo.getOrDefault(KEYSPACE, DEFAULTVAL_STRING); + String columnFamily = compactionInfo.getOrDefault(COLUMNFAMILY, DEFAULTVAL_STRING); + String taskType = compactionInfo.getOrDefault(TASK_TYPE, DEFAULTVAL_STRING); + + // Parse byte values + long completedBytes = safeParseLong(compactionInfo.getOrDefault(COMPLETED, DEFAULTVAL_NUMBER), "completed bytes"); + long totalBytes = safeParseLong(compactionInfo.getOrDefault(TOTAL, DEFAULTVAL_NUMBER), "total bytes"); + + // Calculate percentage completed + double percentCompleted = totalBytes == -1 ? 0.0 : (double) completedBytes / totalBytes * 100.0; + + // Parse SSTables list + String ssTablesStr = compactionInfo.getOrDefault(SSTABLES, DEFAULTVAL_STRING); + List<String> ssTables = ssTablesStr.isEmpty() ? + List.of() : List.of(ssTablesStr.split(",")); Review Comment: ```suggestion List<String> ssTables = ssTablesStr.isEmpty() ? List.of() : List.of(ssTablesStr.split(",")); ``` ########## client-common/src/main/java/org/apache/cassandra/sidecar/common/response/data/ActiveCompactionEntry.java: ########## @@ -0,0 +1,131 @@ +/* + * 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.cassandra.sidecar.common.response.data; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Represents an active compaction entry + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ActiveCompactionEntry +{ + private final String id; + private final String keyspace; + private final String columnFamily; + private final String taskType; + private final long completedBytes; + private final long totalBytes; + private final double percentCompleted; + private final List<String> ssTables; + private final String targetDirectory; + + /** + * Constructs a new {@link ActiveCompactionEntry}. + * + * @param id compaction ID + * @param keyspace keyspace name + * @param columnFamily table/column family name + * @param taskType type of compaction task + * @param completedBytes completed compaction in bytes + * @param totalBytes total compaction in bytes + * @param percentCompleted percentage of completed compactions + * @param ssTables list of SSTables being compacted + * @param targetDirectory target directory for output + */ + @JsonCreator + public ActiveCompactionEntry(@JsonProperty("id") final String id, + @JsonProperty("keyspace") final String keyspace, + @JsonProperty("columnFamily") final String columnFamily, + @JsonProperty("taskType") final String taskType, + @JsonProperty("completedBytes") final long completedBytes, + @JsonProperty("totalBytes") final long totalBytes, + @JsonProperty("percentCompleted") final double percentCompleted, + @JsonProperty("ssTables") final List<String> ssTables, + @JsonProperty("targetDirectory") final String targetDirectory) + { + this.id = id; + this.keyspace = keyspace; + this.columnFamily = columnFamily; + this.taskType = taskType; + this.completedBytes = completedBytes; + this.totalBytes = totalBytes; + this.percentCompleted = percentCompleted; + this.ssTables = ssTables; + this.targetDirectory = targetDirectory; + } + + @JsonProperty("id") + public String id() + { + return id; + } + + @JsonProperty("keyspace") + public String keyspace() + { + return keyspace; + } + + @JsonProperty("columnFamily") + public String columnFamily() + { + return columnFamily; + } + + @JsonProperty("taskType") + public String taskType() + { + return taskType; + } + + @JsonProperty("completedBytes") + public long completedBytes() + { + return completedBytes; + } + + @JsonProperty("totalBytes") + public long totalBytes() + { + return totalBytes; + } + + @JsonProperty("percentCompleted") + public double percentCompleted() + { + return percentCompleted; + } + + @JsonProperty("ssTables") + public List<String> ssTables() + { + return ssTables; + } + + @JsonProperty("targetDirectory") + public String targetDirectory() + { + return targetDirectory; + } +} Review Comment: new line ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/CassandraMetricsOperations.java: ########## @@ -250,4 +278,187 @@ private List<ClientConnectionEntry> statsToEntries(Stream<ConnectedClientStats> stat.authenticationMode, stat.authenticationMetadata); } + + /** + * Represents the metrics related to compaction stats that are supported by the Sidecar + */ + public enum CompactionStatsMetrics + { + TOTAL_COMPACTIONS_COMPLETED("TotalCompactionsCompleted", MetricType.COUNTER), + BYTES_COMPACTED("BytesCompacted", MetricType.COUNTER), + COMPACTIONS_ABORTED("CompactionsAborted", MetricType.COUNTER), + COMPACTIONS_REDUCED("CompactionsReduced", MetricType.COUNTER), + SSTABLES_DROPPED_FROM_COMPACTION("SSTablesDroppedFromCompaction", MetricType.COUNTER), + PENDING_TASKS_BY_TABLE_NAME("PendingTasksByTableName", MetricType.GAUGE); + + private final String metricName; + private final MetricType type; + + CompactionStatsMetrics(String metricName, MetricType type) + { + this.metricName = metricName; + this.type = type; + } + + String metricName() + { + return metricName; + } + } + /** + * {@inheritDoc} + */ + @Override + public CompactionStatsResponse compactionStats() + { + // Get compaction manager and storage service proxies + CompactionManagerJmxOperations compactionManager = jmxClient.proxy(CompactionManagerJmxOperations.class, COMPACTION_MANAGER_OBJ_NAME); + StorageJmxOperations storageService = jmxClient.proxy(StorageJmxOperations.class, STORAGE_SERVICE_OBJ_NAME); + + // Get concurrent compactors from StorageService as per specification + long concurrentCompactors = storageService.getConcurrentCompactors(); + + // Get pending tasks grouped by keyspace and table + Map<String, Map<String, Integer>> pendingTasks = getPendingCompactionTasksByTable(); + long totalPendingTasks = pendingTasks.values().stream() + .mapToLong(tableMap -> tableMap.values().stream().mapToInt(Integer::intValue).sum()) + .sum(); + + // Get compaction metrics from JMX counters and meters + long completedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.TOTAL_COMPACTIONS_COMPLETED)); + long dataCompacted = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.BYTES_COMPACTED)); + long abortedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_ABORTED)); + long reducedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_REDUCED)); + long sstablesDroppedFromCompaction = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.SSTABLES_DROPPED_FROM_COMPACTION)); + + // Get completed compactions rate with proper time conversions + CompactionStatsResponse.CompletedCompactionsRate completedCompactionsRate = getCompletedCompactionsRate(); + + // Get active compactions with all required fields + List<ActiveCompactionEntry> activeCompactions = getActiveCompactions(compactionManager.getCompactions()); + long activeCompactionsCount = activeCompactions.size(); + + // Calculate remaining time in seconds based on throughput and remaining bytes + String activeCompactionsRemainingTime = calculateRemainingTimeSeconds(activeCompactions, storageService); + + return new CompactionStatsResponse(concurrentCompactors, pendingTasks, totalPendingTasks, + completedCompactions, dataCompacted, abortedCompactions, + reducedCompactions, sstablesDroppedFromCompaction, + completedCompactionsRate, + activeCompactions, activeCompactionsCount, activeCompactionsRemainingTime); + } + + private Map<String, Map<String, Integer>> getPendingCompactionTasksByTable() + { + // Get pending tasks by table name from Gauge metric + Object value = getCompactionMetric(CompactionStatsMetrics.PENDING_TASKS_BY_TABLE_NAME); + return parsePendingTasksMap(value); + } + + private Map<String, Map<String, Integer>> parsePendingTasksMap(final Object value) + { + Map<?, ?> rawMap = safeCast(value, Map.class, "pending tasks"); + Map<String, Map<String, Integer>> result = new HashMap<>(); + + for (Map.Entry<?, ?> entry : rawMap.entrySet()) + { + String keyspace = safeCast(entry.getKey(), String.class, "keyspace name"); + Map<?, ?> rawTableMap = safeCast(entry.getValue(), Map.class, "table data"); + Map<String, Integer> tableMap = new HashMap<>(); + + for (Map.Entry<?, ?> tableEntry : rawTableMap.entrySet()) + { + String tableName = safeCast(tableEntry.getKey(), String.class, "table name"); + Number taskCount = safeCast(tableEntry.getValue(), Number.class, "task count"); + tableMap.put(tableName, taskCount.intValue()); + } + + result.put(keyspace, tableMap); + } + + return result; + } + + private Object getCompactionMetric(final CompactionStatsMetrics metric) + { + String metricObjectType = String.format(METRICS_OBJ_TYPE_COMPACTION, metric.metricName()); + return queryMetric(metricObjectType, metric.type); + } + + private CompactionStatsResponse.CompletedCompactionsRate getCompletedCompactionsRate() + { + // Get rates from meter metric for TotalCompactionsCompleted + String metricObjectType = String.format(METRICS_OBJ_TYPE_COMPACTION, "TotalCompactionsCompleted"); + MeterMetricsJmxOperations metricsProxy = jmxClient.proxy(MeterMetricsJmxOperations.class, metricObjectType); + + // Convert rates according to specification: + // meanRate: compactions per hour + // fifteenMinuteRate: compactions per minute for last 15 minutes + double meanRateValue = metricsProxy.getMeanRate() * 3600; // Convert per second to per hour + double fifteenMinuteRateValue = metricsProxy.getFifteenMinuteRate() * 60; // Convert per second to per minute + + String meanRate = String.format("%.2f/hour", meanRateValue); + String fifteenMinuteRate = String.format("%.2f/minute", fifteenMinuteRateValue); + + return new CompactionStatsResponse.CompletedCompactionsRate(meanRate, fifteenMinuteRate); + } + + + private List<ActiveCompactionEntry> getActiveCompactions(final List<Map<String, String>> compactions) + { + return compactions.stream().map(compactionInfo -> { + // Extract fields according to specification + String id = compactionInfo.getOrDefault(COMPACTION_ID, DEFAULTVAL_STRING); + String keyspace = compactionInfo.getOrDefault(KEYSPACE, DEFAULTVAL_STRING); + String columnFamily = compactionInfo.getOrDefault(COLUMNFAMILY, DEFAULTVAL_STRING); + String taskType = compactionInfo.getOrDefault(TASK_TYPE, DEFAULTVAL_STRING); + + // Parse byte values + long completedBytes = safeParseLong(compactionInfo.getOrDefault(COMPLETED, DEFAULTVAL_NUMBER), "completed bytes"); + long totalBytes = safeParseLong(compactionInfo.getOrDefault(TOTAL, DEFAULTVAL_NUMBER), "total bytes"); + + // Calculate percentage completed + double percentCompleted = totalBytes == -1 ? 0.0 : (double) completedBytes / totalBytes * 100.0; + + // Parse SSTables list + String ssTablesStr = compactionInfo.getOrDefault(SSTABLES, DEFAULTVAL_STRING); + List<String> ssTables = ssTablesStr.isEmpty() ? + List.of() : List.of(ssTablesStr.split(",")); + + String targetDirectory = compactionInfo.getOrDefault(TARGET_DIRECTORY, DEFAULTVAL_STRING); + + return new ActiveCompactionEntry(id, keyspace, columnFamily, taskType, + completedBytes, totalBytes, percentCompleted, + ssTables, targetDirectory); + }).collect(Collectors.toList()); + } + + private String calculateRemainingTimeSeconds(final List<ActiveCompactionEntry> activeCompactions, + final StorageJmxOperations storageService) + { + if (activeCompactions.isEmpty()) + { + return DEFAULTVAL_N_A; + } + + // Calculate total remaining bytes across all active compactions + long totalRemainingBytes = activeCompactions.stream() + .filter(compaction -> compaction.totalBytes() >= 0 && compaction.completedBytes() >= 0) + .mapToLong(compaction -> Math.max(0, compaction.totalBytes() - compaction.completedBytes())) + .sum(); + + long throughputBytesPerSec = storageService.getCompactionThroughtputBytesPerSec(); + if (totalRemainingBytes < 0 || throughputBytesPerSec <= 0) + { + return DEFAULTVAL_N_A; + } + + // Calculate time in seconds (throughput is already in bytes/sec) + long remainingTimeInSecs = totalRemainingBytes / throughputBytesPerSec; Review Comment: Convert to double for the time calculation? otherwise, the result is off by 1. ########## client-common/src/main/java/org/apache/cassandra/sidecar/common/response/data/PendingCompactionTasks.java: ########## @@ -0,0 +1,61 @@ +/* + * 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.cassandra.sidecar.common.response.data; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Represents pending compaction tasks by keyspace and table + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PendingCompactionTasks +{ + private final Map<String, Map<String, Integer>> pendingTasksByTable; + private final int totalPendingTasks; + + /** + * Constructs a new {@link PendingCompactionTasks}. + * + * @param pendingTasksByTable pending tasks organized by keyspace and table + * @param totalPendingTasks total count of pending tasks + */ + @JsonCreator + public PendingCompactionTasks(@JsonProperty("pendingTasksByTable") Map<String, Map<String, Integer>> pendingTasksByTable, + @JsonProperty("totalPendingTasks") int totalPendingTasks) + { + this.pendingTasksByTable = pendingTasksByTable; + this.totalPendingTasks = totalPendingTasks; + } + + @JsonProperty("pendingTasksByTable") + public Map<String, Map<String, Integer>> pendingTasksByTable() + { + return pendingTasksByTable; + } + + @JsonProperty("totalPendingTasks") + public int totalPendingTasks() + { + return totalPendingTasks; + } +} Review Comment: new line ########## adapters/adapters-base/src/main/java/org/apache/cassandra/sidecar/adapters/base/CassandraMetricsOperations.java: ########## @@ -250,4 +278,187 @@ private List<ClientConnectionEntry> statsToEntries(Stream<ConnectedClientStats> stat.authenticationMode, stat.authenticationMetadata); } + + /** + * Represents the metrics related to compaction stats that are supported by the Sidecar + */ + public enum CompactionStatsMetrics + { + TOTAL_COMPACTIONS_COMPLETED("TotalCompactionsCompleted", MetricType.COUNTER), + BYTES_COMPACTED("BytesCompacted", MetricType.COUNTER), + COMPACTIONS_ABORTED("CompactionsAborted", MetricType.COUNTER), + COMPACTIONS_REDUCED("CompactionsReduced", MetricType.COUNTER), + SSTABLES_DROPPED_FROM_COMPACTION("SSTablesDroppedFromCompaction", MetricType.COUNTER), + PENDING_TASKS_BY_TABLE_NAME("PendingTasksByTableName", MetricType.GAUGE); + + private final String metricName; + private final MetricType type; + + CompactionStatsMetrics(String metricName, MetricType type) + { + this.metricName = metricName; + this.type = type; + } + + String metricName() + { + return metricName; + } + } + /** + * {@inheritDoc} + */ + @Override + public CompactionStatsResponse compactionStats() + { + // Get compaction manager and storage service proxies + CompactionManagerJmxOperations compactionManager = jmxClient.proxy(CompactionManagerJmxOperations.class, COMPACTION_MANAGER_OBJ_NAME); + StorageJmxOperations storageService = jmxClient.proxy(StorageJmxOperations.class, STORAGE_SERVICE_OBJ_NAME); + + // Get concurrent compactors from StorageService as per specification + long concurrentCompactors = storageService.getConcurrentCompactors(); + + // Get pending tasks grouped by keyspace and table + Map<String, Map<String, Integer>> pendingTasks = getPendingCompactionTasksByTable(); + long totalPendingTasks = pendingTasks.values().stream() + .mapToLong(tableMap -> tableMap.values().stream().mapToInt(Integer::intValue).sum()) + .sum(); + + // Get compaction metrics from JMX counters and meters + long completedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.TOTAL_COMPACTIONS_COMPLETED)); + long dataCompacted = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.BYTES_COMPACTED)); + long abortedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_ABORTED)); + long reducedCompactions = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.COMPACTIONS_REDUCED)); + long sstablesDroppedFromCompaction = getValueAsLong(getCompactionMetric(CompactionStatsMetrics.SSTABLES_DROPPED_FROM_COMPACTION)); + + // Get completed compactions rate with proper time conversions + CompactionStatsResponse.CompletedCompactionsRate completedCompactionsRate = getCompletedCompactionsRate(); + + // Get active compactions with all required fields + List<ActiveCompactionEntry> activeCompactions = getActiveCompactions(compactionManager.getCompactions()); + long activeCompactionsCount = activeCompactions.size(); + + // Calculate remaining time in seconds based on throughput and remaining bytes + String activeCompactionsRemainingTime = calculateRemainingTimeSeconds(activeCompactions, storageService); + + return new CompactionStatsResponse(concurrentCompactors, pendingTasks, totalPendingTasks, + completedCompactions, dataCompacted, abortedCompactions, + reducedCompactions, sstablesDroppedFromCompaction, + completedCompactionsRate, + activeCompactions, activeCompactionsCount, activeCompactionsRemainingTime); + } + + private Map<String, Map<String, Integer>> getPendingCompactionTasksByTable() + { + // Get pending tasks by table name from Gauge metric + Object value = getCompactionMetric(CompactionStatsMetrics.PENDING_TASKS_BY_TABLE_NAME); + return parsePendingTasksMap(value); + } + + private Map<String, Map<String, Integer>> parsePendingTasksMap(final Object value) + { + Map<?, ?> rawMap = safeCast(value, Map.class, "pending tasks"); + Map<String, Map<String, Integer>> result = new HashMap<>(); + + for (Map.Entry<?, ?> entry : rawMap.entrySet()) + { + String keyspace = safeCast(entry.getKey(), String.class, "keyspace name"); + Map<?, ?> rawTableMap = safeCast(entry.getValue(), Map.class, "table data"); + Map<String, Integer> tableMap = new HashMap<>(); + + for (Map.Entry<?, ?> tableEntry : rawTableMap.entrySet()) + { + String tableName = safeCast(tableEntry.getKey(), String.class, "table name"); + Number taskCount = safeCast(tableEntry.getValue(), Number.class, "task count"); + tableMap.put(tableName, taskCount.intValue()); + } + + result.put(keyspace, tableMap); + } + + return result; + } + + private Object getCompactionMetric(final CompactionStatsMetrics metric) + { + String metricObjectType = String.format(METRICS_OBJ_TYPE_COMPACTION, metric.metricName()); + return queryMetric(metricObjectType, metric.type); + } + + private CompactionStatsResponse.CompletedCompactionsRate getCompletedCompactionsRate() + { + // Get rates from meter metric for TotalCompactionsCompleted + String metricObjectType = String.format(METRICS_OBJ_TYPE_COMPACTION, "TotalCompactionsCompleted"); + MeterMetricsJmxOperations metricsProxy = jmxClient.proxy(MeterMetricsJmxOperations.class, metricObjectType); + + // Convert rates according to specification: + // meanRate: compactions per hour + // fifteenMinuteRate: compactions per minute for last 15 minutes + double meanRateValue = metricsProxy.getMeanRate() * 3600; // Convert per second to per hour + double fifteenMinuteRateValue = metricsProxy.getFifteenMinuteRate() * 60; // Convert per second to per minute + + String meanRate = String.format("%.2f/hour", meanRateValue); + String fifteenMinuteRate = String.format("%.2f/minute", fifteenMinuteRateValue); + + return new CompactionStatsResponse.CompletedCompactionsRate(meanRate, fifteenMinuteRate); + } + + + private List<ActiveCompactionEntry> getActiveCompactions(final List<Map<String, String>> compactions) Review Comment: no `final` in the parameter ########## client-common/src/main/java/org/apache/cassandra/sidecar/common/response/data/ActiveCompactionEntry.java: ########## @@ -0,0 +1,131 @@ +/* + * 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.cassandra.sidecar.common.response.data; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Represents an active compaction entry + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ActiveCompactionEntry +{ + private final String id; + private final String keyspace; + private final String columnFamily; + private final String taskType; + private final long completedBytes; + private final long totalBytes; + private final double percentCompleted; + private final List<String> ssTables; + private final String targetDirectory; + + /** + * Constructs a new {@link ActiveCompactionEntry}. + * + * @param id compaction ID + * @param keyspace keyspace name + * @param columnFamily table/column family name + * @param taskType type of compaction task + * @param completedBytes completed compaction in bytes + * @param totalBytes total compaction in bytes + * @param percentCompleted percentage of completed compactions + * @param ssTables list of SSTables being compacted + * @param targetDirectory target directory for output + */ + @JsonCreator + public ActiveCompactionEntry(@JsonProperty("id") final String id, + @JsonProperty("keyspace") final String keyspace, + @JsonProperty("columnFamily") final String columnFamily, + @JsonProperty("taskType") final String taskType, + @JsonProperty("completedBytes") final long completedBytes, + @JsonProperty("totalBytes") final long totalBytes, + @JsonProperty("percentCompleted") final double percentCompleted, + @JsonProperty("ssTables") final List<String> ssTables, + @JsonProperty("targetDirectory") final String targetDirectory) Review Comment: no `final` ########## server/src/main/java/org/apache/cassandra/sidecar/modules/CassandraOperationsModule.java: ########## @@ -90,6 +92,22 @@ VertxRoute cassandraConnectedClientStatsRoute(RouteBuilder.Factory factory, return factory.buildRouteWithHandler(connectedClientStatsHandler); } + @GET + @Path(ApiEndpointsV1.COMPACTION_STATS_ROUTE) + @Operation(summary = "Get compaction statistics", + description = "Returns compaction statistics for the Cassandra node") + @APIResponse(description = "Compaction statistics retrieved successfully", + responseCode = "200", + content = @Content(mediaType = "application/json", + schema = @Schema(implementation = CompactionStatsResponse.class))) Review Comment: 👍 -- 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: pr-unsubscr...@cassandra.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: pr-unsubscr...@cassandra.apache.org For additional commands, e-mail: pr-h...@cassandra.apache.org