2 * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package io.atomix.storage.journal;
18 import static com.google.common.base.Preconditions.checkArgument;
19 import static com.google.common.base.Preconditions.checkState;
20 import static java.util.Objects.requireNonNull;
23 import java.io.IOException;
24 import java.util.Collection;
26 import java.util.TreeMap;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentNavigableMap;
29 import java.util.concurrent.ConcurrentSkipListMap;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
36 public final class SegmentedJournal<E> implements Journal<E> {
38 * Returns a new Raft log builder.
40 * @return A new Raft log builder.
42 public static <E> Builder<E> builder() {
43 return new Builder<>();
46 private static final Logger LOG = LoggerFactory.getLogger(SegmentedJournal.class);
47 private static final int SEGMENT_BUFFER_FACTOR = 3;
49 private final String name;
50 private final StorageLevel storageLevel;
51 private final File directory;
52 private final JournalSerializer<E> serializer;
53 private final int maxSegmentSize;
54 private final int maxEntrySize;
55 private final int maxEntriesPerSegment;
56 private final double indexDensity;
57 private final boolean flushOnCommit;
58 private final SegmentedJournalWriter<E> writer;
59 private volatile long commitIndex;
61 private final ConcurrentNavigableMap<Long, JournalSegment> segments = new ConcurrentSkipListMap<>();
62 private final Collection<SegmentedJournalReader<?>> readers = ConcurrentHashMap.newKeySet();
63 private JournalSegment currentSegment;
65 private volatile boolean open = true;
67 public SegmentedJournal(
69 StorageLevel storageLevel,
71 JournalSerdes namespace,
74 int maxEntriesPerSegment,
76 boolean flushOnCommit) {
77 this.name = requireNonNull(name, "name cannot be null");
78 this.storageLevel = requireNonNull(storageLevel, "storageLevel cannot be null");
79 this.directory = requireNonNull(directory, "directory cannot be null");
80 this.serializer = JournalSerializer.wrap(requireNonNull(namespace, "namespace cannot be null"));
81 this.maxSegmentSize = maxSegmentSize;
82 this.maxEntrySize = maxEntrySize;
83 this.maxEntriesPerSegment = maxEntriesPerSegment;
84 this.indexDensity = indexDensity;
85 this.flushOnCommit = flushOnCommit;
87 this.writer = new SegmentedJournalWriter<>(this);
91 * Returns the segment file name prefix.
93 * @return The segment file name prefix.
95 public String name() {
100 * Returns the storage directory.
102 * The storage directory is the directory to which all segments write files. Segment files for multiple logs may be
103 * stored in the storage directory, and files for each log instance will be identified by the {@code prefix} provided
104 * when the log is opened.
106 * @return The storage directory.
108 public File directory() {
113 * Returns the storage level.
115 * The storage level dictates how entries within individual journal segments should be stored.
117 * @return The storage level.
119 public StorageLevel storageLevel() {
124 * Returns the maximum journal segment size.
126 * The maximum segment size dictates the maximum size any segment in a segment may consume in bytes.
128 * @return The maximum segment size in bytes.
130 public int maxSegmentSize() {
131 return maxSegmentSize;
135 * Returns the maximum journal entry size.
137 * The maximum entry size dictates the maximum size any entry in the segment may consume in bytes.
139 * @return the maximum entry size in bytes
141 public int maxEntrySize() {
146 * Returns the maximum number of entries per segment.
148 * The maximum entries per segment dictates the maximum number of entries that are allowed to be stored in any segment
151 * @return The maximum number of entries per segment.
152 * @deprecated since 3.0.2
155 public int maxEntriesPerSegment() {
156 return maxEntriesPerSegment;
160 * Returns the collection of journal segments.
162 * @return the collection of journal segments
164 public Collection<JournalSegment> segments() {
165 return segments.values();
169 * Returns the collection of journal segments with indexes greater than the given index.
171 * @param index the starting index
172 * @return the journal segments starting with indexes greater than or equal to the given index
174 public Collection<JournalSegment> segments(long index) {
175 return segments.tailMap(index).values();
179 * Returns serializer instance.
181 * @return serializer instance
183 JournalSerializer<E> serializer() {
188 * Returns the total size of the journal.
190 * @return the total size of the journal
193 return segments.values().stream()
194 .mapToLong(JournalSegment::size)
199 public JournalWriter<E> writer() {
204 public JournalReader<E> openReader(long index) {
205 return openReader(index, JournalReader.Mode.ALL);
209 * Opens a new Raft log reader with the given reader mode.
211 * @param index The index from which to begin reading entries.
212 * @param mode The mode in which to read entries.
213 * @return The Raft log reader.
216 public JournalReader<E> openReader(long index, JournalReader.Mode mode) {
217 final var segment = getSegment(index);
218 final var reader = switch (mode) {
219 case ALL -> new SegmentedJournalReader<>(this, segment);
220 case COMMITS -> new CommitsSegmentJournalReader<>(this, segment);
223 // Forward reader to specified index
224 long next = reader.getNextIndex();
225 while (index > next && reader.tryAdvance()) {
226 next = reader.getNextIndex();
234 * Opens the segments.
236 private synchronized void open() {
237 // Load existing log segments from disk.
238 for (var segment : loadSegments()) {
239 segments.put(segment.firstIndex(), segment);
242 // If a segment doesn't already exist, create an initial segment starting at index 1.
243 if (!segments.isEmpty()) {
244 currentSegment = segments.lastEntry().getValue();
246 currentSegment = createSegment(1, 1);
247 segments.put(1L, currentSegment);
252 * Asserts that the manager is open.
254 * @throws IllegalStateException if the segment manager is not open
256 private void assertOpen() {
257 checkState(currentSegment != null, "journal not open");
261 * Asserts that enough disk space is available to allocate a new segment.
263 private void assertDiskSpace() {
264 if (directory().getUsableSpace() < maxSegmentSize() * SEGMENT_BUFFER_FACTOR) {
265 throw new StorageException.OutOfDiskSpace("Not enough space to allocate a new journal segment");
270 * Resets the current segment, creating a new segment if necessary.
272 private synchronized void resetCurrentSegment() {
273 final var lastSegment = getLastSegment();
274 if (lastSegment == null) {
275 currentSegment = createSegment(1, 1);
276 segments.put(1L, currentSegment);
278 currentSegment = lastSegment;
283 * Resets and returns the first segment in the journal.
285 * @param index the starting index of the journal
286 * @return the first segment
288 JournalSegment resetSegments(long index) {
291 // If the index already equals the first segment index, skip the reset.
292 final var firstSegment = getFirstSegment();
293 if (index == firstSegment.firstIndex()) {
297 segments.values().forEach(JournalSegment::delete);
300 currentSegment = createSegment(1, index);
301 segments.put(index, currentSegment);
302 return currentSegment;
306 * Returns the first segment in the log.
308 * @throws IllegalStateException if the segment manager is not open
310 JournalSegment getFirstSegment() {
312 Map.Entry<Long, JournalSegment> segment = segments.firstEntry();
313 return segment != null ? segment.getValue() : null;
317 * Returns the last segment in the log.
319 * @throws IllegalStateException if the segment manager is not open
321 JournalSegment getLastSegment() {
323 Map.Entry<Long, JournalSegment> segment = segments.lastEntry();
324 return segment != null ? segment.getValue() : null;
328 * Creates and returns the next segment.
330 * @return The next segment.
331 * @throws IllegalStateException if the segment manager is not open
333 synchronized JournalSegment getNextSegment() {
337 final var index = currentSegment.lastIndex() + 1;
338 final var lastSegment = getLastSegment();
339 currentSegment = createSegment(lastSegment != null ? lastSegment.file().descriptor().id() + 1 : 1, index);
340 segments.put(index, currentSegment);
341 return currentSegment;
345 * Returns the segment following the segment with the given ID.
347 * @param index The segment index with which to look up the next segment.
348 * @return The next segment for the given index.
350 JournalSegment getNextSegment(long index) {
351 Map.Entry<Long, JournalSegment> nextSegment = segments.higherEntry(index);
352 return nextSegment != null ? nextSegment.getValue() : null;
356 * Returns the segment for the given index.
358 * @param index The index for which to return the segment.
359 * @throws IllegalStateException if the segment manager is not open
361 synchronized JournalSegment getSegment(long index) {
363 // Check if the current segment contains the given index first in order to prevent an unnecessary map lookup.
364 if (currentSegment != null && index > currentSegment.firstIndex()) {
365 return currentSegment;
368 // If the index is in another segment, get the entry with the next lowest first index.
369 Map.Entry<Long, JournalSegment> segment = segments.floorEntry(index);
370 if (segment != null) {
371 return segment.getValue();
373 return getFirstSegment();
379 * @param segment The segment to remove.
381 synchronized void removeSegment(JournalSegment segment) {
382 segments.remove(segment.firstIndex());
384 resetCurrentSegment();
388 * Creates a new segment.
390 JournalSegment createSegment(long id, long index) {
391 final JournalSegmentFile file;
393 file = JournalSegmentFile.createNew(name, directory, JournalSegmentDescriptor.builder()
396 .withMaxSegmentSize(maxSegmentSize)
397 .withMaxEntries(maxEntriesPerSegment)
398 .withUpdated(System.currentTimeMillis())
400 } catch (IOException e) {
401 throw new StorageException(e);
404 final var segment = new JournalSegment(file, storageLevel, maxEntrySize, indexDensity);
405 LOG.debug("Created segment: {}", segment);
410 * Loads all segments from disk.
412 * @return A collection of segments for the log.
414 protected Collection<JournalSegment> loadSegments() {
415 // Ensure log directories are created.
418 final var segments = new TreeMap<Long, JournalSegment>();
420 // Iterate through all files in the log directory.
421 for (var file : directory.listFiles(File::isFile)) {
423 // If the file looks like a segment file, attempt to load the segment.
424 if (JournalSegmentFile.isSegmentFile(name, file)) {
425 final JournalSegmentFile segmentFile;
427 segmentFile = JournalSegmentFile.openExisting(file.toPath());
428 } catch (IOException e) {
429 throw new StorageException(e);
433 LOG.debug("Loaded disk segment: {} ({})", segmentFile.descriptor().id(), segmentFile.path());
435 // Add the segment to the segments list.
436 final var segment = new JournalSegment(segmentFile, storageLevel, maxEntrySize, indexDensity);
437 segments.put(segment.firstIndex(), segment);
441 // Verify that all the segments in the log align with one another.
442 JournalSegment previousSegment = null;
443 boolean corrupted = false;
444 final var iterator = segments.entrySet().iterator();
445 while (iterator.hasNext()) {
446 final var segment = iterator.next().getValue();
447 if (previousSegment != null && previousSegment.lastIndex() != segment.firstIndex() - 1) {
448 LOG.warn("Journal is inconsistent. {} is not aligned with prior segment {}", segment.file().path(),
449 previousSegment.file().path());
456 previousSegment = segment;
459 return segments.values();
463 * Resets journal readers to the given head.
465 * @param index The index at which to reset readers.
467 void resetHead(long index) {
468 for (var reader : readers) {
469 if (reader.getNextIndex() < index) {
476 * Resets journal readers to the given tail.
478 * @param index The index at which to reset readers.
480 void resetTail(long index) {
481 for (var reader : readers) {
482 if (reader.getNextIndex() >= index) {
488 void closeReader(SegmentedJournalReader<E> reader) {
489 readers.remove(reader);
493 public boolean isOpen() {
498 * Returns a boolean indicating whether a segment can be removed from the journal prior to the given index.
500 * @param index the index from which to remove segments
501 * @return indicates whether a segment can be removed from the journal
503 public boolean isCompactable(long index) {
504 Map.Entry<Long, JournalSegment> segmentEntry = segments.floorEntry(index);
505 return segmentEntry != null && segments.headMap(segmentEntry.getValue().firstIndex()).size() > 0;
509 * Returns the index of the last segment in the log.
511 * @param index the compaction index
512 * @return the starting index of the last segment in the log
514 public long getCompactableIndex(long index) {
515 Map.Entry<Long, JournalSegment> segmentEntry = segments.floorEntry(index);
516 return segmentEntry != null ? segmentEntry.getValue().firstIndex() : 0;
520 * Compacts the journal up to the given index.
522 * The semantics of compaction are not specified by this interface.
524 * @param index The index up to which to compact the journal.
526 public void compact(long index) {
527 final var segmentEntry = segments.floorEntry(index);
528 if (segmentEntry != null) {
529 final var compactSegments = segments.headMap(segmentEntry.getValue().firstIndex());
530 if (!compactSegments.isEmpty()) {
531 LOG.debug("{} - Compacting {} segment(s)", name, compactSegments.size());
532 compactSegments.values().forEach(JournalSegment::delete);
533 compactSegments.clear();
534 resetHead(segmentEntry.getValue().firstIndex());
540 public void close() {
541 segments.values().forEach(JournalSegment::close);
542 currentSegment = null;
547 * Returns whether {@code flushOnCommit} is enabled for the log.
549 * @return Indicates whether {@code flushOnCommit} is enabled for the log.
551 boolean isFlushOnCommit() {
552 return flushOnCommit;
556 * Commits entries up to the given index.
558 * @param index The index up to which to commit entries.
560 void setCommitIndex(long index) {
561 this.commitIndex = index;
565 * Returns the Raft log commit index.
567 * @return The Raft log commit index.
569 long getCommitIndex() {
576 public static final class Builder<E> {
577 private static final boolean DEFAULT_FLUSH_ON_COMMIT = false;
578 private static final String DEFAULT_NAME = "atomix";
579 private static final String DEFAULT_DIRECTORY = System.getProperty("user.dir");
580 private static final int DEFAULT_MAX_SEGMENT_SIZE = 1024 * 1024 * 32;
581 private static final int DEFAULT_MAX_ENTRY_SIZE = 1024 * 1024;
582 private static final int DEFAULT_MAX_ENTRIES_PER_SEGMENT = 1024 * 1024;
583 private static final double DEFAULT_INDEX_DENSITY = .005;
585 private String name = DEFAULT_NAME;
586 private StorageLevel storageLevel = StorageLevel.DISK;
587 private File directory = new File(DEFAULT_DIRECTORY);
588 private JournalSerdes namespace;
589 private int maxSegmentSize = DEFAULT_MAX_SEGMENT_SIZE;
590 private int maxEntrySize = DEFAULT_MAX_ENTRY_SIZE;
591 private int maxEntriesPerSegment = DEFAULT_MAX_ENTRIES_PER_SEGMENT;
592 private double indexDensity = DEFAULT_INDEX_DENSITY;
593 private boolean flushOnCommit = DEFAULT_FLUSH_ON_COMMIT;
600 * Sets the storage name.
602 * @param name The storage name.
603 * @return The storage builder.
605 public Builder<E> withName(String name) {
606 this.name = requireNonNull(name, "name cannot be null");
611 * Sets the log storage level, returning the builder for method chaining.
613 * The storage level indicates how individual entries should be persisted in the journal.
615 * @param storageLevel The log storage level.
616 * @return The storage builder.
618 public Builder<E> withStorageLevel(StorageLevel storageLevel) {
619 this.storageLevel = requireNonNull(storageLevel, "storageLevel cannot be null");
624 * Sets the log directory, returning the builder for method chaining.
626 * The log will write segment files into the provided directory.
628 * @param directory The log directory.
629 * @return The storage builder.
630 * @throws NullPointerException If the {@code directory} is {@code null}
632 public Builder<E> withDirectory(String directory) {
633 return withDirectory(new File(requireNonNull(directory, "directory cannot be null")));
637 * Sets the log directory, returning the builder for method chaining.
639 * The log will write segment files into the provided directory.
641 * @param directory The log directory.
642 * @return The storage builder.
643 * @throws NullPointerException If the {@code directory} is {@code null}
645 public Builder<E> withDirectory(File directory) {
646 this.directory = requireNonNull(directory, "directory cannot be null");
651 * Sets the journal namespace, returning the builder for method chaining.
653 * @param namespace The journal serializer.
654 * @return The journal builder.
656 public Builder<E> withNamespace(JournalSerdes namespace) {
657 this.namespace = requireNonNull(namespace, "namespace cannot be null");
662 * Sets the maximum segment size in bytes, returning the builder for method chaining.
664 * The maximum segment size dictates when logs should roll over to new segments. As entries are written to a segment
665 * of the log, once the size of the segment surpasses the configured maximum segment size, the log will create a new
666 * segment and append new entries to that segment.
668 * By default, the maximum segment size is {@code 1024 * 1024 * 32}.
670 * @param maxSegmentSize The maximum segment size in bytes.
671 * @return The storage builder.
672 * @throws IllegalArgumentException If the {@code maxSegmentSize} is not positive
674 public Builder<E> withMaxSegmentSize(int maxSegmentSize) {
675 checkArgument(maxSegmentSize > JournalSegmentDescriptor.BYTES,
676 "maxSegmentSize must be greater than " + JournalSegmentDescriptor.BYTES);
677 this.maxSegmentSize = maxSegmentSize;
682 * Sets the maximum entry size in bytes, returning the builder for method chaining.
684 * @param maxEntrySize the maximum entry size in bytes
685 * @return the storage builder
686 * @throws IllegalArgumentException if the {@code maxEntrySize} is not positive
688 public Builder<E> withMaxEntrySize(int maxEntrySize) {
689 checkArgument(maxEntrySize > 0, "maxEntrySize must be positive");
690 this.maxEntrySize = maxEntrySize;
695 * Sets the maximum number of allows entries per segment, returning the builder for method chaining.
697 * The maximum entry count dictates when logs should roll over to new segments. As entries are written to a segment
698 * of the log, if the entry count in that segment meets the configured maximum entry count, the log will create a
699 * new segment and append new entries to that segment.
701 * By default, the maximum entries per segment is {@code 1024 * 1024}.
703 * @param maxEntriesPerSegment The maximum number of entries allowed per segment.
704 * @return The storage builder.
705 * @throws IllegalArgumentException If the {@code maxEntriesPerSegment} not greater than the default max entries
707 * @deprecated since 3.0.2
710 public Builder<E> withMaxEntriesPerSegment(int maxEntriesPerSegment) {
711 checkArgument(maxEntriesPerSegment > 0, "max entries per segment must be positive");
712 checkArgument(maxEntriesPerSegment <= DEFAULT_MAX_ENTRIES_PER_SEGMENT,
713 "max entries per segment cannot be greater than " + DEFAULT_MAX_ENTRIES_PER_SEGMENT);
714 this.maxEntriesPerSegment = maxEntriesPerSegment;
719 * Sets the journal index density.
721 * The index density is the frequency at which the position of entries written to the journal will be recorded in an
722 * in-memory index for faster seeking.
724 * @param indexDensity the index density
725 * @return the journal builder
726 * @throws IllegalArgumentException if the density is not between 0 and 1
728 public Builder<E> withIndexDensity(double indexDensity) {
729 checkArgument(indexDensity > 0 && indexDensity < 1, "index density must be between 0 and 1");
730 this.indexDensity = indexDensity;
735 * Enables flushing buffers to disk when entries are committed to a segment, returning the builder for method
738 * When flush-on-commit is enabled, log entry buffers will be automatically flushed to disk each time an entry is
739 * committed in a given segment.
741 * @return The storage builder.
743 public Builder<E> withFlushOnCommit() {
744 return withFlushOnCommit(true);
748 * Sets whether to flush buffers to disk when entries are committed to a segment, returning the builder for method
751 * When flush-on-commit is enabled, log entry buffers will be automatically flushed to disk each time an entry is
752 * committed in a given segment.
754 * @param flushOnCommit Whether to flush buffers to disk when entries are committed to a segment.
755 * @return The storage builder.
757 public Builder<E> withFlushOnCommit(boolean flushOnCommit) {
758 this.flushOnCommit = flushOnCommit;
763 * Build the {@link SegmentedJournal}.
765 * @return A new {@link SegmentedJournal}.
767 public SegmentedJournal<E> build() {
768 return new SegmentedJournal<>(
775 maxEntriesPerSegment,