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.MappedByteBuffer;
27 import java.util.zip.CRC32;
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 MappedJournalSegmentWriter<E> implements JournalWriter<E> {
45 private final MappedByteBuffer mappedBuffer;
46 private final ByteBuffer buffer;
47 private final JournalSegment<E> segment;
48 private final int maxEntrySize;
49 private final JournalIndex index;
50 private final Namespace namespace;
51 private final long firstIndex;
52 private Indexed<E> lastEntry;
54 MappedJournalSegmentWriter(
55 MappedByteBuffer buffer,
56 JournalSegment<E> segment,
59 Namespace namespace) {
60 this.mappedBuffer = buffer;
61 this.buffer = buffer.slice();
62 this.segment = segment;
63 this.maxEntrySize = maxEntrySize;
65 this.namespace = namespace;
66 this.firstIndex = segment.index();
71 * Returns the mapped buffer underlying the segment writer.
73 * @return the mapped buffer underlying the segment writer
75 MappedByteBuffer buffer() {
80 public void reset(long index) {
81 long nextIndex = firstIndex;
83 // Clear the buffer indexes.
84 buffer.position(JournalSegmentDescriptor.BYTES);
86 // Record the current buffer position.
87 int position = buffer.position();
89 // Read the entry length.
93 int length = buffer.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 = buffer.getInt() & 0xFFFFFFFFL;
101 // Compute the checksum for the entry bytes.
102 final CRC32 crc32 = new CRC32();
103 ByteBuffer slice = buffer.slice();
107 // If the stored checksum equals the computed checksum, return the entry.
108 if (checksum == crc32.getValue()) {
110 final E entry = namespace.deserialize(slice);
111 lastEntry = new Indexed<>(nextIndex, entry, length);
112 this.index.index(nextIndex, position);
118 // Update the current position for indexing.
119 position = buffer.position() + length;
120 buffer.position(position);
123 length = buffer.getInt();
126 // Reset the buffer to the previous mark.
128 } catch (BufferUnderflowException e) {
134 public long getLastIndex() {
135 return lastEntry != null ? lastEntry.index() : segment.index() - 1;
139 public Indexed<E> getLastEntry() {
144 public long getNextIndex() {
145 if (lastEntry != null) {
146 return lastEntry.index() + 1;
153 * Returns the size of the underlying buffer.
155 * @return The size of the underlying buffer.
158 return buffer.position() + JournalSegmentDescriptor.BYTES;
162 * Returns a boolean indicating whether the segment is empty.
164 * @return Indicates whether the segment is empty.
166 public boolean isEmpty() {
167 return lastEntry == null;
171 public void append(Indexed<E> entry) {
172 final long nextIndex = getNextIndex();
174 // If the entry's index is greater than the next index in the segment, skip some entries.
175 if (entry.index() > nextIndex) {
176 throw new IndexOutOfBoundsException("Entry index is not sequential");
179 // If the entry's index is less than the next index, truncate the segment.
180 if (entry.index() < nextIndex) {
181 truncate(entry.index() - 1);
183 append(entry.entry());
187 @SuppressWarnings("unchecked")
188 public <T extends E> Indexed<T> append(T entry) {
189 // Store the entry index.
190 final long index = getNextIndex();
192 // Serialize the entry.
193 int position = buffer.position();
194 if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
195 throw new BufferOverflowException();
198 buffer.position(position + Integer.BYTES + Integer.BYTES);
201 namespace.serialize(entry, buffer);
202 } catch (KryoException e) {
203 throw new BufferOverflowException();
206 final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
208 // If the entry length exceeds the maximum entry size then throw an exception.
209 if (length > maxEntrySize) {
210 // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
211 buffer.position(position);
212 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
215 // Compute the checksum for the entry.
216 final CRC32 crc32 = new CRC32();
217 buffer.position(position + Integer.BYTES + Integer.BYTES);
218 ByteBuffer slice = buffer.slice();
221 final long checksum = crc32.getValue();
223 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
224 buffer.position(position);
225 buffer.putInt(length);
226 buffer.putInt((int) checksum);
227 buffer.position(position + Integer.BYTES + Integer.BYTES + length);
229 // Update the last entry with the correct index/term/length.
230 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
231 this.lastEntry = indexedEntry;
232 this.index.index(index, position);
233 return (Indexed<T>) indexedEntry;
237 public void commit(long index) {
242 public void truncate(long index) {
243 // If the index is greater than or equal to the last index, skip the truncate.
244 if (index >= getLastIndex()) {
248 // Reset the last entry.
251 // Truncate the index.
252 this.index.truncate(index);
254 if (index < segment.index()) {
255 buffer.position(JournalSegmentDescriptor.BYTES);
258 buffer.position(JournalSegmentDescriptor.BYTES);
260 // Reset the writer to the given index.
263 // Zero entries after the given index.
264 int position = buffer.position();
267 buffer.position(position);
272 public void flush() {
273 mappedBuffer.force();
277 public void close() {
280 BufferCleaner.freeBuffer(mappedBuffer);
281 } catch (IOException e) {
282 throw new StorageException(e);