jberragan commented on code in PR #203: URL: https://github.com/apache/cassandra-sidecar/pull/203#discussion_r2025812212
########## 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(); + return newValue; + } + } + } + catch (SchemaUnavailableException e) + { + LOGGER.debug("Could not read cdc_total_space from system_views.settings", e); + } + catch (Throwable t) + { + LOGGER.warn("Error reading cdc_total_space from system_views.settings", t); + } + + LOGGER.warn( + "Could not read cdc_total_space from system_views.settings, falling back to props"); + return cdcConfiguration.fallbackCdcRawDirectoryMaxSizeBytes(); + } + + @Override + public ScheduleDecision scheduleDecision() + { + if (cdcConfiguration.enableCdcRawDirectoryRoutineCleanUp()) + { + return ScheduleDecision.EXECUTE; + } + LOGGER.debug("Skipping CdcRawDirectorySpaceCleaner: feature is disabled"); + return ScheduleDecision.SKIP; + } + + protected void routineCleanUp() + { + List<String> dataDirectories = instanceMetadata.dataDirs(); + dataDirectories.stream() + .map(dir -> new File(dir, CDC_DIR_NAME)) + .forEach(this::cleanUpCdcRawDirectory); + } + + protected void cleanUpCdcRawDirectory(File cdcRawDirectory) + { + if (!cdcRawDirectory.exists() || !cdcRawDirectory.isDirectory()) + { + LOGGER.debug("Skipping CdcRawDirectorySpaceCleaner: CDC directory does not exist: " + + cdcRawDirectory); + return; + } + + List<CdcRawSegmentFile> segmentFiles = Optional + .ofNullable( + cdcRawDirectory.listFiles(this::validSegmentFilter)) + .map(files -> Arrays.stream(files) + .map(CdcRawSegmentFile::new) + .filter( + CdcRawSegmentFile::indexExists) + .collect(Collectors.toList()) + ) + .orElseGet(List::of); + publishCdcStats(segmentFiles); + if (segmentFiles.size() < 2) + { + LOGGER.debug( + "Skipping cdc data cleaner routine cleanup: No cdc data or only one single cdc segment is found."); + return; + } + + long directorySize = FileUtils.directorySize(cdcRawDirectory); + long upperLimitBytes = + (long) (maxUsage() * cdcConfiguration.cdcRawDirectoryMaxPercentUsage()); + // Sort the files by segmentId to delete commit log segments in write order + // The latest file is the current active segment, but it could be created before the retention duration, e.g. slow data ingress + Collections.sort(segmentFiles); + long nowInMillis = timeProvider.currentTimeMillis(); + + // track the age of the oldest commit log segment to give indication of the time-window buffer available + cdcMetrics.oldestSegmentAge.metric.setValue( + (int) MILLISECONDS.toMinutes(nowInMillis - segmentFiles.get(0).lastModified())); + + if (directorySize > upperLimitBytes) + { + if (segmentFiles.get(0).segmentId > segmentFiles.get(1).segmentId) + { + LOGGER.error("Cdc segments sorted incorrectly {} before {}", + segmentFiles.get(0).segmentId, segmentFiles.get(1).segmentId); + } + + long criticalMillis = cdcConfiguration.cdcRawDirectoryCriticalBufferWindow().toMillis(); + long lowMillis = cdcConfiguration.cdcRawDirectoryLowBufferWindow().toMillis(); + + int i = 0; + while (i < segmentFiles.size() - 1 && directorySize > upperLimitBytes) Review Comment: a 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