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