Rework MappedJournalSegmentWriter position tracking
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / MappedJournalSegmentWriter.java
1 /*
2  * Copyright 2017-2022 Open Networking Foundation and others.  All rights reserved.
3  * Copyright (c) 2024 PANTHEON.tech, s.r.o.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 package io.atomix.storage.journal;
18
19 import static io.atomix.storage.journal.SegmentEntry.HEADER_BYTES;
20
21 import com.esotericsoftware.kryo.KryoException;
22 import io.atomix.storage.journal.index.JournalIndex;
23 import java.io.IOException;
24 import java.nio.BufferOverflowException;
25 import java.nio.ByteBuffer;
26 import java.nio.MappedByteBuffer;
27 import java.nio.channels.FileChannel;
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   private int currentPosition;
52
53   MappedJournalSegmentWriter(
54       final FileChannel channel,
55       final JournalSegment<E> segment,
56       final int maxEntrySize,
57       final JournalIndex index,
58       final JournalSerdes namespace) {
59     super(channel, segment, maxEntrySize, index, namespace);
60     mappedBuffer = mapBuffer(channel, maxSegmentSize);
61     buffer = mappedBuffer.slice();
62     reset(0);
63   }
64
65   MappedJournalSegmentWriter(final JournalSegmentWriter<E> previous, final int position) {
66     super(previous);
67     mappedBuffer = mapBuffer(channel, maxSegmentSize);
68     buffer = mappedBuffer.slice();
69     currentPosition = position;
70     lastEntry = previous.getLastEntry();
71   }
72
73   private static @NonNull MappedByteBuffer mapBuffer(final FileChannel channel, final int maxSegmentSize) {
74     try {
75       return channel.map(FileChannel.MapMode.READ_WRITE, 0, maxSegmentSize);
76     } catch (IOException e) {
77       throw new StorageException(e);
78     }
79   }
80
81   @Override
82   @NonNull MappedByteBuffer buffer() {
83     return mappedBuffer;
84   }
85
86   @Override
87   MappedJournalSegmentWriter<E> toMapped() {
88     return this;
89   }
90
91   @Override
92   DiskJournalSegmentWriter<E> toFileChannel() {
93     close();
94     return new DiskJournalSegmentWriter<>(this, currentPosition);
95   }
96
97   @Override
98   void reset(final long index) {
99     long nextIndex = firstIndex;
100
101     // Clear the buffer indexes.
102     currentPosition = JournalSegmentDescriptor.BYTES;
103
104     int length = buffer.getInt(currentPosition);
105
106     // If the length is non-zero, read the entry.
107     while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
108
109       // Read the checksum of the entry.
110       final long checksum = buffer.getInt(currentPosition + Integer.BYTES);
111
112       // Slice off the entry's bytes
113       final var entryBytes = buffer.slice(currentPosition + SegmentEntry.HEADER_BYTES, length);
114
115       // Compute the checksum for the entry bytes.
116       final var crc32 = new CRC32();
117       crc32.update(entryBytes);
118
119       // If the stored checksum does not equal the computed checksum, do not proceed further
120       if (checksum != (int) crc32.getValue()) {
121           break;
122       }
123
124       entryBytes.rewind();
125       final E entry = namespace.deserialize(entryBytes);
126       lastEntry = new Indexed<>(nextIndex, entry, length);
127       this.index.index(nextIndex, currentPosition);
128       nextIndex++;
129
130       // Update the current position for indexing.
131       currentPosition = currentPosition + SegmentEntry.HEADER_BYTES + length;
132
133       if (currentPosition + SegmentEntry.HEADER_BYTES >= maxSegmentSize) {
134           break;
135       }
136       length = buffer.getInt(currentPosition);
137     }
138   }
139
140   @Override
141   Indexed<E> getLastEntry() {
142     return lastEntry;
143   }
144
145   @Override
146   @SuppressWarnings("unchecked")
147   <T extends E> Indexed<T> append(final T entry) {
148     // Store the entry index.
149     final long index = getNextIndex();
150
151     // Serialize the entry.
152     final int bodyPosition = currentPosition + HEADER_BYTES;
153     final int avail = maxSegmentSize - bodyPosition;
154     if (avail < 0) {
155       throw new BufferOverflowException();
156     }
157
158     final var entryBytes = buffer.slice(bodyPosition, Math.min(avail, maxEntrySize));
159     try {
160       namespace.serialize(entry, entryBytes);
161     } catch (KryoException e) {
162       if (entryBytes.capacity() != maxEntrySize) {
163         // We have not provided enough capacity, signal to roll to next segment
164         throw new BufferOverflowException();
165       }
166
167       // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
168       throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
169     }
170
171     final int length = entryBytes.position();
172
173     // Compute the checksum for the entry.
174     final var crc32 = new CRC32();
175     crc32.update(entryBytes.flip());
176
177     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
178     buffer.putInt(currentPosition, length).putInt(currentPosition + Integer.BYTES, (int) crc32.getValue());
179
180     // Update the last entry with the correct index/term/length.
181     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
182     lastEntry = indexedEntry;
183     this.index.index(index, currentPosition);
184
185     currentPosition = currentPosition + HEADER_BYTES + length;
186     return (Indexed<T>) indexedEntry;
187   }
188
189   @Override
190   void truncate(final long index) {
191     // If the index is greater than or equal to the last index, skip the truncate.
192     if (index >= getLastIndex()) {
193       return;
194     }
195
196     // Reset the last entry.
197     lastEntry = null;
198
199     // Truncate the index.
200     this.index.truncate(index);
201
202     if (index < firstIndex) {
203       // Reset the writer to the first entry.
204       currentPosition = JournalSegmentDescriptor.BYTES;
205     } else {
206       // Reset the writer to the given index.
207       reset(index);
208     }
209
210     // Zero the entry header at current buffer position.
211     // Note: we issue a single putLong() instead of two putInt()s.
212     buffer.putLong(currentPosition, 0L);
213   }
214
215   @Override
216   void flush() {
217     mappedBuffer.force();
218   }
219
220   @Override
221   void close() {
222     flush();
223     try {
224       BufferCleaner.freeBuffer(mappedBuffer);
225     } catch (IOException e) {
226       throw new StorageException(e);
227     }
228   }
229 }