Introduce JournalSegmentWriter
[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 static java.util.Objects.requireNonNull;
19
20 import com.esotericsoftware.kryo.KryoException;
21 import io.atomix.storage.journal.index.JournalIndex;
22
23 import java.io.IOException;
24 import java.nio.BufferOverflowException;
25 import java.nio.BufferUnderflowException;
26 import java.nio.ByteBuffer;
27 import java.nio.MappedByteBuffer;
28 import java.util.zip.CRC32;
29 import org.eclipse.jdt.annotation.NonNull;
30
31 /**
32  * Segment writer.
33  * <p>
34  * The format of an entry in the log is as follows:
35  * <ul>
36  * <li>64-bit index</li>
37  * <li>8-bit boolean indicating whether a term change is contained in the entry</li>
38  * <li>64-bit optional term</li>
39  * <li>32-bit signed entry length, including the entry type ID</li>
40  * <li>8-bit signed entry type ID</li>
41  * <li>n-bit entry bytes</li>
42  * </ul>
43  *
44  * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
45  */
46 final class MappedJournalSegmentWriter<E> extends JournalSegmentWriter<E> {
47   private final @NonNull MappedByteBuffer mappedBuffer;
48   private final ByteBuffer buffer;
49
50   private Indexed<E> lastEntry;
51
52   MappedJournalSegmentWriter(
53       MappedByteBuffer buffer,
54       JournalSegment<E> segment,
55       int maxEntrySize,
56       JournalIndex index,
57       JournalSerdes namespace) {
58     super(segment, maxEntrySize, index, namespace);
59     this.mappedBuffer = requireNonNull(buffer);
60     this.buffer = buffer.slice();
61     reset(0);
62   }
63
64   @Override
65   @NonNull MappedByteBuffer buffer() {
66     return mappedBuffer;
67   }
68
69   @Override
70   public void reset(long index) {
71     long nextIndex = firstIndex;
72
73     // Clear the buffer indexes.
74     buffer.position(JournalSegmentDescriptor.BYTES);
75
76     // Record the current buffer position.
77     int position = buffer.position();
78
79     // Read the entry length.
80     buffer.mark();
81
82     try {
83       int length = buffer.getInt();
84
85       // If the length is non-zero, read the entry.
86       while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
87
88         // Read the checksum of the entry.
89         final long checksum = buffer.getInt() & 0xFFFFFFFFL;
90
91         // Slice off the entry's bytes
92         final ByteBuffer entryBytes = buffer.slice();
93         entryBytes.limit(length);
94
95         // Compute the checksum for the entry bytes.
96         final CRC32 crc32 = new CRC32();
97         crc32.update(entryBytes);
98
99         // If the stored checksum does not equal the computed checksum, do not proceed further
100         if (checksum != crc32.getValue()) {
101           break;
102         }
103
104         entryBytes.rewind();
105         final E entry = namespace.deserialize(entryBytes);
106         lastEntry = new Indexed<>(nextIndex, entry, length);
107         this.index.index(nextIndex, position);
108         nextIndex++;
109
110         // Update the current position for indexing.
111         position = buffer.position() + length;
112         buffer.position(position);
113
114         buffer.mark();
115         length = buffer.getInt();
116       }
117
118       // Reset the buffer to the previous mark.
119       buffer.reset();
120     } catch (BufferUnderflowException e) {
121       buffer.reset();
122     }
123   }
124
125   @Override
126   public long getLastIndex() {
127     return lastEntry != null ? lastEntry.index() : segment.index() - 1;
128   }
129
130   @Override
131   public Indexed<E> getLastEntry() {
132     return lastEntry;
133   }
134
135   @Override
136   public long getNextIndex() {
137     if (lastEntry != null) {
138       return lastEntry.index() + 1;
139     } else {
140       return firstIndex;
141     }
142   }
143
144   @Override
145   public void append(Indexed<E> entry) {
146     final long nextIndex = getNextIndex();
147
148     // If the entry's index is greater than the next index in the segment, skip some entries.
149     if (entry.index() > nextIndex) {
150       throw new IndexOutOfBoundsException("Entry index is not sequential");
151     }
152
153     // If the entry's index is less than the next index, truncate the segment.
154     if (entry.index() < nextIndex) {
155       truncate(entry.index() - 1);
156     }
157     append(entry.entry());
158   }
159
160   @Override
161   @SuppressWarnings("unchecked")
162   public <T extends E> Indexed<T> append(T entry) {
163     // Store the entry index.
164     final long index = getNextIndex();
165
166     // Serialize the entry.
167     int position = buffer.position();
168     if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
169       throw new BufferOverflowException();
170     }
171
172     buffer.position(position + Integer.BYTES + Integer.BYTES);
173
174     try {
175       namespace.serialize(entry, buffer);
176     } catch (KryoException e) {
177       throw new BufferOverflowException();
178     }
179
180     final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
181
182     // If the entry length exceeds the maximum entry size then throw an exception.
183     if (length > maxEntrySize) {
184       // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
185       buffer.position(position);
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     buffer.position(position + Integer.BYTES + Integer.BYTES);
192     ByteBuffer slice = buffer.slice();
193     slice.limit(length);
194     crc32.update(slice);
195     final long checksum = crc32.getValue();
196
197     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
198     buffer.position(position);
199     buffer.putInt(length);
200     buffer.putInt((int) checksum);
201     buffer.position(position + Integer.BYTES + Integer.BYTES + length);
202
203     // Update the last entry with the correct index/term/length.
204     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
205     this.lastEntry = indexedEntry;
206     this.index.index(index, position);
207     return (Indexed<T>) indexedEntry;
208   }
209
210
211   @Override
212   public 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     if (index < segment.index()) {
225       // Reset the writer to the first entry.
226       buffer.position(JournalSegmentDescriptor.BYTES);
227     } else {
228       // Reset the writer to the given index.
229       reset(index);
230     }
231
232     // Zero the entry header at current buffer position.
233     int position = buffer.position();
234     // Note: we issue a single putLong() instead of two putInt()s.
235     buffer.putLong(0);
236     buffer.position(position);
237   }
238
239   @Override
240   public void flush() {
241     mappedBuffer.force();
242   }
243
244   @Override
245   public void close() {
246     flush();
247     try {
248       BufferCleaner.freeBuffer(mappedBuffer);
249     } catch (IOException e) {
250       throw new StorageException(e);
251     }
252   }
253 }