5f146c7f8611f41c3960de8af284d401ee93861a
[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       channel.read(memory.clear(), JournalSegmentDescriptor.BYTES);
100       memory.flip();
101
102       // Read the entry length.
103       int length = memory.getInt();
104
105       // If the length is non-zero, read the entry.
106       while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
107
108         // Read the checksum of the entry.
109         final long checksum = memory.getInt() & 0xFFFFFFFFL;
110
111         // Slice off the entry's bytes
112         final ByteBuffer entryBytes = memory.slice();
113         entryBytes.limit(length);
114
115         // Compute the checksum for the entry bytes.
116         final CRC32 crc32 = new CRC32();
117         crc32.update(entryBytes);
118
119         // If the stored checksum does not equal the computed checksum, do not proceed further
120         if (checksum != crc32.getValue()) {
121           break;
122         }
123
124         entryBytes.rewind();
125         final E entry = namespace.deserialize(entryBytes);
126         lastEntry = new Indexed<>(nextIndex, entry, length);
127         this.index.index(nextIndex, (int) currentPosition);
128         nextIndex++;
129
130         // Update the current position for indexing.
131         currentPosition = currentPosition + Integer.BYTES + Integer.BYTES + length;
132         memory.position(memory.position() + length);
133
134         // Read more bytes from the segment if necessary.
135         if (memory.remaining() < maxEntrySize) {
136           channel.read(memory.compact());
137           memory.flip();
138         }
139
140         length = memory.getInt();
141       }
142     } catch (BufferUnderflowException e) {
143       // No-op, position is only updated on success
144     } catch (IOException e) {
145       throw new StorageException(e);
146     }
147   }
148
149   @Override
150   Indexed<E> getLastEntry() {
151     return lastEntry;
152   }
153
154   @Override
155   long getNextIndex() {
156     if (lastEntry != null) {
157       return lastEntry.index() + 1;
158     } else {
159       return firstIndex;
160     }
161   }
162
163   @Override
164   @SuppressWarnings("unchecked")
165   <T extends E> Indexed<T> append(T entry) {
166     // Store the entry index.
167     final long index = getNextIndex();
168
169     // Serialize the entry.
170     try {
171       namespace.serialize(entry, memory.clear().position(Integer.BYTES + Integer.BYTES));
172     } catch (KryoException e) {
173       throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
174     }
175     memory.flip();
176
177     final int length = memory.limit() - (Integer.BYTES + Integer.BYTES);
178
179     // Ensure there's enough space left in the buffer to store the entry.
180     if (maxSegmentSize - currentPosition < length + Integer.BYTES + Integer.BYTES) {
181       throw new BufferOverflowException();
182     }
183
184     // If the entry length exceeds the maximum entry size then throw an exception.
185     if (length > maxEntrySize) {
186       throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
187     }
188
189     // Compute the checksum for the entry.
190     final CRC32 crc32 = new CRC32();
191     crc32.update(memory.array(), Integer.BYTES + Integer.BYTES, memory.limit() - (Integer.BYTES + Integer.BYTES));
192     final long checksum = crc32.getValue();
193
194     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
195     memory.putInt(0, length).putInt(Integer.BYTES, (int) checksum);
196     try {
197       channel.write(memory, currentPosition);
198     } catch (IOException e) {
199       throw new StorageException(e);
200     }
201
202     // Update the last entry with the correct index/term/length.
203     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
204     this.lastEntry = indexedEntry;
205     this.index.index(index, (int) currentPosition);
206
207     currentPosition = currentPosition + Integer.BYTES + Integer.BYTES + length;
208     return (Indexed<T>) indexedEntry;
209   }
210
211   @Override
212   void truncate(long index) {
213     // If the index is greater than or equal to the last index, skip the truncate.
214     if (index >= getLastIndex()) {
215       return;
216     }
217
218     // Reset the last entry.
219     lastEntry = null;
220
221     // Truncate the index.
222     this.index.truncate(index);
223
224     try {
225       if (index < firstIndex) {
226         // Reset the writer to the first entry.
227         currentPosition = JournalSegmentDescriptor.BYTES;
228       } else {
229         // Reset the writer to the given index.
230         reset(index);
231       }
232
233       // Zero the entry header at current channel position.
234       channel.write(ZERO_ENTRY_HEADER.asReadOnlyBuffer(), currentPosition);
235     } catch (IOException e) {
236       throw new StorageException(e);
237     }
238   }
239
240   @Override
241   void flush() {
242     try {
243       if (channel.isOpen()) {
244         channel.force(true);
245       }
246     } catch (IOException e) {
247       throw new StorageException(e);
248     }
249   }
250
251   @Override
252   void close() {
253     flush();
254   }
255 }