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;
20 import io.atomix.utils.serializer.Namespace;
22 import java.io.IOException;
23 import java.nio.BufferOverflowException;
24 import java.nio.BufferUnderflowException;
25 import java.nio.ByteBuffer;
26 import java.nio.channels.FileChannel;
27 import java.util.zip.CRC32;
28 import java.util.zip.Checksum;
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 class FileChannelJournalSegmentWriter<E> implements JournalWriter<E> {
46 private final FileChannel channel;
47 private final JournalSegment<E> segment;
48 private final int maxEntrySize;
49 private final JournalIndex index;
50 private final Namespace namespace;
51 private final ByteBuffer memory;
52 private final long firstIndex;
53 private Indexed<E> lastEntry;
55 FileChannelJournalSegmentWriter(
57 JournalSegment<E> segment,
60 Namespace namespace) {
61 this.channel = channel;
62 this.segment = segment;
63 this.maxEntrySize = maxEntrySize;
65 this.memory = ByteBuffer.allocate((maxEntrySize + Integer.BYTES + Integer.BYTES) * 2);
67 this.namespace = namespace;
68 this.firstIndex = segment.index();
73 public void reset(long index) {
74 long nextIndex = firstIndex;
76 // Clear the buffer indexes.
78 channel.position(JournalSegmentDescriptor.BYTES);
79 memory.clear().flip();
81 // Record the current buffer position.
82 long position = channel.position();
84 // Read more bytes from the segment if necessary.
85 if (memory.remaining() < maxEntrySize) {
88 channel.position(position);
92 // Read the entry length.
94 int length = memory.getInt();
96 // If the length is non-zero, read the entry.
97 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
99 // Read the checksum of the entry.
100 final long checksum = memory.getInt() & 0xFFFFFFFFL;
102 // Compute the checksum for the entry bytes.
103 final Checksum crc32 = new CRC32();
104 crc32.update(memory.array(), memory.position(), length);
106 // If the stored checksum equals the computed checksum, return the entry.
107 if (checksum == crc32.getValue()) {
108 int limit = memory.limit();
109 memory.limit(memory.position() + length);
110 final E entry = namespace.deserialize(memory);
112 lastEntry = new Indexed<>(nextIndex, entry, length);
113 this.index.index(nextIndex, (int) position);
119 // Update the current position for indexing.
120 position = channel.position() + memory.position();
122 // Read more bytes from the segment if necessary.
123 if (memory.remaining() < maxEntrySize) {
124 channel.position(position);
126 channel.read(memory);
127 channel.position(position);
132 length = memory.getInt();
135 // Reset the buffer to the previous mark.
136 channel.position(channel.position() + memory.reset().position());
137 } catch (BufferUnderflowException e) {
139 channel.position(channel.position() + memory.reset().position());
140 } catch (IOException e2) {
141 throw new StorageException(e2);
143 } catch (IOException e) {
144 throw new StorageException(e);
149 public long getLastIndex() {
150 return lastEntry != null ? lastEntry.index() : segment.index() - 1;
154 public Indexed<E> getLastEntry() {
159 public long getNextIndex() {
160 if (lastEntry != null) {
161 return lastEntry.index() + 1;
168 * Returns the size of the underlying buffer.
170 * @return The size of the underlying buffer.
174 return channel.position();
175 } catch (IOException e) {
176 throw new StorageException(e);
181 * Returns a boolean indicating whether the segment is empty.
183 * @return Indicates whether the segment is empty.
185 public boolean isEmpty() {
186 return lastEntry == null;
190 * Returns a boolean indicating whether the segment is full.
192 * @return Indicates whether the segment is full.
194 public boolean isFull() {
195 return size() >= segment.descriptor().maxSegmentSize()
196 || getNextIndex() - firstIndex >= segment.descriptor().maxEntries();
200 * Returns the first index written to the segment.
202 public long firstIndex() {
207 public void append(Indexed<E> entry) {
208 final long nextIndex = getNextIndex();
210 // If the entry's index is greater than the next index in the segment, skip some entries.
211 if (entry.index() > nextIndex) {
212 throw new IndexOutOfBoundsException("Entry index is not sequential");
215 // If the entry's index is less than the next index, truncate the segment.
216 if (entry.index() < nextIndex) {
217 truncate(entry.index() - 1);
219 append(entry.entry());
223 @SuppressWarnings("unchecked")
224 public <T extends E> Indexed<T> append(T entry) {
225 // Store the entry index.
226 final long index = getNextIndex();
229 // Serialize the entry.
231 memory.position(Integer.BYTES + Integer.BYTES);
233 namespace.serialize(entry, memory);
234 } catch (KryoException e) {
235 throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
239 final int length = memory.limit() - (Integer.BYTES + Integer.BYTES);
241 // Ensure there's enough space left in the buffer to store the entry.
242 long position = channel.position();
243 if (segment.descriptor().maxSegmentSize() - position < length + Integer.BYTES + Integer.BYTES) {
244 throw new BufferOverflowException();
247 // If the entry length exceeds the maximum entry size then throw an exception.
248 if (length > maxEntrySize) {
249 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
252 // Compute the checksum for the entry.
253 final Checksum crc32 = new CRC32();
254 crc32.update(memory.array(), Integer.BYTES + Integer.BYTES, memory.limit() - (Integer.BYTES + Integer.BYTES));
255 final long checksum = crc32.getValue();
257 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
258 memory.putInt(0, length);
259 memory.putInt(Integer.BYTES, (int) checksum);
260 channel.write(memory);
262 // Update the last entry with the correct index/term/length.
263 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
264 this.lastEntry = indexedEntry;
265 this.index.index(index, (int) position);
266 return (Indexed<T>) indexedEntry;
267 } catch (IOException e) {
268 throw new StorageException(e);
273 public void commit(long index) {
278 public void truncate(long index) {
279 // If the index is greater than or equal to the last index, skip the truncate.
280 if (index >= getLastIndex()) {
284 // Reset the last entry.
288 // Truncate the index.
289 this.index.truncate(index);
291 if (index < segment.index()) {
292 channel.position(JournalSegmentDescriptor.BYTES);
293 channel.write(zero());
294 channel.position(JournalSegmentDescriptor.BYTES);
296 // Reset the writer to the given index.
299 // Zero entries after the given index.
300 long position = channel.position();
301 channel.write(zero());
302 channel.position(position);
304 } catch (IOException e) {
305 throw new StorageException(e);
310 * Returns a zeroed out byte buffer.
312 private ByteBuffer zero() {
314 for (int i = 0; i < memory.limit(); i++) {
315 memory.put(i, (byte) 0);
321 public void flush() {
323 if (channel.isOpen()) {
326 } catch (IOException e) {
327 throw new StorageException(e);
332 public void close() {