public void cleanupOldSnapshots()

in ratis-server/src/main/java/org/apache/ratis/statemachine/impl/SimpleStateMachineStorage.java [105:146]


  public void cleanupOldSnapshots(SnapshotRetentionPolicy snapshotRetentionPolicy) throws IOException {
    if (stateMachineDir == null) {
      return;
    }

    final int numSnapshotsRetained = Optional.ofNullable(snapshotRetentionPolicy)
        .map(SnapshotRetentionPolicy::getNumSnapshotsRetained)
        .orElse(SnapshotRetentionPolicy.DEFAULT_ALL_SNAPSHOTS_RETAINED);
    if (numSnapshotsRetained <= 0) {
      return;
    }

    final List<SingleFileSnapshotInfo> allSnapshotFiles = getSingleFileSnapshotInfos(stateMachineDir.toPath());

    if (allSnapshotFiles.size() > numSnapshotsRetained) {
      allSnapshotFiles.sort(Comparator.comparing(SingleFileSnapshotInfo::getIndex).reversed());
      allSnapshotFiles.subList(numSnapshotsRetained, allSnapshotFiles.size())
          .stream()
          .map(SingleFileSnapshotInfo::getFile)
          .map(FileInfo::getPath)
          .forEach(snapshotPath -> {
            LOG.info("Deleting old snapshot at {}", snapshotPath.toAbsolutePath());
            FileUtils.deletePathQuietly(snapshotPath);
          });
      // clean up the md5 files if the corresponding snapshot file does not exist
      try (DirectoryStream<Path> stream = Files.newDirectoryStream(stateMachineDir.toPath(),
          SNAPSHOT_MD5_FILTER)) {
        for (Path md5path : stream) {
          Path md5FileNamePath = md5path.getFileName();
          if (md5FileNamePath == null) {
            continue;
          }
          final String md5FileName = md5FileNamePath.toString();
          final File snapshotFile = new File(stateMachineDir,
              md5FileName.substring(0, md5FileName.length() - MD5_SUFFIX.length()));
          if (!snapshotFile.exists()) {
            FileUtils.deletePathQuietly(md5path);
          }
        }
      }
    }
  }