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 // Slice off the entry's bytes
101 final ByteBuffer entryBytes = buffer.slice();
102 entryBytes.limit(length);
104 // Compute the checksum for the entry bytes.
105 final CRC32 crc32 = new CRC32();
106 crc32.update(entryBytes);
108 // If the stored checksum does not equal the computed checksum, do not proceed further
109 if (checksum != crc32.getValue()) {
114 final E entry = namespace.deserialize(entryBytes);
115 lastEntry = new Indexed<>(nextIndex, entry, length);
116 this.index.index(nextIndex, position);
119 // Update the current position for indexing.
120 position = buffer.position() + length;
121 buffer.position(position);
124 length = buffer.getInt();
127 // Reset the buffer to the previous mark.
129 } catch (BufferUnderflowException e) {
135 public long getLastIndex() {
136 return lastEntry != null ? lastEntry.index() : segment.index() - 1;
140 public Indexed<E> getLastEntry() {
145 public long getNextIndex() {
146 if (lastEntry != null) {
147 return lastEntry.index() + 1;
154 public void append(Indexed<E> entry) {
155 final long nextIndex = getNextIndex();
157 // If the entry's index is greater than the next index in the segment, skip some entries.
158 if (entry.index() > nextIndex) {
159 throw new IndexOutOfBoundsException("Entry index is not sequential");
162 // If the entry's index is less than the next index, truncate the segment.
163 if (entry.index() < nextIndex) {
164 truncate(entry.index() - 1);
166 append(entry.entry());
170 @SuppressWarnings("unchecked")
171 public <T extends E> Indexed<T> append(T entry) {
172 // Store the entry index.
173 final long index = getNextIndex();
175 // Serialize the entry.
176 int position = buffer.position();
177 if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
178 throw new BufferOverflowException();
181 buffer.position(position + Integer.BYTES + Integer.BYTES);
184 namespace.serialize(entry, buffer);
185 } catch (KryoException e) {
186 throw new BufferOverflowException();
189 final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
191 // If the entry length exceeds the maximum entry size then throw an exception.
192 if (length > maxEntrySize) {
193 // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
194 buffer.position(position);
195 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
198 // Compute the checksum for the entry.
199 final CRC32 crc32 = new CRC32();
200 buffer.position(position + Integer.BYTES + Integer.BYTES);
201 ByteBuffer slice = buffer.slice();
204 final long checksum = crc32.getValue();
206 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
207 buffer.position(position);
208 buffer.putInt(length);
209 buffer.putInt((int) checksum);
210 buffer.position(position + Integer.BYTES + Integer.BYTES + length);
212 // Update the last entry with the correct index/term/length.
213 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
214 this.lastEntry = indexedEntry;
215 this.index.index(index, position);
216 return (Indexed<T>) indexedEntry;
220 public void commit(long index) {
225 public void truncate(long index) {
226 // If the index is greater than or equal to the last index, skip the truncate.
227 if (index >= getLastIndex()) {
231 // Reset the last entry.
234 // Truncate the index.
235 this.index.truncate(index);
237 if (index < segment.index()) {
238 // Reset the writer to the first entry.
239 buffer.position(JournalSegmentDescriptor.BYTES);
241 // Reset the writer to the given index.
245 // Zero the entry header at current buffer position.
246 int position = buffer.position();
247 // Note: we issue a single putLong() instead of two putInt()s.
249 buffer.position(position);
253 public void flush() {
254 mappedBuffer.force();
258 public void close() {
261 BufferCleaner.freeBuffer(mappedBuffer);
262 } catch (IOException e) {
263 throw new StorageException(e);