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