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.StorageException;
20 import io.atomix.storage.journal.index.JournalIndex;
21 import io.atomix.utils.serializer.Namespace;
23 import java.io.IOException;
24 import java.nio.BufferOverflowException;
25 import java.nio.BufferUnderflowException;
26 import java.nio.ByteBuffer;
27 import java.nio.channels.FileChannel;
28 import java.util.zip.CRC32;
29 import java.util.zip.Checksum;
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 class FileChannelJournalSegmentWriter<E> implements JournalWriter<E> {
47 private final FileChannel channel;
48 private final JournalSegment segment;
49 private final int maxEntrySize;
50 private final JournalIndex index;
51 private final Namespace namespace;
52 private final ByteBuffer memory;
53 private final long firstIndex;
54 private Indexed<E> lastEntry;
56 FileChannelJournalSegmentWriter(
58 JournalSegment segment,
61 Namespace namespace) {
62 this.channel = channel;
63 this.segment = segment;
64 this.maxEntrySize = maxEntrySize;
66 this.memory = ByteBuffer.allocate((maxEntrySize + Integer.BYTES + Integer.BYTES) * 2);
68 this.namespace = namespace;
69 this.firstIndex = segment.index();
74 public void reset(long index) {
75 long nextIndex = firstIndex;
77 // Clear the buffer indexes.
79 channel.position(JournalSegmentDescriptor.BYTES);
80 memory.clear().flip();
82 // Record the current buffer position.
83 long position = channel.position();
85 // Read more bytes from the segment if necessary.
86 if (memory.remaining() < maxEntrySize) {
89 channel.position(position);
93 // Read the entry length.
95 int length = memory.getInt();
97 // If the length is non-zero, read the entry.
98 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
100 // Read the checksum of the entry.
101 final long checksum = memory.getInt() & 0xFFFFFFFFL;
103 // Compute the checksum for the entry bytes.
104 final Checksum crc32 = new CRC32();
105 crc32.update(memory.array(), memory.position(), length);
107 // If the stored checksum equals the computed checksum, return the entry.
108 if (checksum == crc32.getValue()) {
109 int limit = memory.limit();
110 memory.limit(memory.position() + length);
111 final E entry = namespace.deserialize(memory);
113 lastEntry = new Indexed<>(nextIndex, entry, length);
114 this.index.index(nextIndex, (int) position);
120 // Update the current position for indexing.
121 position = channel.position() + memory.position();
123 // Read more bytes from the segment if necessary.
124 if (memory.remaining() < maxEntrySize) {
125 channel.position(position);
127 channel.read(memory);
128 channel.position(position);
133 length = memory.getInt();
136 // Reset the buffer to the previous mark.
137 channel.position(channel.position() + memory.reset().position());
138 } catch (BufferUnderflowException e) {
140 channel.position(channel.position() + memory.reset().position());
141 } catch (IOException e2) {
142 throw new StorageException(e2);
144 } catch (IOException e) {
145 throw new StorageException(e);
150 public long getLastIndex() {
151 return lastEntry != null ? lastEntry.index() : segment.index() - 1;
155 public Indexed<E> getLastEntry() {
160 public long getNextIndex() {
161 if (lastEntry != null) {
162 return lastEntry.index() + 1;
169 * Returns the size of the underlying buffer.
171 * @return The size of the underlying buffer.
175 return channel.position();
176 } catch (IOException e) {
177 throw new StorageException(e);
182 * Returns a boolean indicating whether the segment is empty.
184 * @return Indicates whether the segment is empty.
186 public boolean isEmpty() {
187 return lastEntry == null;
191 * Returns a boolean indicating whether the segment is full.
193 * @return Indicates whether the segment is full.
195 public boolean isFull() {
196 return size() >= segment.descriptor().maxSegmentSize()
197 || getNextIndex() - firstIndex >= segment.descriptor().maxEntries();
201 * Returns the first index written to the segment.
203 public long firstIndex() {
208 @SuppressWarnings("unchecked")
209 public void append(Indexed<E> entry) {
210 final long nextIndex = getNextIndex();
212 // If the entry's index is greater than the next index in the segment, skip some entries.
213 if (entry.index() > nextIndex) {
214 throw new IndexOutOfBoundsException("Entry index is not sequential");
217 // If the entry's index is less than the next index, truncate the segment.
218 if (entry.index() < nextIndex) {
219 truncate(entry.index() - 1);
221 append(entry.entry());
225 @SuppressWarnings("unchecked")
226 public <T extends E> Indexed<T> append(T entry) {
227 // Store the entry index.
228 final long index = getNextIndex();
231 // Serialize the entry.
233 memory.position(Integer.BYTES + Integer.BYTES);
235 namespace.serialize(entry, memory);
236 } catch (KryoException e) {
237 throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
241 final int length = memory.limit() - (Integer.BYTES + Integer.BYTES);
243 // Ensure there's enough space left in the buffer to store the entry.
244 long position = channel.position();
245 if (segment.descriptor().maxSegmentSize() - position < length + Integer.BYTES + Integer.BYTES) {
246 throw new BufferOverflowException();
249 // If the entry length exceeds the maximum entry size then throw an exception.
250 if (length > maxEntrySize) {
251 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
254 // Compute the checksum for the entry.
255 final Checksum crc32 = new CRC32();
256 crc32.update(memory.array(), Integer.BYTES + Integer.BYTES, memory.limit() - (Integer.BYTES + Integer.BYTES));
257 final long checksum = crc32.getValue();
259 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
260 memory.putInt(0, length);
261 memory.putInt(Integer.BYTES, (int) checksum);
262 channel.write(memory);
264 // Update the last entry with the correct index/term/length.
265 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
266 this.lastEntry = indexedEntry;
267 this.index.index(index, (int) position);
268 return (Indexed<T>) indexedEntry;
269 } catch (IOException e) {
270 throw new StorageException(e);
275 public void commit(long index) {
280 @SuppressWarnings("unchecked")
281 public void truncate(long index) {
282 // If the index is greater than or equal to the last index, skip the truncate.
283 if (index >= getLastIndex()) {
287 // Reset the last entry.
291 // Truncate the index.
292 this.index.truncate(index);
294 if (index < segment.index()) {
295 channel.position(JournalSegmentDescriptor.BYTES);
296 channel.write(zero());
297 channel.position(JournalSegmentDescriptor.BYTES);
299 // Reset the writer to the given index.
302 // Zero entries after the given index.
303 long position = channel.position();
304 channel.write(zero());
305 channel.position(position);
307 } catch (IOException e) {
308 throw new StorageException(e);
313 * Returns a zeroed out byte buffer.
315 private ByteBuffer zero() {
317 for (int i = 0; i < memory.limit(); i++) {
318 memory.put(i, (byte) 0);
324 public void flush() {
326 if (channel.isOpen()) {
329 } catch (IOException e) {
330 throw new StorageException(e);
335 public void close() {