yifan-c commented on code in PR #203:
URL: https://github.com/apache/cassandra-sidecar/pull/203#discussion_r2027634403


##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CdcRawDirectorySpaceCleaner.java:
##########
@@ -0,0 +1,467 @@
+/*
+ * 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.tasks;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import com.google.common.collect.Sets;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.config.CdcConfiguration;
+import org.apache.cassandra.sidecar.db.SystemViewsDatabaseAccessor;
+import org.apache.cassandra.sidecar.exceptions.SchemaUnavailableException;
+import org.apache.cassandra.sidecar.metrics.CdcMetrics;
+import org.apache.cassandra.sidecar.metrics.SidecarMetrics;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.FileUtils;
+import org.apache.cassandra.sidecar.utils.TimeProvider;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.apache.cassandra.sidecar.utils.CdcUtil.isLogFile;
+import static org.apache.cassandra.sidecar.utils.CdcUtil.parseSegmentId;
+
+/**
+ * PeriodTask to monitor and remove the oldest commit log segments in the 
`cdc_raw` directory
+ * when the space used hits the `cdc_total_space` limit set in the yaml file.
+ */
+@Singleton
+public class CdcRawDirectorySpaceCleaner implements PeriodicTask
+{
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(CdcRawDirectorySpaceCleaner.class);
+
+    public static final String CDC_DIR_NAME = "cdc_raw";
+
+    private final TimeProvider timeProvider;
+    private final SystemViewsDatabaseAccessor systemViewsDatabaseAccessor;
+    private final CdcConfiguration cdcConfiguration;
+    private final InstanceMetadata instanceMetadata;
+    private final CdcMetrics cdcMetrics;
+
+    @Nullable
+    private volatile Long maxUsageBytes = null;
+    // lazily loaded from system_views.settings if available
+    private volatile Long maxUsageLastReadNanos = null;
+    // cdc file -> file size in bytes. It memorizes the file set of the last 
time the checker runs.
+    private volatile Map<CdcRawSegmentFile, Long> priorCdcFiles = new 
HashMap<>();
+
+    @Inject
+    public CdcRawDirectorySpaceCleaner(TimeProvider timeProvider,
+                                       SystemViewsDatabaseAccessor 
systemViewsDatabaseAccessor,
+                                       CdcConfiguration cdcConfiguration,
+                                       InstanceMetadata instanceMetadata,
+                                       SidecarMetrics metrics)
+    {
+        this.timeProvider = timeProvider;
+        this.systemViewsDatabaseAccessor = systemViewsDatabaseAccessor;
+        this.cdcConfiguration = cdcConfiguration;
+        this.instanceMetadata = instanceMetadata;
+        this.cdcMetrics = metrics.server().cdc();
+    }
+
+    @Override
+    public DurationSpec delay()
+    {
+        return cdcConfiguration.cdcRawDirectorySpaceCleanerFrequency();
+    }
+
+    @Override
+    public void execute(Promise<Void> promise)
+    {
+        try
+        {
+            routineCleanUp();
+            promise.tryComplete();
+        }
+        catch (Throwable t)
+        {
+            LOGGER.warn("Failed to perform routine clean-up of cdc_raw 
directory", t);
+            cdcMetrics.cdcRawCleanerFailed.metric.update(1L);
+            promise.fail(t);
+        }
+    }
+
+    /**
+     * @return true if we need to refresh the cached `cdc_total_space` value.
+     */
+    protected boolean shouldRefreshCachedMaxUsage()
+    {
+        return maxUsageLastReadNanos == null ||
+               (System.nanoTime() - maxUsageLastReadNanos) >=
+               
TimeUnit.MILLISECONDS.toNanos(cdcConfiguration.cacheMaxUsage().toMillis());
+    }
+
+    protected long maxUsage()
+    {
+        if (!shouldRefreshCachedMaxUsage())
+        {
+            return Objects.requireNonNull(maxUsageBytes,
+                                          "maxUsageBytes cannot be null if 
maxUsageLastReadNanos is non-null");
+        }
+
+        try
+        {
+            Long newValue = 
systemViewsDatabaseAccessor.getCdcTotalSpaceSetting();
+            if (newValue != null)
+            {
+                if (!newValue.equals(maxUsageBytes))
+                {
+                    LOGGER.info(
+                    "Change in cdc_total_space from system_views.settings 
prev={} latest={}",
+                    maxUsageBytes, newValue);
+                    this.maxUsageBytes = newValue;
+                    this.maxUsageLastReadNanos = System.nanoTime();

Review Comment:
   `TimeProvider` was introduced when adding the time skew API and it is used 
only there. At the time, there is no need for nanoTime. I am fine with either 
enriching `TimeProvider` or just using `System` (if considering `TimeProvider` 
is private to  the time skew API). 



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