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