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 com.esotericsoftware.kryo.KryoException;
20 import io.atomix.storage.journal.index.JournalIndex;
22 import java.io.IOException;
23 import java.nio.BufferOverflowException;
24 import java.nio.BufferUnderflowException;
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;
52 MappedJournalSegmentWriter(
54 JournalSegment<E> segment,
57 JournalSerdes namespace) {
58 super(channel, segment, maxEntrySize, index, namespace);
59 mappedBuffer = mapBuffer(channel, maxSegmentSize);
60 buffer = mappedBuffer.slice();
64 MappedJournalSegmentWriter(JournalSegmentWriter<E> previous, int position) {
66 mappedBuffer = mapBuffer(channel, maxSegmentSize);
67 buffer = mappedBuffer.slice().position(position);
68 lastEntry = previous.getLastEntry();
71 private static @NonNull MappedByteBuffer mapBuffer(FileChannel channel, int maxSegmentSize) {
73 return channel.map(FileChannel.MapMode.READ_WRITE, 0, maxSegmentSize);
74 } catch (IOException e) {
75 throw new StorageException(e);
80 @NonNull MappedByteBuffer buffer() {
85 MappedJournalSegmentWriter<E> toMapped() {
90 FileChannelJournalSegmentWriter<E> toFileChannel() {
91 final int position = buffer.position();
93 return new FileChannelJournalSegmentWriter<>(this, position);
97 void reset(long index) {
98 long nextIndex = firstIndex;
100 // Clear the buffer indexes.
101 buffer.position(JournalSegmentDescriptor.BYTES);
103 // Record the current buffer position.
104 int position = buffer.position();
106 // Read the entry length.
110 int length = buffer.getInt();
112 // If the length is non-zero, read the entry.
113 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
115 // Read the checksum of the entry.
116 final long checksum = buffer.getInt() & 0xFFFFFFFFL;
118 // Slice off the entry's bytes
119 final ByteBuffer entryBytes = buffer.slice();
120 entryBytes.limit(length);
122 // Compute the checksum for the entry bytes.
123 final CRC32 crc32 = new CRC32();
124 crc32.update(entryBytes);
126 // If the stored checksum does not equal the computed checksum, do not proceed further
127 if (checksum != crc32.getValue()) {
132 final E entry = namespace.deserialize(entryBytes);
133 lastEntry = new Indexed<>(nextIndex, entry, length);
134 this.index.index(nextIndex, position);
137 // Update the current position for indexing.
138 position = buffer.position() + length;
139 buffer.position(position);
141 length = buffer.mark().getInt();
144 // Reset the buffer to the previous mark.
146 } catch (BufferUnderflowException e) {
152 Indexed<E> getLastEntry() {
157 @SuppressWarnings("unchecked")
158 <T extends E> Indexed<T> append(T entry) {
159 // Store the entry index.
160 final long index = getNextIndex();
162 // Serialize the entry.
163 int position = buffer.position();
164 if (position + ENTRY_HEADER_BYTES > buffer.limit()) {
165 throw new BufferOverflowException();
168 buffer.position(position + ENTRY_HEADER_BYTES);
171 namespace.serialize(entry, buffer);
172 } catch (KryoException e) {
173 throw new BufferOverflowException();
176 final int length = buffer.position() - (position + ENTRY_HEADER_BYTES);
178 // If the entry length exceeds the maximum entry size then throw an exception.
179 if (length > maxEntrySize) {
180 // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
181 buffer.position(position);
182 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
185 // Compute the checksum for the entry.
186 final CRC32 crc32 = new CRC32();
187 buffer.position(position + ENTRY_HEADER_BYTES);
188 ByteBuffer slice = buffer.slice();
191 final long checksum = crc32.getValue();
193 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
194 buffer.position(position).putInt(length).putInt((int) checksum).position(position + ENTRY_HEADER_BYTES + length);
196 // Update the last entry with the correct index/term/length.
197 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
198 this.lastEntry = indexedEntry;
199 this.index.index(index, position);
200 return (Indexed<T>) indexedEntry;
204 void truncate(long index) {
205 // If the index is greater than or equal to the last index, skip the truncate.
206 if (index >= getLastIndex()) {
210 // Reset the last entry.
213 // Truncate the index.
214 this.index.truncate(index);
216 if (index < firstIndex) {
217 // Reset the writer to the first entry.
218 buffer.position(JournalSegmentDescriptor.BYTES);
220 // Reset the writer to the given index.
224 // Zero the entry header at current buffer position.
225 int position = buffer.position();
226 // Note: we issue a single putLong() instead of two putInt()s.
227 buffer.putLong(0).position(position);
232 mappedBuffer.force();
239 BufferCleaner.freeBuffer(mappedBuffer);
240 } catch (IOException e) {
241 throw new StorageException(e);