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 @SuppressWarnings("unchecked")
174 public void append(Indexed<E> entry) {
175 final long nextIndex = getNextIndex();
177 // If the entry's index is greater than the next index in the segment, skip some entries.
178 if (entry.index() > nextIndex) {
179 throw new IndexOutOfBoundsException("Entry index is not sequential");
182 // If the entry's index is less than the next index, truncate the segment.
183 if (entry.index() < nextIndex) {
184 truncate(entry.index() - 1);
186 append(entry.entry());
190 @SuppressWarnings("unchecked")
191 public <T extends E> Indexed<T> append(T entry) {
192 // Store the entry index.
193 final long index = getNextIndex();
195 // Serialize the entry.
196 int position = buffer.position();
197 if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
198 throw new BufferOverflowException();
201 buffer.position(position + Integer.BYTES + Integer.BYTES);
204 namespace.serialize(entry, buffer);
205 } catch (KryoException e) {
206 throw new BufferOverflowException();
209 final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
211 // If the entry length exceeds the maximum entry size then throw an exception.
212 if (length > maxEntrySize) {
213 // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
214 buffer.position(position);
215 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
218 // Compute the checksum for the entry.
219 final CRC32 crc32 = new CRC32();
220 buffer.position(position + Integer.BYTES + Integer.BYTES);
221 ByteBuffer slice = buffer.slice();
224 final long checksum = crc32.getValue();
226 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
227 buffer.position(position);
228 buffer.putInt(length);
229 buffer.putInt((int) checksum);
230 buffer.position(position + Integer.BYTES + Integer.BYTES + length);
232 // Update the last entry with the correct index/term/length.
233 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
234 this.lastEntry = indexedEntry;
235 this.index.index(index, position);
236 return (Indexed<T>) indexedEntry;
240 public void commit(long index) {
245 @SuppressWarnings("unchecked")
246 public void truncate(long index) {
247 // If the index is greater than or equal to the last index, skip the truncate.
248 if (index >= getLastIndex()) {
252 // Reset the last entry.
255 // Truncate the index.
256 this.index.truncate(index);
258 if (index < segment.index()) {
259 buffer.position(JournalSegmentDescriptor.BYTES);
262 buffer.position(JournalSegmentDescriptor.BYTES);
264 // Reset the writer to the given index.
267 // Zero entries after the given index.
268 int position = buffer.position();
271 buffer.position(position);
276 public void flush() {
277 mappedBuffer.force();
281 public void close() {
284 BufferCleaner.freeBuffer(mappedBuffer);
285 } catch (IOException e) {
286 throw new StorageException(e);