Position is a simple record
[controller.git] / third-party / 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 import io.atomix.utils.serializer.Namespace;
21
22 import java.io.IOException;
23 import java.nio.BufferOverflowException;
24 import java.nio.BufferUnderflowException;
25 import java.nio.ByteBuffer;
26 import java.nio.MappedByteBuffer;
27 import java.util.zip.CRC32;
28
29 /**
30  * Segment writer.
31  * <p>
32  * The format of an entry in the log is as follows:
33  * <ul>
34  * <li>64-bit index</li>
35  * <li>8-bit boolean indicating whether a term change is contained in the entry</li>
36  * <li>64-bit optional term</li>
37  * <li>32-bit signed entry length, including the entry type ID</li>
38  * <li>8-bit signed entry type ID</li>
39  * <li>n-bit entry bytes</li>
40  * </ul>
41  *
42  * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
43  */
44 class MappedJournalSegmentWriter<E> implements JournalWriter<E> {
45   private final MappedByteBuffer mappedBuffer;
46   private final ByteBuffer buffer;
47   private final JournalSegment<E> segment;
48   private final int maxEntrySize;
49   private final JournalIndex index;
50   private final Namespace namespace;
51   private final long firstIndex;
52   private Indexed<E> lastEntry;
53
54   MappedJournalSegmentWriter(
55       MappedByteBuffer buffer,
56       JournalSegment<E> segment,
57       int maxEntrySize,
58       JournalIndex index,
59       Namespace namespace) {
60     this.mappedBuffer = buffer;
61     this.buffer = buffer.slice();
62     this.segment = segment;
63     this.maxEntrySize = maxEntrySize;
64     this.index = index;
65     this.namespace = namespace;
66     this.firstIndex = segment.index();
67     reset(0);
68   }
69
70   /**
71    * Returns the mapped buffer underlying the segment writer.
72    *
73    * @return the mapped buffer underlying the segment writer
74    */
75   MappedByteBuffer buffer() {
76     return mappedBuffer;
77   }
78
79   @Override
80   public void reset(long index) {
81     long nextIndex = firstIndex;
82
83     // Clear the buffer indexes.
84     buffer.position(JournalSegmentDescriptor.BYTES);
85
86     // Record the current buffer position.
87     int position = buffer.position();
88
89     // Read the entry length.
90     buffer.mark();
91
92     try {
93       int length = buffer.getInt();
94
95       // If the length is non-zero, read the entry.
96       while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
97
98         // Read the checksum of the entry.
99         final long checksum = buffer.getInt() & 0xFFFFFFFFL;
100
101         // Compute the checksum for the entry bytes.
102         final CRC32 crc32 = new CRC32();
103         ByteBuffer slice = buffer.slice();
104         slice.limit(length);
105         crc32.update(slice);
106
107         // If the stored checksum equals the computed checksum, return the entry.
108         if (checksum == crc32.getValue()) {
109           slice.rewind();
110           final E entry = namespace.deserialize(slice);
111           lastEntry = new Indexed<>(nextIndex, entry, length);
112           this.index.index(nextIndex, position);
113           nextIndex++;
114         } else {
115           break;
116         }
117
118         // Update the current position for indexing.
119         position = buffer.position() + length;
120         buffer.position(position);
121
122         buffer.mark();
123         length = buffer.getInt();
124       }
125
126       // Reset the buffer to the previous mark.
127       buffer.reset();
128     } catch (BufferUnderflowException e) {
129       buffer.reset();
130     }
131   }
132
133   @Override
134   public long getLastIndex() {
135     return lastEntry != null ? lastEntry.index() : segment.index() - 1;
136   }
137
138   @Override
139   public Indexed<E> getLastEntry() {
140     return lastEntry;
141   }
142
143   @Override
144   public long getNextIndex() {
145     if (lastEntry != null) {
146       return lastEntry.index() + 1;
147     } else {
148       return firstIndex;
149     }
150   }
151
152   /**
153    * Returns the size of the underlying buffer.
154    *
155    * @return The size of the underlying buffer.
156    */
157   public long size() {
158     return buffer.position() + JournalSegmentDescriptor.BYTES;
159   }
160
161   /**
162    * Returns a boolean indicating whether the segment is empty.
163    *
164    * @return Indicates whether the segment is empty.
165    */
166   public boolean isEmpty() {
167     return lastEntry == null;
168   }
169
170   @Override
171   public void append(Indexed<E> entry) {
172     final long nextIndex = getNextIndex();
173
174     // If the entry's index is greater than the next index in the segment, skip some entries.
175     if (entry.index() > nextIndex) {
176       throw new IndexOutOfBoundsException("Entry index is not sequential");
177     }
178
179     // If the entry's index is less than the next index, truncate the segment.
180     if (entry.index() < nextIndex) {
181       truncate(entry.index() - 1);
182     }
183     append(entry.entry());
184   }
185
186   @Override
187   @SuppressWarnings("unchecked")
188   public <T extends E> Indexed<T> append(T entry) {
189     // Store the entry index.
190     final long index = getNextIndex();
191
192     // Serialize the entry.
193     int position = buffer.position();
194     if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
195       throw new BufferOverflowException();
196     }
197
198     buffer.position(position + Integer.BYTES + Integer.BYTES);
199
200     try {
201       namespace.serialize(entry, buffer);
202     } catch (KryoException e) {
203       throw new BufferOverflowException();
204     }
205
206     final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
207
208     // If the entry length exceeds the maximum entry size then throw an exception.
209     if (length > maxEntrySize) {
210       // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
211       buffer.position(position);
212       throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
213     }
214
215     // Compute the checksum for the entry.
216     final CRC32 crc32 = new CRC32();
217     buffer.position(position + Integer.BYTES + Integer.BYTES);
218     ByteBuffer slice = buffer.slice();
219     slice.limit(length);
220     crc32.update(slice);
221     final long checksum = crc32.getValue();
222
223     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
224     buffer.position(position);
225     buffer.putInt(length);
226     buffer.putInt((int) checksum);
227     buffer.position(position + Integer.BYTES + Integer.BYTES + length);
228
229     // Update the last entry with the correct index/term/length.
230     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
231     this.lastEntry = indexedEntry;
232     this.index.index(index, position);
233     return (Indexed<T>) indexedEntry;
234   }
235
236   @Override
237   public void commit(long index) {
238
239   }
240
241   @Override
242   public void truncate(long index) {
243     // If the index is greater than or equal to the last index, skip the truncate.
244     if (index >= getLastIndex()) {
245       return;
246     }
247
248     // Reset the last entry.
249     lastEntry = null;
250
251     // Truncate the index.
252     this.index.truncate(index);
253
254     if (index < segment.index()) {
255       buffer.position(JournalSegmentDescriptor.BYTES);
256       buffer.putInt(0);
257       buffer.putInt(0);
258       buffer.position(JournalSegmentDescriptor.BYTES);
259     } else {
260       // Reset the writer to the given index.
261       reset(index);
262
263       // Zero entries after the given index.
264       int position = buffer.position();
265       buffer.putInt(0);
266       buffer.putInt(0);
267       buffer.position(position);
268     }
269   }
270
271   @Override
272   public void flush() {
273     mappedBuffer.force();
274   }
275
276   @Override
277   public void close() {
278     flush();
279     try {
280       BufferCleaner.freeBuffer(mappedBuffer);
281     } catch (IOException e) {
282       throw new StorageException(e);
283     }
284   }
285 }