|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. 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 | + |
| 18 | +package org.apache.ozone.rocksdb.util; |
| 19 | + |
| 20 | +import jakarta.annotation.Nonnull; |
| 21 | +import java.io.Closeable; |
| 22 | +import java.io.IOException; |
| 23 | +import java.io.UncheckedIOException; |
| 24 | +import java.util.Comparator; |
| 25 | +import java.util.HashMap; |
| 26 | +import java.util.Iterator; |
| 27 | +import java.util.List; |
| 28 | +import java.util.Map; |
| 29 | +import java.util.NoSuchElementException; |
| 30 | +import java.util.Objects; |
| 31 | +import java.util.PriorityQueue; |
| 32 | +import java.util.stream.Collectors; |
| 33 | +import java.util.stream.IntStream; |
| 34 | +import org.apache.hadoop.hdds.utils.db.RocksDatabaseException; |
| 35 | +import org.apache.hadoop.ozone.util.ClosableIterator; |
| 36 | +import org.rocksdb.RocksDBException; |
| 37 | + |
| 38 | +/** |
| 39 | + * An abstract class that provides functionality to merge elements from multiple sorted iterators |
| 40 | + * using a min-heap. The {@code MinHeapMergeIterator} ensures the merged output is in sorted order |
| 41 | + * by repeatedly polling the smallest element from the heap of iterators. |
| 42 | + * |
| 43 | + * @param <K> the type of keys being merged, must be {@link Comparable} |
| 44 | + * @param <I> the type of iterators being used, must extend {@link Iterator} and implement {@link Closeable} |
| 45 | + * @param <V> the type of the final merged output |
| 46 | + */ |
| 47 | +public abstract class MinHeapMergeIterator<K, I extends Iterator<K> & Closeable, V> |
| 48 | + implements ClosableIterator<V> { |
| 49 | + private final PriorityQueue<HeapEntry<K>> minHeap; |
| 50 | + private final Map<Integer, K> keys; |
| 51 | + private final List<I> iterators; |
| 52 | + private boolean initialized; |
| 53 | + private final Comparator<K> comparator; |
| 54 | + |
| 55 | + public MinHeapMergeIterator(int numberOfIterators, Comparator<K> comparator) { |
| 56 | + this.minHeap = new PriorityQueue<>(Math.max(numberOfIterators, 1)); |
| 57 | + keys = new HashMap<>(numberOfIterators); |
| 58 | + iterators = IntStream.range(0, numberOfIterators).mapToObj(i -> (I) null).collect(Collectors.toList()); |
| 59 | + this.initialized = false; |
| 60 | + this.comparator = comparator; |
| 61 | + } |
| 62 | + |
| 63 | + protected abstract I getIterator(int idx) throws RocksDBException, IOException; |
| 64 | + |
| 65 | + private boolean initHeap() throws IOException, RocksDBException { |
| 66 | + if (initialized) { |
| 67 | + return false; |
| 68 | + } |
| 69 | + initialized = true; |
| 70 | + int count = 0; |
| 71 | + try { |
| 72 | + for (int idx = 0; idx < iterators.size(); idx++) { |
| 73 | + I itr = getIterator(idx); |
| 74 | + iterators.set(idx, itr); |
| 75 | + HeapEntry<K> entry = new HeapEntry<>(idx, itr, comparator); |
| 76 | + if (entry.getCurrentKey() != null) { |
| 77 | + minHeap.add(entry); |
| 78 | + count++; |
| 79 | + } else { |
| 80 | + // No valid entries, close the iterator. |
| 81 | + closeItrAtIndex(idx); |
| 82 | + } |
| 83 | + } |
| 84 | + } catch (IOException | RocksDBException e) { |
| 85 | + close(); |
| 86 | + throw e; |
| 87 | + } |
| 88 | + return count > 0; |
| 89 | + } |
| 90 | + |
| 91 | + @Override |
| 92 | + public boolean hasNext() { |
| 93 | + try { |
| 94 | + return !minHeap.isEmpty() || initHeap(); |
| 95 | + } catch (IOException e) { |
| 96 | + throw new UncheckedIOException(e); |
| 97 | + } catch (RocksDBException e) { |
| 98 | + throw new UncheckedIOException(new RocksDatabaseException("Error while initializing iterator ", e)); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + protected abstract V merge(Map<Integer, K> keysToMerge); |
| 103 | + |
| 104 | + @Override |
| 105 | + public V next() { |
| 106 | + if (!hasNext()) { |
| 107 | + throw new NoSuchElementException("No more elements found."); |
| 108 | + } |
| 109 | + |
| 110 | + assert minHeap.peek() != null; |
| 111 | + // Get current key from heap |
| 112 | + K currentKey = minHeap.peek().getCurrentKey(); |
| 113 | + // Clear the keys list by setting all entries to null. |
| 114 | + keys.clear(); |
| 115 | + // Advance all entries with the same key (from different files) |
| 116 | + while (!minHeap.isEmpty() && Objects.equals(minHeap.peek().getCurrentKey(), currentKey)) { |
| 117 | + HeapEntry<K> entry = minHeap.poll(); |
| 118 | + int idx = entry.index; |
| 119 | + // Set the key for the current entry in the keys list. |
| 120 | + keys.put(idx, entry.getCurrentKey()); |
| 121 | + if (entry.advance()) { |
| 122 | + minHeap.offer(entry); |
| 123 | + } else { |
| 124 | + // Iterator is exhausted, close it to prevent resource leak |
| 125 | + try { |
| 126 | + closeItrAtIndex(idx); |
| 127 | + } catch (IOException e) { |
| 128 | + throw new UncheckedIOException(e); |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + return merge(keys); |
| 133 | + } |
| 134 | + |
| 135 | + private void closeItrAtIndex(int idx) throws IOException { |
| 136 | + if (iterators.get(idx) != null) { |
| 137 | + iterators.get(idx).close(); |
| 138 | + iterators.set(idx, null); |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + @Override |
| 143 | + public void close() { |
| 144 | + IOException exception = null; |
| 145 | + for (int idx = 0; idx < iterators.size(); idx++) { |
| 146 | + try { |
| 147 | + closeItrAtIndex(idx); |
| 148 | + } catch (IOException e) { |
| 149 | + exception = e; |
| 150 | + } |
| 151 | + } |
| 152 | + if (exception != null) { |
| 153 | + throw new UncheckedIOException(exception); |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + /** |
| 158 | + * A wrapper class that holds an iterator and its current value for heap operations. |
| 159 | + */ |
| 160 | + private static final class HeapEntry<T> implements Comparable<HeapEntry<T>> { |
| 161 | + private final int index; |
| 162 | + private final Iterator<T> iterator; |
| 163 | + private T currentKey; |
| 164 | + private Comparator<T> comparator; |
| 165 | + |
| 166 | + private HeapEntry(int index, Iterator<T> iterator, Comparator<T> comparator) { |
| 167 | + this.iterator = iterator; |
| 168 | + this.index = index; |
| 169 | + this.comparator = comparator; |
| 170 | + advance(); |
| 171 | + } |
| 172 | + |
| 173 | + private boolean advance() { |
| 174 | + if (iterator.hasNext()) { |
| 175 | + currentKey = iterator.next(); |
| 176 | + return true; |
| 177 | + } else { |
| 178 | + currentKey = null; |
| 179 | + return false; |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + private T getCurrentKey() { |
| 184 | + return currentKey; |
| 185 | + } |
| 186 | + |
| 187 | + @Override |
| 188 | + public int compareTo(@Nonnull HeapEntry<T> other) { |
| 189 | + return Comparator.comparing(HeapEntry<T>::getCurrentKey, this.comparator).compare(this, other); |
| 190 | + } |
| 191 | + |
| 192 | + @Override |
| 193 | + @SuppressWarnings("unchecked") |
| 194 | + public boolean equals(Object obj) { |
| 195 | + if (this == obj) { |
| 196 | + return true; |
| 197 | + } |
| 198 | + if (obj == null || getClass() != obj.getClass()) { |
| 199 | + return false; |
| 200 | + } |
| 201 | + |
| 202 | + HeapEntry<T> other = (HeapEntry<T>) obj; |
| 203 | + return this.compareTo(other) == 0; |
| 204 | + } |
| 205 | + |
| 206 | + @Override |
| 207 | + public int hashCode() { |
| 208 | + return currentKey.hashCode(); |
| 209 | + } |
| 210 | + } |
| 211 | +} |
0 commit comments