|
| 1 | +/* |
| 2 | + * Copyright OpenSearch Contributors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package org.opensearch.knn.index.codec.nativeindex.remote; |
| 7 | + |
| 8 | +import lombok.AllArgsConstructor; |
| 9 | +import lombok.extern.log4j.Log4j2; |
| 10 | +import org.opensearch.action.LatchedActionListener; |
| 11 | +import org.opensearch.common.CheckedTriFunction; |
| 12 | +import org.opensearch.common.StreamContext; |
| 13 | +import org.opensearch.common.blobstore.AsyncMultiStreamBlobContainer; |
| 14 | +import org.opensearch.common.blobstore.BlobContainer; |
| 15 | +import org.opensearch.common.blobstore.BlobPath; |
| 16 | +import org.opensearch.common.blobstore.stream.write.WriteContext; |
| 17 | +import org.opensearch.common.blobstore.stream.write.WritePriority; |
| 18 | +import org.opensearch.common.io.InputStreamContainer; |
| 19 | +import org.opensearch.core.action.ActionListener; |
| 20 | +import org.opensearch.index.IndexSettings; |
| 21 | +import org.opensearch.knn.index.VectorDataType; |
| 22 | +import org.opensearch.knn.index.vectorvalues.KNNVectorValues; |
| 23 | +import org.opensearch.repositories.blobstore.BlobStoreRepository; |
| 24 | + |
| 25 | +import java.io.BufferedInputStream; |
| 26 | +import java.io.IOException; |
| 27 | +import java.io.InputStream; |
| 28 | +import java.util.concurrent.CountDownLatch; |
| 29 | +import java.util.concurrent.atomic.AtomicReference; |
| 30 | +import java.util.function.Supplier; |
| 31 | + |
| 32 | +import static org.opensearch.knn.index.codec.nativeindex.remote.RemoteIndexBuildStrategy.DOC_ID_FILE_EXTENSION; |
| 33 | +import static org.opensearch.knn.index.codec.nativeindex.remote.RemoteIndexBuildStrategy.VECTORS_PATH; |
| 34 | +import static org.opensearch.knn.index.codec.nativeindex.remote.RemoteIndexBuildStrategy.VECTOR_BLOB_FILE_EXTENSION; |
| 35 | +import static org.opensearch.knn.index.codec.util.KNNCodecUtil.initializeVectorValues; |
| 36 | + |
| 37 | +@Log4j2 |
| 38 | +@AllArgsConstructor |
| 39 | +public class DefaultVectorRepositoryAccessor implements VectorRepositoryAccessor { |
| 40 | + private final BlobStoreRepository repository; |
| 41 | + private final IndexSettings indexSettings; |
| 42 | + |
| 43 | + /** |
| 44 | + * If the repository implements {@link AsyncMultiStreamBlobContainer}, then parallel uploads will be used. Parallel uploads are backed by a {@link WriteContext}, for which we have a custom |
| 45 | + * {@link org.opensearch.common.blobstore.stream.write.StreamContextSupplier} implementation. |
| 46 | + * |
| 47 | + * @see DefaultVectorRepositoryAccessor#getStreamContext |
| 48 | + * @see DefaultVectorRepositoryAccessor#getTransferPartStreamSupplier |
| 49 | + * |
| 50 | + * @param blobName Base name of the blobs we are writing, excluding file extensions |
| 51 | + * @param totalLiveDocs Number of documents we are processing. This is used to compute the size of the blob we are writing |
| 52 | + * @param vectorDataType Data type of the vector (FLOAT, BYTE, BINARY) |
| 53 | + * @param knnVectorValuesSupplier Supplier for {@link KNNVectorValues} |
| 54 | + * @throws IOException |
| 55 | + * @throws InterruptedException |
| 56 | + */ |
| 57 | + @Override |
| 58 | + public void writeToRepository( |
| 59 | + String blobName, |
| 60 | + int totalLiveDocs, |
| 61 | + VectorDataType vectorDataType, |
| 62 | + Supplier<KNNVectorValues<?>> knnVectorValuesSupplier |
| 63 | + ) throws IOException, InterruptedException { |
| 64 | + assert repository != null; |
| 65 | + // Get the blob container based on blobName and the repo base path. This is where the blobs will be written to. |
| 66 | + BlobPath path = repository.basePath().add(indexSettings.getUUID() + VECTORS_PATH); |
| 67 | + BlobContainer blobContainer = repository.blobStore().blobContainer(path); |
| 68 | + |
| 69 | + KNNVectorValues<?> knnVectorValues = knnVectorValuesSupplier.get(); |
| 70 | + initializeVectorValues(knnVectorValues); |
| 71 | + long vectorBlobLength = (long) knnVectorValues.bytesPerVector() * totalLiveDocs; |
| 72 | + |
| 73 | + if (blobContainer instanceof AsyncMultiStreamBlobContainer) { |
| 74 | + // First initiate vectors upload |
| 75 | + log.debug("Repository {} Supports Parallel Blob Upload", repository); |
| 76 | + // WriteContext is the main entry point into asyncBlobUpload. It stores all of our upload configurations, analogous to |
| 77 | + // BuildIndexParams |
| 78 | + WriteContext writeContext = new WriteContext.Builder().fileName(blobName + VECTOR_BLOB_FILE_EXTENSION) |
| 79 | + .streamContextSupplier((partSize) -> getStreamContext(partSize, vectorBlobLength, knnVectorValuesSupplier, vectorDataType)) |
| 80 | + .fileSize(vectorBlobLength) |
| 81 | + .failIfAlreadyExists(true) |
| 82 | + .writePriority(WritePriority.NORMAL) |
| 83 | + // TODO: Checksum implementations -- It is difficult to calculate a checksum on the knnVectorValues as |
| 84 | + // there is no underlying file upon which we can create the checksum. We should be able to create a |
| 85 | + // checksum still by iterating through once, however this will be an expensive operation. |
| 86 | + .uploadFinalizer((bool) -> {}) |
| 87 | + .doRemoteDataIntegrityCheck(false) |
| 88 | + .expectedChecksum(null) |
| 89 | + .build(); |
| 90 | + |
| 91 | + AtomicReference<Exception> exception = new AtomicReference<>(); |
| 92 | + final CountDownLatch latch = new CountDownLatch(1); |
| 93 | + ((AsyncMultiStreamBlobContainer) blobContainer).asyncBlobUpload( |
| 94 | + writeContext, |
| 95 | + new LatchedActionListener<>(new ActionListener<>() { |
| 96 | + @Override |
| 97 | + public void onResponse(Void unused) { |
| 98 | + log.debug( |
| 99 | + "Parallel vector upload succeeded for blob {} with size {}", |
| 100 | + blobName + VECTOR_BLOB_FILE_EXTENSION, |
| 101 | + vectorBlobLength |
| 102 | + ); |
| 103 | + } |
| 104 | + |
| 105 | + @Override |
| 106 | + public void onFailure(Exception e) { |
| 107 | + log.error( |
| 108 | + "Parallel vector upload failed for blob {} with size {}", |
| 109 | + blobName + VECTOR_BLOB_FILE_EXTENSION, |
| 110 | + vectorBlobLength, |
| 111 | + e |
| 112 | + ); |
| 113 | + exception.set(e); |
| 114 | + } |
| 115 | + }, latch) |
| 116 | + ); |
| 117 | + |
| 118 | + // Then upload doc id blob before waiting on vector uploads |
| 119 | + // TODO: We wrap with a BufferedInputStream to support retries. We can tune this buffer size to optimize performance. |
| 120 | + // Note: We do not use the parallel upload API here as the doc id blob will be much smaller than the vector blob |
| 121 | + writeDocIds(knnVectorValuesSupplier.get(), vectorBlobLength, totalLiveDocs, blobName, blobContainer); |
| 122 | + latch.await(); |
| 123 | + if (exception.get() != null) { |
| 124 | + throw new IOException(exception.get()); |
| 125 | + } |
| 126 | + } else { |
| 127 | + log.debug("Repository {} Does Not Support Parallel Blob Upload", repository); |
| 128 | + // Write Vectors |
| 129 | + InputStream vectorStream = new BufferedInputStream(new VectorValuesInputStream(knnVectorValuesSupplier.get(), vectorDataType)); |
| 130 | + log.debug("Writing {} bytes for {} docs to {}", vectorBlobLength, totalLiveDocs, blobName + VECTOR_BLOB_FILE_EXTENSION); |
| 131 | + blobContainer.writeBlob(blobName + VECTOR_BLOB_FILE_EXTENSION, vectorStream, vectorBlobLength, true); |
| 132 | + // Then write doc ids |
| 133 | + writeDocIds(knnVectorValuesSupplier.get(), vectorBlobLength, totalLiveDocs, blobName, blobContainer); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * Helper method for uploading doc ids to repository, as it's re-used in both parallel and sequential upload cases |
| 139 | + * @param knnVectorValues |
| 140 | + * @param vectorBlobLength |
| 141 | + * @param totalLiveDocs |
| 142 | + * @param blobName |
| 143 | + * @param blobContainer |
| 144 | + * @throws IOException |
| 145 | + */ |
| 146 | + private void writeDocIds( |
| 147 | + KNNVectorValues<?> knnVectorValues, |
| 148 | + long vectorBlobLength, |
| 149 | + long totalLiveDocs, |
| 150 | + String blobName, |
| 151 | + BlobContainer blobContainer |
| 152 | + ) throws IOException { |
| 153 | + InputStream docStream = new BufferedInputStream(new DocIdInputStream(knnVectorValues)); |
| 154 | + log.debug( |
| 155 | + "Writing {} bytes for {} docs ids to {}", |
| 156 | + vectorBlobLength, |
| 157 | + totalLiveDocs * Integer.BYTES, |
| 158 | + blobName + DOC_ID_FILE_EXTENSION |
| 159 | + ); |
| 160 | + blobContainer.writeBlob(blobName + DOC_ID_FILE_EXTENSION, docStream, totalLiveDocs * Integer.BYTES, true); |
| 161 | + } |
| 162 | + |
| 163 | + /** |
| 164 | + * Returns a {@link org.opensearch.common.StreamContext}. Intended to be invoked as a {@link org.opensearch.common.blobstore.stream.write.StreamContextSupplier}, |
| 165 | + * which takes the partSize determined by the repository implementation and calculates the number of parts as well as handles the last part of the stream. |
| 166 | + * |
| 167 | + * @see DefaultVectorRepositoryAccessor#getTransferPartStreamSupplier |
| 168 | + * |
| 169 | + * @param partSize Size of each InputStream to be uploaded in parallel. Provided by repository implementation |
| 170 | + * @param vectorBlobLength Total size of the vectors across all InputStreams |
| 171 | + * @param knnVectorValuesSupplier Supplier for {@link KNNVectorValues} |
| 172 | + * @param vectorDataType Data type of the vector (FLOAT, BYTE, BINARY) |
| 173 | + * @return a {@link org.opensearch.common.StreamContext} with a function that will create {@link InputStream}s of {@param partSize} |
| 174 | + */ |
| 175 | + private StreamContext getStreamContext( |
| 176 | + long partSize, |
| 177 | + long vectorBlobLength, |
| 178 | + Supplier<KNNVectorValues<?>> knnVectorValuesSupplier, |
| 179 | + VectorDataType vectorDataType |
| 180 | + ) { |
| 181 | + long lastPartSize = (vectorBlobLength % partSize) != 0 ? vectorBlobLength % partSize : partSize; |
| 182 | + int numberOfParts = (int) ((vectorBlobLength % partSize) == 0 ? vectorBlobLength / partSize : (vectorBlobLength / partSize) + 1); |
| 183 | + return new StreamContext( |
| 184 | + getTransferPartStreamSupplier(knnVectorValuesSupplier, vectorDataType), |
| 185 | + partSize, |
| 186 | + lastPartSize, |
| 187 | + numberOfParts |
| 188 | + ); |
| 189 | + } |
| 190 | + |
| 191 | + /** |
| 192 | + * This method handles creating {@link VectorValuesInputStream}s based on the part number, the requested size of the stream part, and the position that the stream starts at within the underlying {@link KNNVectorValues} |
| 193 | + * |
| 194 | + * @param knnVectorValuesSupplier Supplier for {@link KNNVectorValues} |
| 195 | + * @param vectorDataType Data type of the vector (FLOAT, BYTE, BINARY) |
| 196 | + * @return a function with which the repository implementation will use to create {@link VectorValuesInputStream}s of specific sizes and start positions. |
| 197 | + */ |
| 198 | + private CheckedTriFunction<Integer, Long, Long, InputStreamContainer, IOException> getTransferPartStreamSupplier( |
| 199 | + Supplier<KNNVectorValues<?>> knnVectorValuesSupplier, |
| 200 | + VectorDataType vectorDataType |
| 201 | + ) { |
| 202 | + return ((partNo, size, position) -> { |
| 203 | + log.info("Creating InputStream for partNo: {}, size: {}, position: {}", partNo, size, position); |
| 204 | + VectorValuesInputStream vectorValuesInputStream = new VectorValuesInputStream( |
| 205 | + knnVectorValuesSupplier.get(), |
| 206 | + vectorDataType, |
| 207 | + position, |
| 208 | + size |
| 209 | + ); |
| 210 | + return new InputStreamContainer(vectorValuesInputStream, size, position); |
| 211 | + }); |
| 212 | + } |
| 213 | +} |
0 commit comments