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.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 MappedJournalSegmentWriter<E> implements JournalWriter<E> {
44 private final MappedByteBuffer mappedBuffer;
45 private final ByteBuffer buffer;
46 private final JournalSegment<E> segment;
47 private final int maxEntrySize;
48 private final JournalIndex index;
49 private final JournalSerdes namespace;
50 private final long firstIndex;
51 private Indexed<E> lastEntry;
53 MappedJournalSegmentWriter(
54 MappedByteBuffer buffer,
55 JournalSegment<E> segment,
58 JournalSerdes namespace) {
59 this.mappedBuffer = buffer;
60 this.buffer = buffer.slice();
61 this.segment = segment;
62 this.maxEntrySize = maxEntrySize;
64 this.namespace = namespace;
65 this.firstIndex = segment.index();
70 * Returns the mapped buffer underlying the segment writer.
72 * @return the mapped buffer underlying the segment writer
74 MappedByteBuffer buffer() {
79 public void reset(long index) {
80 long nextIndex = firstIndex;
82 // Clear the buffer indexes.
83 buffer.position(JournalSegmentDescriptor.BYTES);
85 // Record the current buffer position.
86 int position = buffer.position();
88 // Read the entry length.
92 int length = buffer.getInt();
94 // If the length is non-zero, read the entry.
95 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
97 // Read the checksum of the entry.
98 final long checksum = buffer.getInt() & 0xFFFFFFFFL;
100 // Compute the checksum for the entry bytes.
101 final CRC32 crc32 = new CRC32();
102 ByteBuffer slice = buffer.slice();
106 // If the stored checksum equals the computed checksum, return the entry.
107 if (checksum == crc32.getValue()) {
109 final E entry = namespace.deserialize(slice);
110 lastEntry = new Indexed<>(nextIndex, entry, length);
111 this.index.index(nextIndex, position);
117 // Update the current position for indexing.
118 position = buffer.position() + length;
119 buffer.position(position);
122 length = buffer.getInt();
125 // Reset the buffer to the previous mark.
127 } catch (BufferUnderflowException e) {
133 public long getLastIndex() {
134 return lastEntry != null ? lastEntry.index() : segment.index() - 1;
138 public Indexed<E> getLastEntry() {
143 public long getNextIndex() {
144 if (lastEntry != null) {
145 return lastEntry.index() + 1;
152 * Returns the size of the underlying buffer.
154 * @return The size of the underlying buffer.
157 return buffer.position() + JournalSegmentDescriptor.BYTES;
161 * Returns a boolean indicating whether the segment is empty.
163 * @return Indicates whether the segment is empty.
165 public boolean isEmpty() {
166 return lastEntry == null;
170 public void append(Indexed<E> entry) {
171 final long nextIndex = getNextIndex();
173 // If the entry's index is greater than the next index in the segment, skip some entries.
174 if (entry.index() > nextIndex) {
175 throw new IndexOutOfBoundsException("Entry index is not sequential");
178 // If the entry's index is less than the next index, truncate the segment.
179 if (entry.index() < nextIndex) {
180 truncate(entry.index() - 1);
182 append(entry.entry());
186 @SuppressWarnings("unchecked")
187 public <T extends E> Indexed<T> append(T entry) {
188 // Store the entry index.
189 final long index = getNextIndex();
191 // Serialize the entry.
192 int position = buffer.position();
193 if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
194 throw new BufferOverflowException();
197 buffer.position(position + Integer.BYTES + Integer.BYTES);
200 namespace.serialize(entry, buffer);
201 } catch (KryoException e) {
202 throw new BufferOverflowException();
205 final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
207 // If the entry length exceeds the maximum entry size then throw an exception.
208 if (length > maxEntrySize) {
209 // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
210 buffer.position(position);
211 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
214 // Compute the checksum for the entry.
215 final CRC32 crc32 = new CRC32();
216 buffer.position(position + Integer.BYTES + Integer.BYTES);
217 ByteBuffer slice = buffer.slice();
220 final long checksum = crc32.getValue();
222 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
223 buffer.position(position);
224 buffer.putInt(length);
225 buffer.putInt((int) checksum);
226 buffer.position(position + Integer.BYTES + Integer.BYTES + length);
228 // Update the last entry with the correct index/term/length.
229 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
230 this.lastEntry = indexedEntry;
231 this.index.index(index, position);
232 return (Indexed<T>) indexedEntry;
236 public void commit(long index) {
241 public void truncate(long index) {
242 // If the index is greater than or equal to the last index, skip the truncate.
243 if (index >= getLastIndex()) {
247 // Reset the last entry.
250 // Truncate the index.
251 this.index.truncate(index);
253 if (index < segment.index()) {
254 buffer.position(JournalSegmentDescriptor.BYTES);
257 buffer.position(JournalSegmentDescriptor.BYTES);
259 // Reset the writer to the given index.
262 // Zero entries after the given index.
263 int position = buffer.position();
266 buffer.position(position);
271 public void flush() {
272 mappedBuffer.force();
276 public void close() {
279 BufferCleaner.freeBuffer(mappedBuffer);
280 } catch (IOException e) {
281 throw new StorageException(e);