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;
31 * The format of an entry in the log is as follows:
33 * <li>64-bit index</li>
34 * <li>8-bit boolean indicating whether a term change is contained in the entry</li>
35 * <li>64-bit optional term</li>
36 * <li>32-bit signed entry length, including the entry type ID</li>
37 * <li>8-bit signed entry type ID</li>
38 * <li>n-bit entry bytes</li>
41 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
43 class FileChannelJournalSegmentWriter<E> implements JournalWriter<E> {
44 private static final ByteBuffer ZERO_ENTRY_HEADER = ByteBuffer.wrap(new byte[Integer.BYTES + Integer.BYTES]);
46 private final FileChannel channel;
47 private final JournalSegment<E> segment;
48 private final int maxEntrySize;
49 private final JournalIndex index;
50 private final JournalSerdes namespace;
51 private final ByteBuffer memory;
52 private final long firstIndex;
53 private Indexed<E> lastEntry;
55 FileChannelJournalSegmentWriter(
57 JournalSegment<E> segment,
60 JournalSerdes 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);
80 // Record the current buffer position.
81 long position = channel.position();
83 // Clear memory buffer and read fist chunk
85 channel.read(memory, position);
88 // Read the entry length.
89 int length = memory.getInt();
91 // If the length is non-zero, read the entry.
92 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
94 // Read the checksum of the entry.
95 final long checksum = memory.getInt() & 0xFFFFFFFFL;
97 // Slice off the entry's bytes
98 final ByteBuffer entryBytes = memory.slice();
99 entryBytes.limit(length);
101 // Compute the checksum for the entry bytes.
102 final CRC32 crc32 = new CRC32();
103 crc32.update(entryBytes);
105 // If the stored checksum does not equal the computed checksum, do not proceed further
106 if (checksum != crc32.getValue()) {
111 final E entry = namespace.deserialize(entryBytes);
112 lastEntry = new Indexed<>(nextIndex, entry, length);
113 this.index.index(nextIndex, (int) position);
116 // Update the current position for indexing.
117 position = position + Integer.BYTES + Integer.BYTES + length;
118 channel.position(position);
119 memory.position(memory.position() + length);
121 // Read more bytes from the segment if necessary.
122 if (memory.remaining() < maxEntrySize) {
124 channel.read(memory, position);
128 length = memory.getInt();
130 } catch (BufferUnderflowException e) {
131 // No-op, position is only updated on success
132 } catch (IOException e) {
133 throw new StorageException(e);
138 public long getLastIndex() {
139 return lastEntry != null ? lastEntry.index() : segment.index() - 1;
143 public Indexed<E> getLastEntry() {
148 public long getNextIndex() {
149 if (lastEntry != null) {
150 return lastEntry.index() + 1;
157 public void append(Indexed<E> entry) {
158 final long nextIndex = getNextIndex();
160 // If the entry's index is greater than the next index in the segment, skip some entries.
161 if (entry.index() > nextIndex) {
162 throw new IndexOutOfBoundsException("Entry index is not sequential");
165 // If the entry's index is less than the next index, truncate the segment.
166 if (entry.index() < nextIndex) {
167 truncate(entry.index() - 1);
169 append(entry.entry());
173 @SuppressWarnings("unchecked")
174 public <T extends E> Indexed<T> append(T entry) {
175 // Store the entry index.
176 final long index = getNextIndex();
179 // Serialize the entry.
181 memory.position(Integer.BYTES + Integer.BYTES);
183 namespace.serialize(entry, memory);
184 } catch (KryoException e) {
185 throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
189 final int length = memory.limit() - (Integer.BYTES + Integer.BYTES);
191 // Ensure there's enough space left in the buffer to store the entry.
192 long position = channel.position();
193 if (segment.descriptor().maxSegmentSize() - position < length + Integer.BYTES + Integer.BYTES) {
194 throw new BufferOverflowException();
197 // If the entry length exceeds the maximum entry size then throw an exception.
198 if (length > maxEntrySize) {
199 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
202 // Compute the checksum for the entry.
203 final CRC32 crc32 = new CRC32();
204 crc32.update(memory.array(), Integer.BYTES + Integer.BYTES, memory.limit() - (Integer.BYTES + Integer.BYTES));
205 final long checksum = crc32.getValue();
207 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
208 memory.putInt(0, length);
209 memory.putInt(Integer.BYTES, (int) checksum);
210 channel.write(memory);
212 // Update the last entry with the correct index/term/length.
213 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
214 this.lastEntry = indexedEntry;
215 this.index.index(index, (int) position);
216 return (Indexed<T>) indexedEntry;
217 } catch (IOException e) {
218 throw new StorageException(e);
223 public void commit(long index) {
228 public void truncate(long index) {
229 // If the index is greater than or equal to the last index, skip the truncate.
230 if (index >= getLastIndex()) {
234 // Reset the last entry.
237 // Truncate the index.
238 this.index.truncate(index);
241 if (index < segment.index()) {
242 // Reset the writer to the first entry.
243 channel.position(JournalSegmentDescriptor.BYTES);
245 // Reset the writer to the given index.
249 // Zero the entry header at current channel position.
250 channel.write(ZERO_ENTRY_HEADER.asReadOnlyBuffer(), channel.position());
251 } catch (IOException e) {
252 throw new StorageException(e);
257 public void flush() {
259 if (channel.isOpen()) {
262 } catch (IOException e) {
263 throw new StorageException(e);
268 public void close() {