2 * Copyright 2017-present Open Networking Foundation
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 com.esotericsoftware.kryo.KryoException;
19 import io.atomix.storage.journal.index.JournalIndex;
21 import java.io.IOException;
22 import java.nio.BufferOverflowException;
23 import java.nio.BufferUnderflowException;
24 import java.nio.ByteBuffer;
25 import java.nio.MappedByteBuffer;
26 import java.nio.channels.FileChannel;
27 import java.util.zip.CRC32;
32 * The format of an entry in the log is as follows:
34 * <li>64-bit index</li>
35 * <li>8-bit boolean indicating whether a term change is contained in the entry</li>
36 * <li>64-bit optional term</li>
37 * <li>32-bit signed entry length, including the entry type ID</li>
38 * <li>8-bit signed entry type ID</li>
39 * <li>n-bit entry bytes</li>
42 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
44 final class FileChannelJournalSegmentWriter<E> extends JournalSegmentWriter<E> {
45 private static final ByteBuffer ZERO_ENTRY_HEADER = ByteBuffer.wrap(new byte[ENTRY_HEADER_BYTES]);
47 private final ByteBuffer memory;
48 private Indexed<E> lastEntry;
49 private long currentPosition;
51 FileChannelJournalSegmentWriter(
53 JournalSegment<E> segment,
56 JournalSerdes namespace) {
57 super(channel, segment, maxEntrySize, index, namespace);
58 memory = allocMemory(maxEntrySize);
62 FileChannelJournalSegmentWriter(JournalSegmentWriter<E> previous, int position) {
64 memory = allocMemory(maxEntrySize);
65 lastEntry = previous.getLastEntry();
66 currentPosition = position;
69 private static ByteBuffer allocMemory(int maxEntrySize) {
70 final var buf = ByteBuffer.allocate((maxEntrySize + ENTRY_HEADER_BYTES) * 2);
76 MappedByteBuffer buffer() {
81 MappedJournalSegmentWriter<E> toMapped() {
82 return new MappedJournalSegmentWriter<>(this, (int) currentPosition);
86 FileChannelJournalSegmentWriter<E> toFileChannel() {
91 void reset(long index) {
92 long nextIndex = firstIndex;
94 // Clear the buffer indexes.
95 currentPosition = JournalSegmentDescriptor.BYTES;
98 // Clear memory buffer and read fist chunk
99 channel.read(memory.clear(), JournalSegmentDescriptor.BYTES);
102 // Read the entry length.
103 int length = memory.getInt();
105 // If the length is non-zero, read the entry.
106 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
108 // Read the checksum of the entry.
109 final long checksum = memory.getInt() & 0xFFFFFFFFL;
111 // Slice off the entry's bytes
112 final ByteBuffer entryBytes = memory.slice();
113 entryBytes.limit(length);
115 // Compute the checksum for the entry bytes.
116 final CRC32 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 != crc32.getValue()) {
125 final E entry = namespace.deserialize(entryBytes);
126 lastEntry = new Indexed<>(nextIndex, entry, length);
127 this.index.index(nextIndex, (int) currentPosition);
130 // Update the current position for indexing.
131 currentPosition = currentPosition + ENTRY_HEADER_BYTES + length;
132 memory.position(memory.position() + length);
134 // Read more bytes from the segment if necessary.
135 if (memory.remaining() < maxEntrySize) {
136 channel.read(memory.compact());
140 length = memory.getInt();
142 } catch (BufferUnderflowException e) {
143 // No-op, position is only updated on success
144 } catch (IOException e) {
145 throw new StorageException(e);
150 Indexed<E> getLastEntry() {
155 @SuppressWarnings("unchecked")
156 <T extends E> Indexed<T> append(T entry) {
157 // Store the entry index.
158 final long index = getNextIndex();
160 // Serialize the entry.
162 namespace.serialize(entry, memory.clear().position(ENTRY_HEADER_BYTES));
163 } catch (KryoException e) {
164 throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
168 final int length = memory.limit() - ENTRY_HEADER_BYTES;
170 // Ensure there's enough space left in the buffer to store the entry.
171 if (maxSegmentSize - currentPosition < length + ENTRY_HEADER_BYTES) {
172 throw new BufferOverflowException();
175 // If the entry length exceeds the maximum entry size then throw an exception.
176 if (length > maxEntrySize) {
177 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
180 // Compute the checksum for the entry.
181 final CRC32 crc32 = new CRC32();
182 crc32.update(memory.array(), ENTRY_HEADER_BYTES, memory.limit() - ENTRY_HEADER_BYTES);
183 final long checksum = crc32.getValue();
185 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
186 memory.putInt(0, length).putInt(Integer.BYTES, (int) checksum);
188 channel.write(memory, currentPosition);
189 } catch (IOException e) {
190 throw new StorageException(e);
193 // Update the last entry with the correct index/term/length.
194 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
195 this.lastEntry = indexedEntry;
196 this.index.index(index, (int) currentPosition);
198 currentPosition = currentPosition + ENTRY_HEADER_BYTES + length;
199 return (Indexed<T>) indexedEntry;
203 void truncate(long index) {
204 // If the index is greater than or equal to the last index, skip the truncate.
205 if (index >= getLastIndex()) {
209 // Reset the last entry.
212 // Truncate the index.
213 this.index.truncate(index);
216 if (index < firstIndex) {
217 // Reset the writer to the first entry.
218 currentPosition = JournalSegmentDescriptor.BYTES;
220 // Reset the writer to the given index.
224 // Zero the entry header at current channel position.
225 channel.write(ZERO_ENTRY_HEADER.asReadOnlyBuffer(), currentPosition);
226 } catch (IOException e) {
227 throw new StorageException(e);
234 if (channel.isOpen()) {
237 } catch (IOException e) {
238 throw new StorageException(e);