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