Improve entry crc32 computation
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / MappedJournalSegmentWriter.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.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 MappedJournalSegmentWriter<E> implements JournalWriter<E> {
44   private final MappedByteBuffer mappedBuffer;
45   private final ByteBuffer buffer;
46   private final JournalSegment<E> segment;
47   private final int maxEntrySize;
48   private final JournalIndex index;
49   private final JournalSerdes namespace;
50   private final long firstIndex;
51   private Indexed<E> lastEntry;
52
53   MappedJournalSegmentWriter(
54       MappedByteBuffer buffer,
55       JournalSegment<E> segment,
56       int maxEntrySize,
57       JournalIndex index,
58       JournalSerdes namespace) {
59     this.mappedBuffer = buffer;
60     this.buffer = buffer.slice();
61     this.segment = segment;
62     this.maxEntrySize = maxEntrySize;
63     this.index = index;
64     this.namespace = namespace;
65     this.firstIndex = segment.index();
66     reset(0);
67   }
68
69   /**
70    * Returns the mapped buffer underlying the segment writer.
71    *
72    * @return the mapped buffer underlying the segment writer
73    */
74   MappedByteBuffer buffer() {
75     return mappedBuffer;
76   }
77
78   @Override
79   public void reset(long index) {
80     long nextIndex = firstIndex;
81
82     // Clear the buffer indexes.
83     buffer.position(JournalSegmentDescriptor.BYTES);
84
85     // Record the current buffer position.
86     int position = buffer.position();
87
88     // Read the entry length.
89     buffer.mark();
90
91     try {
92       int length = buffer.getInt();
93
94       // If the length is non-zero, read the entry.
95       while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
96
97         // Read the checksum of the entry.
98         final long checksum = buffer.getInt() & 0xFFFFFFFFL;
99
100         // Slice off the entry's bytes
101         final ByteBuffer entryBytes = buffer.slice();
102         entryBytes.limit(length);
103
104         // Compute the checksum for the entry bytes.
105         final CRC32 crc32 = new CRC32();
106         crc32.update(entryBytes);
107
108         // If the stored checksum does not equal the computed checksum, do not proceed further
109         if (checksum != crc32.getValue()) {
110           break;
111         }
112
113         entryBytes.rewind();
114         final E entry = namespace.deserialize(entryBytes);
115         lastEntry = new Indexed<>(nextIndex, entry, length);
116         this.index.index(nextIndex, position);
117         nextIndex++;
118
119         // Update the current position for indexing.
120         position = buffer.position() + length;
121         buffer.position(position);
122
123         buffer.mark();
124         length = buffer.getInt();
125       }
126
127       // Reset the buffer to the previous mark.
128       buffer.reset();
129     } catch (BufferUnderflowException e) {
130       buffer.reset();
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     int position = buffer.position();
177     if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
178       throw new BufferOverflowException();
179     }
180
181     buffer.position(position + Integer.BYTES + Integer.BYTES);
182
183     try {
184       namespace.serialize(entry, buffer);
185     } catch (KryoException e) {
186       throw new BufferOverflowException();
187     }
188
189     final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
190
191     // If the entry length exceeds the maximum entry size then throw an exception.
192     if (length > maxEntrySize) {
193       // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
194       buffer.position(position);
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     buffer.position(position + Integer.BYTES + Integer.BYTES);
201     ByteBuffer slice = buffer.slice();
202     slice.limit(length);
203     crc32.update(slice);
204     final long checksum = crc32.getValue();
205
206     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
207     buffer.position(position);
208     buffer.putInt(length);
209     buffer.putInt((int) checksum);
210     buffer.position(position + Integer.BYTES + Integer.BYTES + length);
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, position);
216     return (Indexed<T>) indexedEntry;
217   }
218
219   @Override
220   public void commit(long index) {
221
222   }
223
224   @Override
225   public void truncate(long index) {
226     // If the index is greater than or equal to the last index, skip the truncate.
227     if (index >= getLastIndex()) {
228       return;
229     }
230
231     // Reset the last entry.
232     lastEntry = null;
233
234     // Truncate the index.
235     this.index.truncate(index);
236
237     if (index < segment.index()) {
238       // Reset the writer to the first entry.
239       buffer.position(JournalSegmentDescriptor.BYTES);
240     } else {
241       // Reset the writer to the given index.
242       reset(index);
243     }
244
245     // Zero the entry header at current buffer position.
246     int position = buffer.position();
247     // Note: we issue a single putLong() instead of two putInt()s.
248     buffer.putLong(0);
249     buffer.position(position);
250   }
251
252   @Override
253   public void flush() {
254     mappedBuffer.force();
255   }
256
257   @Override
258   public void close() {
259     flush();
260     try {
261       BufferCleaner.freeBuffer(mappedBuffer);
262     } catch (IOException e) {
263       throw new StorageException(e);
264     }
265   }
266 }