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