Remove most of atomix.utils.memory
[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   public void append(Indexed<E> entry) {
174     final long nextIndex = getNextIndex();
175
176     // If the entry's index is greater than the next index in the segment, skip some entries.
177     if (entry.index() > nextIndex) {
178       throw new IndexOutOfBoundsException("Entry index is not sequential");
179     }
180
181     // If the entry's index is less than the next index, truncate the segment.
182     if (entry.index() < nextIndex) {
183       truncate(entry.index() - 1);
184     }
185     append(entry.entry());
186   }
187
188   @Override
189   @SuppressWarnings("unchecked")
190   public <T extends E> Indexed<T> append(T entry) {
191     // Store the entry index.
192     final long index = getNextIndex();
193
194     // Serialize the entry.
195     int position = buffer.position();
196     if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
197       throw new BufferOverflowException();
198     }
199
200     buffer.position(position + Integer.BYTES + Integer.BYTES);
201
202     try {
203       namespace.serialize(entry, buffer);
204     } catch (KryoException e) {
205       throw new BufferOverflowException();
206     }
207
208     final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
209
210     // If the entry length exceeds the maximum entry size then throw an exception.
211     if (length > maxEntrySize) {
212       // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
213       buffer.position(position);
214       throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
215     }
216
217     // Compute the checksum for the entry.
218     final CRC32 crc32 = new CRC32();
219     buffer.position(position + Integer.BYTES + Integer.BYTES);
220     ByteBuffer slice = buffer.slice();
221     slice.limit(length);
222     crc32.update(slice);
223     final long checksum = crc32.getValue();
224
225     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
226     buffer.position(position);
227     buffer.putInt(length);
228     buffer.putInt((int) checksum);
229     buffer.position(position + Integer.BYTES + Integer.BYTES + length);
230
231     // Update the last entry with the correct index/term/length.
232     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
233     this.lastEntry = indexedEntry;
234     this.index.index(index, position);
235     return (Indexed<T>) indexedEntry;
236   }
237
238   @Override
239   public void commit(long index) {
240
241   }
242
243   @Override
244   public void truncate(long index) {
245     // If the index is greater than or equal to the last index, skip the truncate.
246     if (index >= getLastIndex()) {
247       return;
248     }
249
250     // Reset the last entry.
251     lastEntry = null;
252
253     // Truncate the index.
254     this.index.truncate(index);
255
256     if (index < segment.index()) {
257       buffer.position(JournalSegmentDescriptor.BYTES);
258       buffer.putInt(0);
259       buffer.putInt(0);
260       buffer.position(JournalSegmentDescriptor.BYTES);
261     } else {
262       // Reset the writer to the given index.
263       reset(index);
264
265       // Zero entries after the given index.
266       int position = buffer.position();
267       buffer.putInt(0);
268       buffer.putInt(0);
269       buffer.position(position);
270     }
271   }
272
273   @Override
274   public void flush() {
275     mappedBuffer.force();
276   }
277
278   @Override
279   public void close() {
280     flush();
281     try {
282       BufferCleaner.freeBuffer(mappedBuffer);
283     } catch (IOException e) {
284       throw new StorageException(e);
285     }
286   }
287 }