2 * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
3 * Copyright (c) 2024 PANTHEON.tech, s.r.o.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package io.atomix.storage.journal;
19 import static io.atomix.storage.journal.SegmentEntry.HEADER_BYTES;
21 import com.esotericsoftware.kryo.KryoException;
22 import io.atomix.storage.journal.index.JournalIndex;
23 import java.io.IOException;
24 import java.nio.BufferOverflowException;
25 import java.nio.ByteBuffer;
26 import java.nio.MappedByteBuffer;
27 import java.nio.channels.FileChannel;
28 import java.util.zip.CRC32;
29 import org.eclipse.jdt.annotation.NonNull;
34 * The format of an entry in the log is as follows:
36 * <li>64-bit index</li>
37 * <li>8-bit boolean indicating whether a term change is contained in the entry</li>
38 * <li>64-bit optional term</li>
39 * <li>32-bit signed entry length, including the entry type ID</li>
40 * <li>8-bit signed entry type ID</li>
41 * <li>n-bit entry bytes</li>
44 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
46 final class MappedJournalSegmentWriter<E> extends JournalSegmentWriter<E> {
47 private final @NonNull MappedByteBuffer mappedBuffer;
48 private final ByteBuffer buffer;
50 private Indexed<E> lastEntry;
51 private int currentPosition;
53 MappedJournalSegmentWriter(
54 final FileChannel channel,
55 final JournalSegment<E> segment,
56 final int maxEntrySize,
57 final JournalIndex index,
58 final JournalSerdes namespace) {
59 super(channel, segment, maxEntrySize, index, namespace);
60 mappedBuffer = mapBuffer(channel, maxSegmentSize);
61 buffer = mappedBuffer.slice();
65 MappedJournalSegmentWriter(final JournalSegmentWriter<E> previous, final int position) {
67 mappedBuffer = mapBuffer(channel, maxSegmentSize);
68 buffer = mappedBuffer.slice();
69 currentPosition = position;
70 lastEntry = previous.getLastEntry();
73 private static @NonNull MappedByteBuffer mapBuffer(final FileChannel channel, final int maxSegmentSize) {
75 return channel.map(FileChannel.MapMode.READ_WRITE, 0, maxSegmentSize);
76 } catch (IOException e) {
77 throw new StorageException(e);
82 @NonNull MappedByteBuffer buffer() {
87 MappedJournalSegmentWriter<E> toMapped() {
92 DiskJournalSegmentWriter<E> toFileChannel() {
94 return new DiskJournalSegmentWriter<>(this, currentPosition);
98 void reset(final long index) {
99 long nextIndex = firstIndex;
101 // Clear the buffer indexes.
102 currentPosition = JournalSegmentDescriptor.BYTES;
104 int length = buffer.getInt(currentPosition);
106 // If the length is non-zero, read the entry.
107 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
109 // Read the checksum of the entry.
110 final long checksum = buffer.getInt(currentPosition + Integer.BYTES);
112 // Slice off the entry's bytes
113 final var entryBytes = buffer.slice(currentPosition + SegmentEntry.HEADER_BYTES, length);
115 // Compute the checksum for the entry bytes.
116 final var crc32 = new CRC32();
117 crc32.update(entryBytes);
119 // If the stored checksum does not equal the computed checksum, do not proceed further
120 if (checksum != (int) crc32.getValue()) {
125 final E entry = namespace.deserialize(entryBytes);
126 lastEntry = new Indexed<>(nextIndex, entry, length);
127 this.index.index(nextIndex, currentPosition);
130 // Update the current position for indexing.
131 currentPosition = currentPosition + SegmentEntry.HEADER_BYTES + length;
133 if (currentPosition + SegmentEntry.HEADER_BYTES >= maxSegmentSize) {
136 length = buffer.getInt(currentPosition);
141 Indexed<E> getLastEntry() {
146 @SuppressWarnings("unchecked")
147 <T extends E> Indexed<T> append(final T entry) {
148 // Store the entry index.
149 final long index = getNextIndex();
151 // Serialize the entry.
152 final int bodyPosition = currentPosition + HEADER_BYTES;
153 final int avail = maxSegmentSize - bodyPosition;
155 throw new BufferOverflowException();
158 final var entryBytes = buffer.slice(bodyPosition, Math.min(avail, maxEntrySize));
160 namespace.serialize(entry, entryBytes);
161 } catch (KryoException e) {
162 if (entryBytes.capacity() != maxEntrySize) {
163 // We have not provided enough capacity, signal to roll to next segment
164 throw new BufferOverflowException();
167 // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
168 throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
171 final int length = entryBytes.position();
173 // Compute the checksum for the entry.
174 final var crc32 = new CRC32();
175 crc32.update(entryBytes.flip());
177 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
178 buffer.putInt(currentPosition, length).putInt(currentPosition + Integer.BYTES, (int) crc32.getValue());
180 // Update the last entry with the correct index/term/length.
181 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
182 lastEntry = indexedEntry;
183 this.index.index(index, currentPosition);
185 currentPosition = currentPosition + HEADER_BYTES + length;
186 return (Indexed<T>) indexedEntry;
190 void truncate(final long index) {
191 // If the index is greater than or equal to the last index, skip the truncate.
192 if (index >= getLastIndex()) {
196 // Reset the last entry.
199 // Truncate the index.
200 this.index.truncate(index);
202 if (index < firstIndex) {
203 // Reset the writer to the first entry.
204 currentPosition = JournalSegmentDescriptor.BYTES;
206 // Reset the writer to the given index.
210 // Zero the entry header at current buffer position.
211 // Note: we issue a single putLong() instead of two putInt()s.
212 buffer.putLong(currentPosition, 0L);
217 mappedBuffer.force();
224 BufferCleaner.freeBuffer(mappedBuffer);
225 } catch (IOException e) {
226 throw new StorageException(e);