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.nio.channels.FileChannel;
27 import java.util.zip.CRC32;
28 import org.eclipse.jdt.annotation.NonNull;
33 * The format of an entry in the log is as follows:
35 * <li>64-bit index</li>
36 * <li>8-bit boolean indicating whether a term change is contained in the entry</li>
37 * <li>64-bit optional term</li>
38 * <li>32-bit signed entry length, including the entry type ID</li>
39 * <li>8-bit signed entry type ID</li>
40 * <li>n-bit entry bytes</li>
43 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
45 final class MappedJournalSegmentWriter<E> extends JournalSegmentWriter<E> {
46 private final @NonNull MappedByteBuffer mappedBuffer;
47 private final ByteBuffer buffer;
49 private Indexed<E> lastEntry;
51 MappedJournalSegmentWriter(
53 JournalSegment<E> segment,
56 JournalSerdes namespace) {
57 super(channel, segment, maxEntrySize, index, namespace);
58 mappedBuffer = mapBuffer(channel, maxSegmentSize);
59 buffer = mappedBuffer.slice();
63 MappedJournalSegmentWriter(JournalSegmentWriter<E> previous, int position) {
65 mappedBuffer = mapBuffer(channel, maxSegmentSize);
66 buffer = mappedBuffer.slice();
67 lastEntry = previous.getLastEntry();
68 buffer.position(position);
71 private static @NonNull MappedByteBuffer mapBuffer(FileChannel channel, int maxSegmentSize) {
73 return channel.map(FileChannel.MapMode.READ_WRITE, 0, maxSegmentSize);
74 } catch (IOException e) {
75 throw new StorageException(e);
80 @NonNull MappedByteBuffer buffer() {
85 MappedJournalSegmentWriter<E> toMapped() {
90 FileChannelJournalSegmentWriter<E> toFileChannel() {
91 final int position = buffer.position();
93 return new FileChannelJournalSegmentWriter<>(this, position);
97 void reset(long index) {
98 long nextIndex = firstIndex;
100 // Clear the buffer indexes.
101 buffer.position(JournalSegmentDescriptor.BYTES);
103 // Record the current buffer position.
104 int position = buffer.position();
106 // Read the entry length.
110 int length = buffer.getInt();
112 // If the length is non-zero, read the entry.
113 while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
115 // Read the checksum of the entry.
116 final long checksum = buffer.getInt() & 0xFFFFFFFFL;
118 // Slice off the entry's bytes
119 final ByteBuffer entryBytes = buffer.slice();
120 entryBytes.limit(length);
122 // Compute the checksum for the entry bytes.
123 final CRC32 crc32 = new CRC32();
124 crc32.update(entryBytes);
126 // If the stored checksum does not equal the computed checksum, do not proceed further
127 if (checksum != crc32.getValue()) {
132 final E entry = namespace.deserialize(entryBytes);
133 lastEntry = new Indexed<>(nextIndex, entry, length);
134 this.index.index(nextIndex, position);
137 // Update the current position for indexing.
138 position = buffer.position() + length;
139 buffer.position(position);
142 length = buffer.getInt();
145 // Reset the buffer to the previous mark.
147 } catch (BufferUnderflowException e) {
153 Indexed<E> getLastEntry() {
158 long getNextIndex() {
159 if (lastEntry != null) {
160 return lastEntry.index() + 1;
167 @SuppressWarnings("unchecked")
168 <T extends E> Indexed<T> append(T entry) {
169 // Store the entry index.
170 final long index = getNextIndex();
172 // Serialize the entry.
173 int position = buffer.position();
174 if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
175 throw new BufferOverflowException();
178 buffer.position(position + Integer.BYTES + Integer.BYTES);
181 namespace.serialize(entry, buffer);
182 } catch (KryoException e) {
183 throw new BufferOverflowException();
186 final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
188 // If the entry length exceeds the maximum entry size then throw an exception.
189 if (length > maxEntrySize) {
190 // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
191 buffer.position(position);
192 throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
195 // Compute the checksum for the entry.
196 final CRC32 crc32 = new CRC32();
197 buffer.position(position + Integer.BYTES + Integer.BYTES);
198 ByteBuffer slice = buffer.slice();
201 final long checksum = crc32.getValue();
203 // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
204 buffer.position(position);
205 buffer.putInt(length);
206 buffer.putInt((int) checksum);
207 buffer.position(position + Integer.BYTES + Integer.BYTES + length);
209 // Update the last entry with the correct index/term/length.
210 Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
211 this.lastEntry = indexedEntry;
212 this.index.index(index, position);
213 return (Indexed<T>) indexedEntry;
217 void truncate(long index) {
218 // If the index is greater than or equal to the last index, skip the truncate.
219 if (index >= getLastIndex()) {
223 // Reset the last entry.
226 // Truncate the index.
227 this.index.truncate(index);
229 if (index < firstIndex) {
230 // Reset the writer to the first entry.
231 buffer.position(JournalSegmentDescriptor.BYTES);
233 // Reset the writer to the given index.
237 // Zero the entry header at current buffer position.
238 int position = buffer.position();
239 // Note: we issue a single putLong() instead of two putInt()s.
241 buffer.position(position);
246 mappedBuffer.force();
253 BufferCleaner.freeBuffer(mappedBuffer);
254 } catch (IOException e) {
255 throw new StorageException(e);