sklaha commented on code in PR #249:
URL: https://github.com/apache/cassandra-sidecar/pull/249#discussion_r2286692515


##########
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:
   done



##########
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:
   Done



##########
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:
   Done



##########
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:
   Done



-- 
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

Reply via email to