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;
33 * The format of an entry in the log is as follows:
35 * <li>64-bit index</li>
36 * <li>8-bit boolean indicating whether a term change is contained in the entry</li>
37 * <li>64-bit optional term</li>
38 * <li>32-bit signed entry length, including the entry type ID</li>
39 * <li>8-bit signed entry type ID</li>
40 * <li>n-bit entry bytes</li>
43 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
45 final class FileChannelJournalSegmentWriter<E> extends JournalSegmentWriter<E> {
46 private static final ByteBuffer ZERO_ENTRY_HEADER = ByteBuffer.wrap(new byte[ENTRY_HEADER_BYTES]);
48 private final ByteBuffer memory;
49 private Indexed<E> lastEntry;
50 private long currentPosition;
52 FileChannelJournalSegmentWriter(
54 JournalSegment<E> segment,
57 JournalSerdes namespace) {
58 super(channel, segment, maxEntrySize, index, namespace);
59 memory = allocMemory(maxEntrySize);
63 FileChannelJournalSegmentWriter(JournalSegmentWriter<E> previous, int position) {
65 memory = allocMemory(maxEntrySize);
66 lastEntry = previous.getLastEntry();
67 currentPosition = position;
70 private static ByteBuffer allocMemory(int maxEntrySize) {
71 final var buf = ByteBuffer.allocate((maxEntrySize + ENTRY_HEADER_BYTES) * 2);
77 MappedByteBuffer buffer() {
82 MappedJournalSegmentWriter<E> toMapped() {
83 return new MappedJournalSegmentWriter<>(this, (int) currentPosition);
87 FileChannelJournalSegmentWriter<E> toFileChannel() {
92 void reset(long index) {
93 long nextIndex = firstIndex;
95 // Clear the buffer indexes.
96 currentPosition = JournalSegmentDescriptor.BYTES;
99 // Clear memory buffer and read fist chunk
100 channel.read(memory.clear(), JournalSegmentDescriptor.BYTES);
103 // Read the entry length.
104 int length = memory.getInt();
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 = memory.getInt() & 0xFFFFFFFFL;
112 // Slice off the entry's bytes
113 final ByteBuffer entryBytes = memory.slice();
114 entryBytes.limit(length);
116 // Compute the checksum for the entry bytes.
117 final CRC32 crc32 = new CRC32();
118 crc32.update(entryBytes);
120 // If the stored checksum does not equal the computed checksum, do not proceed further
121 if (checksum != crc32.getValue()) {
126 final E entry = namespace.deserialize(entryBytes);
127 lastEntry = new Indexed<>(nextIndex, entry, length);
128 this.index.index(nextIndex, (int) currentPosition);
131 // Update the current position for indexing.
132 currentPosition = currentPosition + ENTRY_HEADER_BYTES + length;
133 memory.position(memory.position() + length);
135 // Read more bytes from the segment if necessary.
136 if (memory.remaining() < maxEntrySize) {
137 channel.read(memory.compact());
141 length = memory.getInt();
143 } catch (BufferUnderflowException e) {
144 // No-op, position is only updated on success
145 } catch (IOException e) {
146 throw new StorageException(e);
151 Indexed<E> getLastEntry() {
156 @SuppressWarnings("unchecked")
157 <T extends E> Indexed<T> append(T entry) {
158 // Store the entry index.
159 final long index = getNextIndex();
161 // Serialize the entry.
163 namespace.serialize(entry, memory.clear().position(ENTRY_HEADER_BYTES));
164 } catch (KryoException e) {
165 throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
169 final int length = memory.limit() - ENTRY_HEADER_BYTES;
171 // Ensure there's enough space left in the buffer to store the entry.
172 if (maxSegmentSize - currentPosition < length + ENTRY_HEADER_BYTES) {
173 throw new BufferOverflowException();
176 // If the entry length exceeds the maximum entry size then throw an exception.
177 if (length > maxEntrySize) {
178 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
181 // Compute the checksum for the entry.
182 final CRC32 crc32 = new CRC32();
183 crc32.update(memory.array(), ENTRY_HEADER_BYTES, memory.limit() - ENTRY_HEADER_BYTES);
184 final long checksum = crc32.getValue();
186 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
187 memory.putInt(0, length).putInt(Integer.BYTES, (int) checksum);
189 channel.write(memory, currentPosition);
190 } catch (IOException e) {
191 throw new StorageException(e);
194 // Update the last entry with the correct index/term/length.
195 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
196 this.lastEntry = indexedEntry;
197 this.index.index(index, (int) currentPosition);
199 currentPosition = currentPosition + ENTRY_HEADER_BYTES + length;
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);
217 if (index < firstIndex) {
218 // Reset the writer to the first entry.
219 currentPosition = JournalSegmentDescriptor.BYTES;
221 // Reset the writer to the given index.
225 // Zero the entry header at current channel position.
226 channel.write(ZERO_ENTRY_HEADER.asReadOnlyBuffer(), currentPosition);
227 } catch (IOException e) {
228 throw new StorageException(e);
235 if (channel.isOpen()) {
238 } catch (IOException e) {
239 throw new StorageException(e);