Clean up initial FileChannel writer reset's read
[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         // Compute the checksum for the entry bytes.
101         final CRC32 crc32 = new CRC32();
102         ByteBuffer slice = buffer.slice();
103         slice.limit(length);
104         crc32.update(slice);
105
106         // If the stored checksum equals the computed checksum, return the entry.
107         if (checksum == crc32.getValue()) {
108           slice.rewind();
109           final E entry = namespace.deserialize(slice);
110           lastEntry = new Indexed<>(nextIndex, entry, length);
111           this.index.index(nextIndex, position);
112           nextIndex++;
113         } else {
114           break;
115         }
116
117         // Update the current position for indexing.
118         position = buffer.position() + length;
119         buffer.position(position);
120
121         buffer.mark();
122         length = buffer.getInt();
123       }
124
125       // Reset the buffer to the previous mark.
126       buffer.reset();
127     } catch (BufferUnderflowException e) {
128       buffer.reset();
129     }
130   }
131
132   @Override
133   public long getLastIndex() {
134     return lastEntry != null ? lastEntry.index() : segment.index() - 1;
135   }
136
137   @Override
138   public Indexed<E> getLastEntry() {
139     return lastEntry;
140   }
141
142   @Override
143   public long getNextIndex() {
144     if (lastEntry != null) {
145       return lastEntry.index() + 1;
146     } else {
147       return firstIndex;
148     }
149   }
150
151   @Override
152   public void append(Indexed<E> entry) {
153     final long nextIndex = getNextIndex();
154
155     // If the entry's index is greater than the next index in the segment, skip some entries.
156     if (entry.index() > nextIndex) {
157       throw new IndexOutOfBoundsException("Entry index is not sequential");
158     }
159
160     // If the entry's index is less than the next index, truncate the segment.
161     if (entry.index() < nextIndex) {
162       truncate(entry.index() - 1);
163     }
164     append(entry.entry());
165   }
166
167   @Override
168   @SuppressWarnings("unchecked")
169   public <T extends E> Indexed<T> append(T entry) {
170     // Store the entry index.
171     final long index = getNextIndex();
172
173     // Serialize the entry.
174     int position = buffer.position();
175     if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
176       throw new BufferOverflowException();
177     }
178
179     buffer.position(position + Integer.BYTES + Integer.BYTES);
180
181     try {
182       namespace.serialize(entry, buffer);
183     } catch (KryoException e) {
184       throw new BufferOverflowException();
185     }
186
187     final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
188
189     // If the entry length exceeds the maximum entry size then throw an exception.
190     if (length > maxEntrySize) {
191       // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
192       buffer.position(position);
193       throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
194     }
195
196     // Compute the checksum for the entry.
197     final CRC32 crc32 = new CRC32();
198     buffer.position(position + Integer.BYTES + Integer.BYTES);
199     ByteBuffer slice = buffer.slice();
200     slice.limit(length);
201     crc32.update(slice);
202     final long checksum = crc32.getValue();
203
204     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
205     buffer.position(position);
206     buffer.putInt(length);
207     buffer.putInt((int) checksum);
208     buffer.position(position + Integer.BYTES + Integer.BYTES + length);
209
210     // Update the last entry with the correct index/term/length.
211     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
212     this.lastEntry = indexedEntry;
213     this.index.index(index, position);
214     return (Indexed<T>) indexedEntry;
215   }
216
217   @Override
218   public void commit(long index) {
219
220   }
221
222   @Override
223   public void truncate(long index) {
224     // If the index is greater than or equal to the last index, skip the truncate.
225     if (index >= getLastIndex()) {
226       return;
227     }
228
229     // Reset the last entry.
230     lastEntry = null;
231
232     // Truncate the index.
233     this.index.truncate(index);
234
235     if (index < segment.index()) {
236       // Reset the writer to the first entry.
237       buffer.position(JournalSegmentDescriptor.BYTES);
238     } else {
239       // Reset the writer to the given index.
240       reset(index);
241     }
242
243     // Zero the entry header at current buffer position.
244     int position = buffer.position();
245     // Note: we issue a single putLong() instead of two putInt()s.
246     buffer.putLong(0);
247     buffer.position(position);
248   }
249
250   @Override
251   public void flush() {
252     mappedBuffer.force();
253   }
254
255   @Override
256   public void close() {
257     flush();
258     try {
259       BufferCleaner.freeBuffer(mappedBuffer);
260     } catch (IOException e) {
261       throw new StorageException(e);
262     }
263   }
264 }