Introduce JournalSegmentWriter
[controller.git] / 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.MappedByteBuffer;
26 import java.nio.channels.FileChannel;
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 final class FileChannelJournalSegmentWriter<E> extends JournalSegmentWriter<E> {
45   private static final ByteBuffer ZERO_ENTRY_HEADER = ByteBuffer.wrap(new byte[Integer.BYTES + Integer.BYTES]);
46
47   private final FileChannel channel;
48   private final ByteBuffer memory;
49   private Indexed<E> lastEntry;
50   private long currentPosition;
51
52   FileChannelJournalSegmentWriter(
53       FileChannel channel,
54       JournalSegment<E> segment,
55       int maxEntrySize,
56       JournalIndex index,
57       JournalSerdes namespace) {
58     super(segment, maxEntrySize, index, namespace);
59     this.channel = channel;
60     this.memory = ByteBuffer.allocate((maxEntrySize + Integer.BYTES + Integer.BYTES) * 2);
61     memory.limit(0);
62     reset(0);
63   }
64
65   @Override
66   MappedByteBuffer buffer() {
67     return null;
68   }
69
70   @Override
71   public void reset(long index) {
72     long nextIndex = firstIndex;
73
74     // Clear the buffer indexes.
75     currentPosition = JournalSegmentDescriptor.BYTES;
76
77     try {
78       // Clear memory buffer and read fist chunk
79       memory.clear();
80       channel.read(memory, JournalSegmentDescriptor.BYTES);
81       memory.flip();
82
83       // Read the entry length.
84       int length = memory.getInt();
85
86       // If the length is non-zero, read the entry.
87       while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
88
89         // Read the checksum of the entry.
90         final long checksum = memory.getInt() & 0xFFFFFFFFL;
91
92         // Slice off the entry's bytes
93         final ByteBuffer entryBytes = memory.slice();
94         entryBytes.limit(length);
95
96         // Compute the checksum for the entry bytes.
97         final CRC32 crc32 = new CRC32();
98         crc32.update(entryBytes);
99
100         // If the stored checksum does not equal the computed checksum, do not proceed further
101         if (checksum != crc32.getValue()) {
102           break;
103         }
104
105         entryBytes.rewind();
106         final E entry = namespace.deserialize(entryBytes);
107         lastEntry = new Indexed<>(nextIndex, entry, length);
108         this.index.index(nextIndex, (int) currentPosition);
109         nextIndex++;
110
111         // Update the current position for indexing.
112         currentPosition = currentPosition + Integer.BYTES + Integer.BYTES + length;
113         memory.position(memory.position() + length);
114
115         // Read more bytes from the segment if necessary.
116         if (memory.remaining() < maxEntrySize) {
117           memory.clear();
118           channel.read(memory, currentPosition);
119           memory.flip();
120         }
121
122         length = memory.getInt();
123       }
124     } catch (BufferUnderflowException e) {
125       // No-op, position is only updated on success
126     } catch (IOException e) {
127       throw new StorageException(e);
128     }
129   }
130
131   @Override
132   public long getLastIndex() {
133     return lastEntry != null ? lastEntry.index() : segment.index() - 1;
134   }
135
136   @Override
137   public Indexed<E> getLastEntry() {
138     return lastEntry;
139   }
140
141   @Override
142   public long getNextIndex() {
143     if (lastEntry != null) {
144       return lastEntry.index() + 1;
145     } else {
146       return firstIndex;
147     }
148   }
149
150   @Override
151   public void append(Indexed<E> entry) {
152     final long nextIndex = getNextIndex();
153
154     // If the entry's index is greater than the next index in the segment, skip some entries.
155     if (entry.index() > nextIndex) {
156       throw new IndexOutOfBoundsException("Entry index is not sequential");
157     }
158
159     // If the entry's index is less than the next index, truncate the segment.
160     if (entry.index() < nextIndex) {
161       truncate(entry.index() - 1);
162     }
163     append(entry.entry());
164   }
165
166   @Override
167   @SuppressWarnings("unchecked")
168   public <T extends E> Indexed<T> append(T entry) {
169     // Store the entry index.
170     final long index = getNextIndex();
171
172     // Serialize the entry.
173     memory.clear();
174     memory.position(Integer.BYTES + Integer.BYTES);
175     try {
176       namespace.serialize(entry, memory);
177     } catch (KryoException e) {
178       throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
179     }
180     memory.flip();
181
182     final int length = memory.limit() - (Integer.BYTES + Integer.BYTES);
183
184     // Ensure there's enough space left in the buffer to store the entry.
185     if (segment.descriptor().maxSegmentSize() - currentPosition < length + Integer.BYTES + Integer.BYTES) {
186       throw new BufferOverflowException();
187     }
188
189     // If the entry length exceeds the maximum entry size then throw an exception.
190     if (length > maxEntrySize) {
191       throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
192     }
193
194     // Compute the checksum for the entry.
195     final CRC32 crc32 = new CRC32();
196     crc32.update(memory.array(), Integer.BYTES + Integer.BYTES, memory.limit() - (Integer.BYTES + Integer.BYTES));
197     final long checksum = crc32.getValue();
198
199     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
200     memory.putInt(0, length);
201     memory.putInt(Integer.BYTES, (int) checksum);
202     try {
203       channel.write(memory, currentPosition);
204     } catch (IOException e) {
205       throw new StorageException(e);
206     }
207
208     // Update the last entry with the correct index/term/length.
209     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
210     this.lastEntry = indexedEntry;
211     this.index.index(index, (int) currentPosition);
212
213     currentPosition = currentPosition + Integer.BYTES + Integer.BYTES + length;
214     return (Indexed<T>) indexedEntry;
215   }
216
217   @Override
218   public void truncate(long index) {
219     // If the index is greater than or equal to the last index, skip the truncate.
220     if (index >= getLastIndex()) {
221       return;
222     }
223
224     // Reset the last entry.
225     lastEntry = null;
226
227     // Truncate the index.
228     this.index.truncate(index);
229
230     try {
231       if (index < segment.index()) {
232         // Reset the writer to the first entry.
233         currentPosition = JournalSegmentDescriptor.BYTES;
234       } else {
235         // Reset the writer to the given index.
236         reset(index);
237       }
238
239       // Zero the entry header at current channel position.
240       channel.write(ZERO_ENTRY_HEADER.asReadOnlyBuffer(), currentPosition);
241     } catch (IOException e) {
242       throw new StorageException(e);
243     }
244   }
245
246   @Override
247   public void flush() {
248     try {
249       if (channel.isOpen()) {
250         channel.force(true);
251       }
252     } catch (IOException e) {
253       throw new StorageException(e);
254     }
255   }
256
257   @Override
258   public void close() {
259     flush();
260   }
261 }