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[Integer.BYTES + Integer.BYTES]);
47 private final FileChannel channel;
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(segment, maxEntrySize, index, namespace);
59 this.channel = channel;
60 this.memory = ByteBuffer.allocate((maxEntrySize + Integer.BYTES + Integer.BYTES) * 2);
66 MappedByteBuffer buffer() {
71 public void reset(long index) {
72 long nextIndex = firstIndex;
74 // Clear the buffer indexes.
75 currentPosition = JournalSegmentDescriptor.BYTES;
78 // Clear memory buffer and read fist chunk
80 channel.read(memory, JournalSegmentDescriptor.BYTES);
83 // Read the entry length.
84 int length = memory.getInt();
86 // If the length is non-zero, read the entry.
87 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
89 // Read the checksum of the entry.
90 final long checksum = memory.getInt() & 0xFFFFFFFFL;
92 // Slice off the entry's bytes
93 final ByteBuffer entryBytes = memory.slice();
94 entryBytes.limit(length);
96 // Compute the checksum for the entry bytes.
97 final CRC32 crc32 = new CRC32();
98 crc32.update(entryBytes);
100 // If the stored checksum does not equal the computed checksum, do not proceed further
101 if (checksum != crc32.getValue()) {
106 final E entry = namespace.deserialize(entryBytes);
107 lastEntry = new Indexed<>(nextIndex, entry, length);
108 this.index.index(nextIndex, (int) currentPosition);
111 // Update the current position for indexing.
112 currentPosition = currentPosition + Integer.BYTES + Integer.BYTES + length;
113 memory.position(memory.position() + length);
115 // Read more bytes from the segment if necessary.
116 if (memory.remaining() < maxEntrySize) {
118 channel.read(memory, currentPosition);
122 length = memory.getInt();
124 } catch (BufferUnderflowException e) {
125 // No-op, position is only updated on success
126 } catch (IOException e) {
127 throw new StorageException(e);
132 public long getLastIndex() {
133 return lastEntry != null ? lastEntry.index() : segment.index() - 1;
137 public Indexed<E> getLastEntry() {
142 public long getNextIndex() {
143 if (lastEntry != null) {
144 return lastEntry.index() + 1;
151 public void append(Indexed<E> entry) {
152 final long nextIndex = getNextIndex();
154 // If the entry's index is greater than the next index in the segment, skip some entries.
155 if (entry.index() > nextIndex) {
156 throw new IndexOutOfBoundsException("Entry index is not sequential");
159 // If the entry's index is less than the next index, truncate the segment.
160 if (entry.index() < nextIndex) {
161 truncate(entry.index() - 1);
163 append(entry.entry());
167 @SuppressWarnings("unchecked")
168 public <T extends E> Indexed<T> append(T entry) {
169 // Store the entry index.
170 final long index = getNextIndex();
172 // Serialize the entry.
174 memory.position(Integer.BYTES + Integer.BYTES);
176 namespace.serialize(entry, memory);
177 } catch (KryoException e) {
178 throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
182 final int length = memory.limit() - (Integer.BYTES + Integer.BYTES);
184 // Ensure there's enough space left in the buffer to store the entry.
185 if (segment.descriptor().maxSegmentSize() - currentPosition < length + Integer.BYTES + Integer.BYTES) {
186 throw new BufferOverflowException();
189 // If the entry length exceeds the maximum entry size then throw an exception.
190 if (length > maxEntrySize) {
191 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
194 // Compute the checksum for the entry.
195 final CRC32 crc32 = new CRC32();
196 crc32.update(memory.array(), Integer.BYTES + Integer.BYTES, memory.limit() - (Integer.BYTES + Integer.BYTES));
197 final long checksum = crc32.getValue();
199 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
200 memory.putInt(0, length);
201 memory.putInt(Integer.BYTES, (int) checksum);
203 channel.write(memory, currentPosition);
204 } catch (IOException e) {
205 throw new StorageException(e);
208 // Update the last entry with the correct index/term/length.
209 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
210 this.lastEntry = indexedEntry;
211 this.index.index(index, (int) currentPosition);
213 currentPosition = currentPosition + Integer.BYTES + Integer.BYTES + length;
214 return (Indexed<T>) indexedEntry;
218 public void truncate(long index) {
219 // If the index is greater than or equal to the last index, skip the truncate.
220 if (index >= getLastIndex()) {
224 // Reset the last entry.
227 // Truncate the index.
228 this.index.truncate(index);
231 if (index < segment.index()) {
232 // Reset the writer to the first entry.
233 currentPosition = JournalSegmentDescriptor.BYTES;
235 // Reset the writer to the given index.
239 // Zero the entry header at current channel position.
240 channel.write(ZERO_ENTRY_HEADER.asReadOnlyBuffer(), currentPosition);
241 } catch (IOException e) {
242 throw new StorageException(e);
247 public void flush() {
249 if (channel.isOpen()) {
252 } catch (IOException e) {
253 throw new StorageException(e);
258 public void close() {