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.channels.FileChannel;
26 import java.util.zip.CRC32;
27 import java.util.zip.Checksum;
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 class FileChannelJournalSegmentWriter<E> implements JournalWriter<E> {
45 private final FileChannel channel;
46 private final JournalSegment<E> segment;
47 private final int maxEntrySize;
48 private final JournalIndex index;
49 private final JournalSerdes namespace;
50 private final ByteBuffer memory;
51 private final long firstIndex;
52 private Indexed<E> lastEntry;
54 FileChannelJournalSegmentWriter(
56 JournalSegment<E> segment,
59 JournalSerdes namespace) {
60 this.channel = channel;
61 this.segment = segment;
62 this.maxEntrySize = maxEntrySize;
64 this.memory = ByteBuffer.allocate((maxEntrySize + Integer.BYTES + Integer.BYTES) * 2);
66 this.namespace = namespace;
67 this.firstIndex = segment.index();
72 public void reset(long index) {
73 long nextIndex = firstIndex;
75 // Clear the buffer indexes.
77 channel.position(JournalSegmentDescriptor.BYTES);
78 memory.clear().flip();
80 // Record the current buffer position.
81 long position = channel.position();
83 // Read more bytes from the segment if necessary.
84 if (memory.remaining() < maxEntrySize) {
87 channel.position(position);
91 // Read the entry length.
93 int length = memory.getInt();
95 // If the length is non-zero, read the entry.
96 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
98 // Read the checksum of the entry.
99 final long checksum = memory.getInt() & 0xFFFFFFFFL;
101 // Compute the checksum for the entry bytes.
102 final Checksum crc32 = new CRC32();
103 crc32.update(memory.array(), memory.position(), length);
105 // If the stored checksum equals the computed checksum, return the entry.
106 if (checksum == crc32.getValue()) {
107 int limit = memory.limit();
108 memory.limit(memory.position() + length);
109 final E entry = namespace.deserialize(memory);
111 lastEntry = new Indexed<>(nextIndex, entry, length);
112 this.index.index(nextIndex, (int) position);
118 // Update the current position for indexing.
119 position = channel.position() + memory.position();
121 // Read more bytes from the segment if necessary.
122 if (memory.remaining() < maxEntrySize) {
123 channel.position(position);
125 channel.read(memory);
126 channel.position(position);
131 length = memory.getInt();
134 // Reset the buffer to the previous mark.
135 channel.position(channel.position() + memory.reset().position());
136 } catch (BufferUnderflowException e) {
138 channel.position(channel.position() + memory.reset().position());
139 } catch (IOException e2) {
140 throw new StorageException(e2);
142 } catch (IOException e) {
143 throw new StorageException(e);
148 public long getLastIndex() {
149 return lastEntry != null ? lastEntry.index() : segment.index() - 1;
153 public Indexed<E> getLastEntry() {
158 public long getNextIndex() {
159 if (lastEntry != null) {
160 return lastEntry.index() + 1;
167 public void append(Indexed<E> entry) {
168 final long nextIndex = getNextIndex();
170 // If the entry's index is greater than the next index in the segment, skip some entries.
171 if (entry.index() > nextIndex) {
172 throw new IndexOutOfBoundsException("Entry index is not sequential");
175 // If the entry's index is less than the next index, truncate the segment.
176 if (entry.index() < nextIndex) {
177 truncate(entry.index() - 1);
179 append(entry.entry());
183 @SuppressWarnings("unchecked")
184 public <T extends E> Indexed<T> append(T entry) {
185 // Store the entry index.
186 final long index = getNextIndex();
189 // Serialize the entry.
191 memory.position(Integer.BYTES + Integer.BYTES);
193 namespace.serialize(entry, memory);
194 } catch (KryoException e) {
195 throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
199 final int length = memory.limit() - (Integer.BYTES + Integer.BYTES);
201 // Ensure there's enough space left in the buffer to store the entry.
202 long position = channel.position();
203 if (segment.descriptor().maxSegmentSize() - position < length + Integer.BYTES + Integer.BYTES) {
204 throw new BufferOverflowException();
207 // If the entry length exceeds the maximum entry size then throw an exception.
208 if (length > maxEntrySize) {
209 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
212 // Compute the checksum for the entry.
213 final Checksum crc32 = new CRC32();
214 crc32.update(memory.array(), Integer.BYTES + Integer.BYTES, memory.limit() - (Integer.BYTES + Integer.BYTES));
215 final long checksum = crc32.getValue();
217 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
218 memory.putInt(0, length);
219 memory.putInt(Integer.BYTES, (int) checksum);
220 channel.write(memory);
222 // Update the last entry with the correct index/term/length.
223 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
224 this.lastEntry = indexedEntry;
225 this.index.index(index, (int) position);
226 return (Indexed<T>) indexedEntry;
227 } catch (IOException e) {
228 throw new StorageException(e);
233 public void commit(long index) {
238 public void truncate(long index) {
239 // If the index is greater than or equal to the last index, skip the truncate.
240 if (index >= getLastIndex()) {
244 // Reset the last entry.
247 // Truncate the index.
248 this.index.truncate(index);
251 if (index < segment.index()) {
252 // Reset the writer to the first entry.
253 channel.position(JournalSegmentDescriptor.BYTES);
255 // Reset the writer to the given index.
259 // Zero entries at the current position.
260 // FIXME: This is quite inefficient, we essentially want to zero-out part of the file, but it is not quite clear
261 // how much: this overwrites at least two entries. I believe we should be able to get by with wiping the
262 // header of the current entry.
264 for (int i = 0; i < memory.limit(); i++) {
265 memory.put(i, (byte) 0);
267 channel.write(memory, channel.position());
268 } catch (IOException e) {
269 throw new StorageException(e);
274 public void flush() {
276 if (channel.isOpen()) {
279 } catch (IOException e) {
280 throw new StorageException(e);
285 public void close() {