Do not leak Kryo from atomix.storage
[controller.git] / third-party / atomix / storage / src / main / java / io / atomix / storage / journal / FileChannelJournalSegmentWriter.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.channels.FileChannel;
26 import java.util.zip.CRC32;
27 import java.util.zip.Checksum;
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 FileChannelJournalSegmentWriter<E> implements JournalWriter<E> {
45   private final FileChannel channel;
46   private final JournalSegment<E> segment;
47   private final int maxEntrySize;
48   private final JournalIndex index;
49   private final JournalSerdes namespace;
50   private final ByteBuffer memory;
51   private final long firstIndex;
52   private Indexed<E> lastEntry;
53
54   FileChannelJournalSegmentWriter(
55       FileChannel channel,
56       JournalSegment<E> segment,
57       int maxEntrySize,
58       JournalIndex index,
59       JournalSerdes namespace) {
60     this.channel = channel;
61     this.segment = segment;
62     this.maxEntrySize = maxEntrySize;
63     this.index = index;
64     this.memory = ByteBuffer.allocate((maxEntrySize + Integer.BYTES + Integer.BYTES) * 2);
65     memory.limit(0);
66     this.namespace = namespace;
67     this.firstIndex = segment.index();
68     reset(0);
69   }
70
71   @Override
72   public void reset(long index) {
73     long nextIndex = firstIndex;
74
75     // Clear the buffer indexes.
76     try {
77       channel.position(JournalSegmentDescriptor.BYTES);
78       memory.clear().flip();
79
80       // Record the current buffer position.
81       long position = channel.position();
82
83       // Read more bytes from the segment if necessary.
84       if (memory.remaining() < maxEntrySize) {
85         memory.clear();
86         channel.read(memory);
87         channel.position(position);
88         memory.flip();
89       }
90
91       // Read the entry length.
92       memory.mark();
93       int length = memory.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 = memory.getInt() & 0xFFFFFFFFL;
100
101         // Compute the checksum for the entry bytes.
102         final Checksum crc32 = new CRC32();
103         crc32.update(memory.array(), memory.position(), length);
104
105         // If the stored checksum equals the computed checksum, return the entry.
106         if (checksum == crc32.getValue()) {
107           int limit = memory.limit();
108           memory.limit(memory.position() + length);
109           final E entry = namespace.deserialize(memory);
110           memory.limit(limit);
111           lastEntry = new Indexed<>(nextIndex, entry, length);
112           this.index.index(nextIndex, (int) position);
113           nextIndex++;
114         } else {
115           break;
116         }
117
118         // Update the current position for indexing.
119         position = channel.position() + memory.position();
120
121         // Read more bytes from the segment if necessary.
122         if (memory.remaining() < maxEntrySize) {
123           channel.position(position);
124           memory.clear();
125           channel.read(memory);
126           channel.position(position);
127           memory.flip();
128         }
129
130         memory.mark();
131         length = memory.getInt();
132       }
133
134       // Reset the buffer to the previous mark.
135       channel.position(channel.position() + memory.reset().position());
136     } catch (BufferUnderflowException e) {
137       try {
138         channel.position(channel.position() + memory.reset().position());
139       } catch (IOException e2) {
140         throw new StorageException(e2);
141       }
142     } catch (IOException e) {
143       throw new StorageException(e);
144     }
145   }
146
147   @Override
148   public long getLastIndex() {
149     return lastEntry != null ? lastEntry.index() : segment.index() - 1;
150   }
151
152   @Override
153   public Indexed<E> getLastEntry() {
154     return lastEntry;
155   }
156
157   @Override
158   public long getNextIndex() {
159     if (lastEntry != null) {
160       return lastEntry.index() + 1;
161     } else {
162       return firstIndex;
163     }
164   }
165
166   /**
167    * Returns the size of the underlying buffer.
168    *
169    * @return The size of the underlying buffer.
170    */
171   public long size() {
172     try {
173       return channel.position();
174     } catch (IOException e) {
175       throw new StorageException(e);
176     }
177   }
178
179   /**
180    * Returns a boolean indicating whether the segment is empty.
181    *
182    * @return Indicates whether the segment is empty.
183    */
184   public boolean isEmpty() {
185     return lastEntry == null;
186   }
187
188   /**
189    * Returns a boolean indicating whether the segment is full.
190    *
191    * @return Indicates whether the segment is full.
192    */
193   public boolean isFull() {
194     return size() >= segment.descriptor().maxSegmentSize()
195         || getNextIndex() - firstIndex >= segment.descriptor().maxEntries();
196   }
197
198   /**
199    * Returns the first index written to the segment.
200    */
201   public long firstIndex() {
202     return firstIndex;
203   }
204
205   @Override
206   public void append(Indexed<E> entry) {
207     final long nextIndex = getNextIndex();
208
209     // If the entry's index is greater than the next index in the segment, skip some entries.
210     if (entry.index() > nextIndex) {
211       throw new IndexOutOfBoundsException("Entry index is not sequential");
212     }
213
214     // If the entry's index is less than the next index, truncate the segment.
215     if (entry.index() < nextIndex) {
216       truncate(entry.index() - 1);
217     }
218     append(entry.entry());
219   }
220
221   @Override
222   @SuppressWarnings("unchecked")
223   public <T extends E> Indexed<T> append(T entry) {
224     // Store the entry index.
225     final long index = getNextIndex();
226
227     try {
228       // Serialize the entry.
229       memory.clear();
230       memory.position(Integer.BYTES + Integer.BYTES);
231       try {
232         namespace.serialize(entry, memory);
233       } catch (KryoException e) {
234         throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
235       }
236       memory.flip();
237
238       final int length = memory.limit() - (Integer.BYTES + Integer.BYTES);
239
240       // Ensure there's enough space left in the buffer to store the entry.
241       long position = channel.position();
242       if (segment.descriptor().maxSegmentSize() - position < length + Integer.BYTES + Integer.BYTES) {
243         throw new BufferOverflowException();
244       }
245
246       // If the entry length exceeds the maximum entry size then throw an exception.
247       if (length > maxEntrySize) {
248         throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
249       }
250
251       // Compute the checksum for the entry.
252       final Checksum crc32 = new CRC32();
253       crc32.update(memory.array(), Integer.BYTES + Integer.BYTES, memory.limit() - (Integer.BYTES + Integer.BYTES));
254       final long checksum = crc32.getValue();
255
256       // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
257       memory.putInt(0, length);
258       memory.putInt(Integer.BYTES, (int) checksum);
259       channel.write(memory);
260
261       // Update the last entry with the correct index/term/length.
262       Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
263       this.lastEntry = indexedEntry;
264       this.index.index(index, (int) position);
265       return (Indexed<T>) indexedEntry;
266     } catch (IOException e) {
267       throw new StorageException(e);
268     }
269   }
270
271   @Override
272   public void commit(long index) {
273
274   }
275
276   @Override
277   public void truncate(long index) {
278     // If the index is greater than or equal to the last index, skip the truncate.
279     if (index >= getLastIndex()) {
280       return;
281     }
282
283     // Reset the last entry.
284     lastEntry = null;
285
286     try {
287       // Truncate the index.
288       this.index.truncate(index);
289
290       if (index < segment.index()) {
291         channel.position(JournalSegmentDescriptor.BYTES);
292         channel.write(zero());
293         channel.position(JournalSegmentDescriptor.BYTES);
294       } else {
295         // Reset the writer to the given index.
296         reset(index);
297
298         // Zero entries after the given index.
299         long position = channel.position();
300         channel.write(zero());
301         channel.position(position);
302       }
303     } catch (IOException e) {
304       throw new StorageException(e);
305     }
306   }
307
308   /**
309    * Returns a zeroed out byte buffer.
310    */
311   private ByteBuffer zero() {
312     memory.clear();
313     for (int i = 0; i < memory.limit(); i++) {
314       memory.put(i, (byte) 0);
315     }
316     return memory;
317   }
318
319   @Override
320   public void flush() {
321     try {
322       if (channel.isOpen()) {
323         channel.force(true);
324       }
325     } catch (IOException e) {
326       throw new StorageException(e);
327     }
328   }
329
330   @Override
331   public void close() {
332     flush();
333   }
334 }