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.memory.BufferCleaner;
22 import io.atomix.utils.serializer.Namespace;
24 import java.io.IOException;
25 import java.nio.BufferOverflowException;
26 import java.nio.BufferUnderflowException;
27 import java.nio.ByteBuffer;
28 import java.nio.MappedByteBuffer;
29 import java.util.zip.CRC32;
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 MappedJournalSegmentWriter<E> implements JournalWriter<E> {
47 private final MappedByteBuffer mappedBuffer;
48 private final ByteBuffer buffer;
49 private final JournalSegment<E> segment;
50 private final int maxEntrySize;
51 private final JournalIndex index;
52 private final Namespace namespace;
53 private final long firstIndex;
54 private Indexed<E> lastEntry;
56 MappedJournalSegmentWriter(
57 MappedByteBuffer buffer,
58 JournalSegment<E> segment,
61 Namespace namespace) {
62 this.mappedBuffer = buffer;
63 this.buffer = buffer.slice();
64 this.segment = segment;
65 this.maxEntrySize = maxEntrySize;
67 this.namespace = namespace;
68 this.firstIndex = segment.index();
73 * Returns the mapped buffer underlying the segment writer.
75 * @return the mapped buffer underlying the segment writer
77 MappedByteBuffer buffer() {
82 public void reset(long index) {
83 long nextIndex = firstIndex;
85 // Clear the buffer indexes.
86 buffer.position(JournalSegmentDescriptor.BYTES);
88 // Record the current buffer position.
89 int position = buffer.position();
91 // Read the entry length.
95 int length = buffer.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 = buffer.getInt() & 0xFFFFFFFFL;
103 // Compute the checksum for the entry bytes.
104 final CRC32 crc32 = new CRC32();
105 ByteBuffer slice = buffer.slice();
109 // If the stored checksum equals the computed checksum, return the entry.
110 if (checksum == crc32.getValue()) {
112 final E entry = namespace.deserialize(slice);
113 lastEntry = new Indexed<>(nextIndex, entry, length);
114 this.index.index(nextIndex, position);
120 // Update the current position for indexing.
121 position = buffer.position() + length;
122 buffer.position(position);
125 length = buffer.getInt();
128 // Reset the buffer to the previous mark.
130 } catch (BufferUnderflowException e) {
136 public long getLastIndex() {
137 return lastEntry != null ? lastEntry.index() : segment.index() - 1;
141 public Indexed<E> getLastEntry() {
146 public long getNextIndex() {
147 if (lastEntry != null) {
148 return lastEntry.index() + 1;
155 * Returns the size of the underlying buffer.
157 * @return The size of the underlying buffer.
160 return buffer.position() + JournalSegmentDescriptor.BYTES;
164 * Returns a boolean indicating whether the segment is empty.
166 * @return Indicates whether the segment is empty.
168 public boolean isEmpty() {
169 return lastEntry == null;
173 public void append(Indexed<E> entry) {
174 final long nextIndex = getNextIndex();
176 // If the entry's index is greater than the next index in the segment, skip some entries.
177 if (entry.index() > nextIndex) {
178 throw new IndexOutOfBoundsException("Entry index is not sequential");
181 // If the entry's index is less than the next index, truncate the segment.
182 if (entry.index() < nextIndex) {
183 truncate(entry.index() - 1);
185 append(entry.entry());
189 @SuppressWarnings("unchecked")
190 public <T extends E> Indexed<T> append(T entry) {
191 // Store the entry index.
192 final long index = getNextIndex();
194 // Serialize the entry.
195 int position = buffer.position();
196 if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
197 throw new BufferOverflowException();
200 buffer.position(position + Integer.BYTES + Integer.BYTES);
203 namespace.serialize(entry, buffer);
204 } catch (KryoException e) {
205 throw new BufferOverflowException();
208 final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
210 // If the entry length exceeds the maximum entry size then throw an exception.
211 if (length > maxEntrySize) {
212 // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
213 buffer.position(position);
214 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
217 // Compute the checksum for the entry.
218 final CRC32 crc32 = new CRC32();
219 buffer.position(position + Integer.BYTES + Integer.BYTES);
220 ByteBuffer slice = buffer.slice();
223 final long checksum = crc32.getValue();
225 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
226 buffer.position(position);
227 buffer.putInt(length);
228 buffer.putInt((int) checksum);
229 buffer.position(position + Integer.BYTES + Integer.BYTES + length);
231 // Update the last entry with the correct index/term/length.
232 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
233 this.lastEntry = indexedEntry;
234 this.index.index(index, position);
235 return (Indexed<T>) indexedEntry;
239 public void commit(long index) {
244 public void truncate(long index) {
245 // If the index is greater than or equal to the last index, skip the truncate.
246 if (index >= getLastIndex()) {
250 // Reset the last entry.
253 // Truncate the index.
254 this.index.truncate(index);
256 if (index < segment.index()) {
257 buffer.position(JournalSegmentDescriptor.BYTES);
260 buffer.position(JournalSegmentDescriptor.BYTES);
262 // Reset the writer to the given index.
265 // Zero entries after the given index.
266 int position = buffer.position();
269 buffer.position(position);
274 public void flush() {
275 mappedBuffer.force();
279 public void close() {
282 BufferCleaner.freeBuffer(mappedBuffer);
283 } catch (IOException e) {
284 throw new StorageException(e);