Do not store JournalSegment in JournalSegmentWriter
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / MappedJournalSegmentWriter.java
1 /*
2  * Copyright 2017-present Open Networking Foundation
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 package io.atomix.storage.journal;
17
18 import com.esotericsoftware.kryo.KryoException;
19 import io.atomix.storage.journal.index.JournalIndex;
20
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;
29
30 /**
31  * Segment writer.
32  * <p>
33  * The format of an entry in the log is as follows:
34  * <ul>
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>
41  * </ul>
42  *
43  * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
44  */
45 final class MappedJournalSegmentWriter<E> extends JournalSegmentWriter<E> {
46   private final @NonNull MappedByteBuffer mappedBuffer;
47   private final ByteBuffer buffer;
48
49   private Indexed<E> lastEntry;
50
51   MappedJournalSegmentWriter(
52       FileChannel channel,
53       JournalSegment<E> segment,
54       int maxEntrySize,
55       JournalIndex index,
56       JournalSerdes namespace) {
57     super(channel, segment, maxEntrySize, index, namespace);
58     mappedBuffer = mapBuffer(channel, maxSegmentSize);
59     buffer = mappedBuffer.slice();
60     reset(0);
61   }
62
63   MappedJournalSegmentWriter(JournalSegmentWriter<E> previous, int position) {
64     super(previous);
65     mappedBuffer = mapBuffer(channel, maxSegmentSize);
66     buffer = mappedBuffer.slice();
67     lastEntry = previous.getLastEntry();
68     buffer.position(position);
69   }
70
71   private static @NonNull MappedByteBuffer mapBuffer(FileChannel channel, int maxSegmentSize) {
72     try {
73       return channel.map(FileChannel.MapMode.READ_WRITE, 0, maxSegmentSize);
74     } catch (IOException e) {
75       throw new StorageException(e);
76     }
77   }
78
79   @Override
80   @NonNull MappedByteBuffer buffer() {
81     return mappedBuffer;
82   }
83
84   @Override
85   MappedJournalSegmentWriter<E> toMapped() {
86     return this;
87   }
88
89   @Override
90   FileChannelJournalSegmentWriter<E> toFileChannel() {
91     final int position = buffer.position();
92     close();
93     return new FileChannelJournalSegmentWriter<>(this, position);
94   }
95
96   @Override
97   public void reset(long index) {
98     long nextIndex = firstIndex;
99
100     // Clear the buffer indexes.
101     buffer.position(JournalSegmentDescriptor.BYTES);
102
103     // Record the current buffer position.
104     int position = buffer.position();
105
106     // Read the entry length.
107     buffer.mark();
108
109     try {
110       int length = buffer.getInt();
111
112       // If the length is non-zero, read the entry.
113       while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
114
115         // Read the checksum of the entry.
116         final long checksum = buffer.getInt() & 0xFFFFFFFFL;
117
118         // Slice off the entry's bytes
119         final ByteBuffer entryBytes = buffer.slice();
120         entryBytes.limit(length);
121
122         // Compute the checksum for the entry bytes.
123         final CRC32 crc32 = new CRC32();
124         crc32.update(entryBytes);
125
126         // If the stored checksum does not equal the computed checksum, do not proceed further
127         if (checksum != crc32.getValue()) {
128           break;
129         }
130
131         entryBytes.rewind();
132         final E entry = namespace.deserialize(entryBytes);
133         lastEntry = new Indexed<>(nextIndex, entry, length);
134         this.index.index(nextIndex, position);
135         nextIndex++;
136
137         // Update the current position for indexing.
138         position = buffer.position() + length;
139         buffer.position(position);
140
141         buffer.mark();
142         length = buffer.getInt();
143       }
144
145       // Reset the buffer to the previous mark.
146       buffer.reset();
147     } catch (BufferUnderflowException e) {
148       buffer.reset();
149     }
150   }
151
152   @Override
153   public long getLastIndex() {
154     return lastEntry != null ? lastEntry.index() : firstIndex - 1;
155   }
156
157   @Override
158   public Indexed<E> getLastEntry() {
159     return lastEntry;
160   }
161
162   @Override
163   public long getNextIndex() {
164     if (lastEntry != null) {
165       return lastEntry.index() + 1;
166     } else {
167       return firstIndex;
168     }
169   }
170
171   @Override
172   public void append(Indexed<E> entry) {
173     final long nextIndex = getNextIndex();
174
175     // If the entry's index is greater than the next index in the segment, skip some entries.
176     if (entry.index() > nextIndex) {
177       throw new IndexOutOfBoundsException("Entry index is not sequential");
178     }
179
180     // If the entry's index is less than the next index, truncate the segment.
181     if (entry.index() < nextIndex) {
182       truncate(entry.index() - 1);
183     }
184     append(entry.entry());
185   }
186
187   @Override
188   @SuppressWarnings("unchecked")
189   public <T extends E> Indexed<T> append(T entry) {
190     // Store the entry index.
191     final long index = getNextIndex();
192
193     // Serialize the entry.
194     int position = buffer.position();
195     if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
196       throw new BufferOverflowException();
197     }
198
199     buffer.position(position + Integer.BYTES + Integer.BYTES);
200
201     try {
202       namespace.serialize(entry, buffer);
203     } catch (KryoException e) {
204       throw new BufferOverflowException();
205     }
206
207     final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
208
209     // If the entry length exceeds the maximum entry size then throw an exception.
210     if (length > maxEntrySize) {
211       // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
212       buffer.position(position);
213       throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
214     }
215
216     // Compute the checksum for the entry.
217     final CRC32 crc32 = new CRC32();
218     buffer.position(position + Integer.BYTES + Integer.BYTES);
219     ByteBuffer slice = buffer.slice();
220     slice.limit(length);
221     crc32.update(slice);
222     final long checksum = crc32.getValue();
223
224     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
225     buffer.position(position);
226     buffer.putInt(length);
227     buffer.putInt((int) checksum);
228     buffer.position(position + Integer.BYTES + Integer.BYTES + length);
229
230     // Update the last entry with the correct index/term/length.
231     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
232     this.lastEntry = indexedEntry;
233     this.index.index(index, position);
234     return (Indexed<T>) indexedEntry;
235   }
236
237
238   @Override
239   public void truncate(long index) {
240     // If the index is greater than or equal to the last index, skip the truncate.
241     if (index >= getLastIndex()) {
242       return;
243     }
244
245     // Reset the last entry.
246     lastEntry = null;
247
248     // Truncate the index.
249     this.index.truncate(index);
250
251     if (index < firstIndex) {
252       // Reset the writer to the first entry.
253       buffer.position(JournalSegmentDescriptor.BYTES);
254     } else {
255       // Reset the writer to the given index.
256       reset(index);
257     }
258
259     // Zero the entry header at current buffer position.
260     int position = buffer.position();
261     // Note: we issue a single putLong() instead of two putInt()s.
262     buffer.putLong(0);
263     buffer.position(position);
264   }
265
266   @Override
267   public void flush() {
268     mappedBuffer.force();
269   }
270
271   @Override
272   public void close() {
273     flush();
274     try {
275       BufferCleaner.freeBuffer(mappedBuffer);
276     } catch (IOException e) {
277       throw new StorageException(e);
278     }
279   }
280 }