d096b33fd88846eb3d4bd57f461cf963182ec66c
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / JournalSegmentFile.java
1 /*
2  * Copyright 2015-2022 Open Networking Foundation and others.  All rights reserved.
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.google.common.base.MoreObjects;
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.RandomAccessFile;
24 import java.nio.ByteBuffer;
25 import java.nio.channels.FileChannel;
26 import java.nio.file.Path;
27 import org.eclipse.jdt.annotation.NonNull;
28
29 /**
30  * Segment file utility.
31  *
32  * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
33  */
34 final class JournalSegmentFile {
35     private static final char PART_SEPARATOR = '-';
36     private static final char EXTENSION_SEPARATOR = '.';
37     private static final String EXTENSION = "log";
38     /**
39      * Just do not bother with IO smaller than this many bytes.
40      */
41     private static final int MIN_IO_SIZE = 8192;
42
43     private final @NonNull JournalSegmentDescriptor descriptor;
44     private final @NonNull Path path;
45
46     private final RandomAccessFile file;
47
48     private JournalSegmentFile(final Path path, final JournalSegmentDescriptor descriptor,
49             final RandomAccessFile file) {
50         this.path = requireNonNull(path);
51         this.descriptor = requireNonNull(descriptor);
52         this.file = requireNonNull(file);
53     }
54
55     static @NonNull JournalSegmentFile createNew(final String name, final File directory,
56             final JournalSegmentDescriptor descriptor) throws IOException {
57         final var file = createSegmentFile(name, directory, descriptor.id());
58         final var raf = new RandomAccessFile(file, "rw");
59         try {
60             raf.setLength(descriptor.maxSegmentSize());
61             raf.write(descriptor.toArray());
62         } catch (IOException e) {
63             raf.close();
64             throw e;
65         }
66         return new JournalSegmentFile(file.toPath(), descriptor, raf);
67     }
68
69     static @NonNull JournalSegmentFile openExisting(final Path path) throws IOException {
70         final var raf = new RandomAccessFile(path.toFile(), "rw");
71         final JournalSegmentDescriptor descriptor;
72         try {
73             // read the descriptor
74             descriptor = JournalSegmentDescriptor.readFrom(raf.getChannel());
75         } catch (IOException e) {
76             raf.close();
77             throw e;
78         }
79         return new JournalSegmentFile(path, descriptor, raf);
80     }
81
82     /**
83      * Returns the segment file.
84      *
85      * @return The segment file.
86      */
87     @NonNull Path path() {
88         return path;
89     }
90
91     /**
92      * Returns the segment version.
93      *
94      * @return the segment version
95      */
96     int version() {
97         return descriptor.version();
98     }
99
100     /**
101      * Returns the segment identifier.
102      *
103      * @return the segment identifier
104      */
105     long segmentId() {
106         return descriptor.id();
107     }
108
109     /**
110      * Returns the index of first entry stored in this file.
111      *
112      * @return the index of first entry stored in this file
113      */
114     long firstIndex() {
115         return descriptor.index();
116     }
117
118     int maxSize() {
119         return descriptor.maxSegmentSize();
120     }
121
122     int size() throws IOException {
123         return (int) file.length();
124     }
125
126     FileChannel channel() {
127         return file.getChannel();
128     }
129
130     void close() throws IOException {
131         file.close();
132     }
133
134     ByteBuffer allocateBuffer(final int maxEntrySize) {
135         return ByteBuffer.allocate(chooseBufferSize(maxEntrySize));
136     }
137
138     @Override
139     public String toString() {
140         return MoreObjects.toStringHelper(this).add("path", path).add("descriptor", descriptor).toString();
141     }
142
143     private int chooseBufferSize(final int maxEntrySize) {
144         final int maxSegmentSize = maxSize();
145         if (maxSegmentSize <= MIN_IO_SIZE) {
146             // just buffer the entire segment
147             return maxSegmentSize;
148         }
149
150         // one full entry plus its header, or MIN_IO_SIZE, which benefits the read of many small entries
151         final int minBufferSize = maxEntrySize + SegmentEntry.HEADER_BYTES;
152         return minBufferSize <= MIN_IO_SIZE ? MIN_IO_SIZE : minBufferSize;
153     }
154
155     /**
156      * Returns a boolean value indicating whether the given file appears to be a parsable segment file.
157      *
158      * @throws NullPointerException if {@code file} is null
159      */
160     public static boolean isSegmentFile(final String name, final File file) {
161         return isSegmentFile(name, file.getName());
162     }
163
164     /**
165      * Returns a boolean value indicating whether the given file appears to be a parsable segment file.
166      *
167      * @param journalName the name of the journal
168      * @param fileName the name of the file to check
169      * @throws NullPointerException if {@code file} is null
170      */
171     public static boolean isSegmentFile(final String journalName, final String fileName) {
172         requireNonNull(journalName, "journalName cannot be null");
173         requireNonNull(fileName, "fileName cannot be null");
174
175         int partSeparator = fileName.lastIndexOf(PART_SEPARATOR);
176         int extensionSeparator = fileName.lastIndexOf(EXTENSION_SEPARATOR);
177
178         if (extensionSeparator == -1 || partSeparator == -1 || extensionSeparator < partSeparator
179             || !fileName.endsWith(EXTENSION)) {
180             return false;
181         }
182
183         for (int i = partSeparator + 1; i < extensionSeparator; i++) {
184             if (!Character.isDigit(fileName.charAt(i))) {
185                 return false;
186             }
187         }
188
189         return fileName.startsWith(journalName);
190     }
191
192     /**
193      * Creates a segment file for the given directory, log name, segment ID, and segment version.
194      */
195     static File createSegmentFile(final String name, final File directory, final long id) {
196         return new File(directory, String.format("%s-%d.log", requireNonNull(name, "name cannot be null"), id));
197     }
198 }