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 static java.util.Objects.requireNonNull;
20 import com.esotericsoftware.kryo.KryoException;
21 import io.atomix.storage.journal.index.JournalIndex;
23 import java.io.IOException;
24 import java.nio.BufferOverflowException;
25 import java.nio.BufferUnderflowException;
26 import java.nio.ByteBuffer;
27 import java.nio.MappedByteBuffer;
28 import java.util.zip.CRC32;
29 import org.eclipse.jdt.annotation.NonNull;
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 final class MappedJournalSegmentWriter<E> extends JournalSegmentWriter<E> {
47 private final @NonNull MappedByteBuffer mappedBuffer;
48 private final ByteBuffer buffer;
50 private Indexed<E> lastEntry;
52 MappedJournalSegmentWriter(
53 MappedByteBuffer buffer,
54 JournalSegment<E> segment,
57 JournalSerdes namespace) {
58 super(segment, maxEntrySize, index, namespace);
59 this.mappedBuffer = requireNonNull(buffer);
60 this.buffer = buffer.slice();
65 @NonNull MappedByteBuffer buffer() {
70 public void reset(long index) {
71 long nextIndex = firstIndex;
73 // Clear the buffer indexes.
74 buffer.position(JournalSegmentDescriptor.BYTES);
76 // Record the current buffer position.
77 int position = buffer.position();
79 // Read the entry length.
83 int length = buffer.getInt();
85 // If the length is non-zero, read the entry.
86 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
88 // Read the checksum of the entry.
89 final long checksum = buffer.getInt() & 0xFFFFFFFFL;
91 // Slice off the entry's bytes
92 final ByteBuffer entryBytes = buffer.slice();
93 entryBytes.limit(length);
95 // Compute the checksum for the entry bytes.
96 final CRC32 crc32 = new CRC32();
97 crc32.update(entryBytes);
99 // If the stored checksum does not equal the computed checksum, do not proceed further
100 if (checksum != crc32.getValue()) {
105 final E entry = namespace.deserialize(entryBytes);
106 lastEntry = new Indexed<>(nextIndex, entry, length);
107 this.index.index(nextIndex, position);
110 // Update the current position for indexing.
111 position = buffer.position() + length;
112 buffer.position(position);
115 length = buffer.getInt();
118 // Reset the buffer to the previous mark.
120 } catch (BufferUnderflowException e) {
126 public long getLastIndex() {
127 return lastEntry != null ? lastEntry.index() : segment.index() - 1;
131 public Indexed<E> getLastEntry() {
136 public long getNextIndex() {
137 if (lastEntry != null) {
138 return lastEntry.index() + 1;
145 public void append(Indexed<E> entry) {
146 final long nextIndex = getNextIndex();
148 // If the entry's index is greater than the next index in the segment, skip some entries.
149 if (entry.index() > nextIndex) {
150 throw new IndexOutOfBoundsException("Entry index is not sequential");
153 // If the entry's index is less than the next index, truncate the segment.
154 if (entry.index() < nextIndex) {
155 truncate(entry.index() - 1);
157 append(entry.entry());
161 @SuppressWarnings("unchecked")
162 public <T extends E> Indexed<T> append(T entry) {
163 // Store the entry index.
164 final long index = getNextIndex();
166 // Serialize the entry.
167 int position = buffer.position();
168 if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
169 throw new BufferOverflowException();
172 buffer.position(position + Integer.BYTES + Integer.BYTES);
175 namespace.serialize(entry, buffer);
176 } catch (KryoException e) {
177 throw new BufferOverflowException();
180 final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
182 // If the entry length exceeds the maximum entry size then throw an exception.
183 if (length > maxEntrySize) {
184 // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
185 buffer.position(position);
186 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
189 // Compute the checksum for the entry.
190 final CRC32 crc32 = new CRC32();
191 buffer.position(position + Integer.BYTES + Integer.BYTES);
192 ByteBuffer slice = buffer.slice();
195 final long checksum = crc32.getValue();
197 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
198 buffer.position(position);
199 buffer.putInt(length);
200 buffer.putInt((int) checksum);
201 buffer.position(position + Integer.BYTES + Integer.BYTES + length);
203 // Update the last entry with the correct index/term/length.
204 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
205 this.lastEntry = indexedEntry;
206 this.index.index(index, position);
207 return (Indexed<T>) indexedEntry;
212 public void truncate(long index) {
213 // If the index is greater than or equal to the last index, skip the truncate.
214 if (index >= getLastIndex()) {
218 // Reset the last entry.
221 // Truncate the index.
222 this.index.truncate(index);
224 if (index < segment.index()) {
225 // Reset the writer to the first entry.
226 buffer.position(JournalSegmentDescriptor.BYTES);
228 // Reset the writer to the given index.
232 // Zero the entry header at current buffer position.
233 int position = buffer.position();
234 // Note: we issue a single putLong() instead of two putInt()s.
236 buffer.position(position);
240 public void flush() {
241 mappedBuffer.force();
245 public void close() {
248 BufferCleaner.freeBuffer(mappedBuffer);
249 } catch (IOException e) {
250 throw new StorageException(e);