gerlowskija commented on a change in pull request #39:
URL: https://github.com/apache/solr/pull/39#discussion_r616904467



##########
File path: 
solr/contrib/gcs-repository/src/java/org/apache/solr/gcs/GCSBackupRepository.java
##########
@@ -0,0 +1,466 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.gcs;
+
+import com.google.auth.oauth2.GoogleCredentials;
+import com.google.cloud.ReadChannel;
+import com.google.cloud.WriteChannel;
+import com.google.cloud.storage.Blob;
+import com.google.cloud.storage.BlobId;
+import com.google.cloud.storage.BlobInfo;
+import com.google.cloud.storage.Storage;
+import com.google.cloud.storage.StorageException;
+import com.google.cloud.storage.StorageOptions;
+import org.apache.lucene.codecs.CodecUtil;
+import org.apache.lucene.index.CorruptIndexException;
+import org.apache.lucene.store.BufferedIndexInput;
+import org.apache.lucene.store.ChecksumIndexInput;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.core.DirectoryFactory;
+import org.apache.solr.core.backup.repository.BackupRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.ByteBuffer;
+import java.nio.channels.Channels;
+import java.nio.channels.WritableByteChannel;
+import java.nio.file.FileAlreadyExistsException;
+import java.nio.file.NoSuchFileException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+import static java.net.HttpURLConnection.HTTP_PRECON_FAILED;
+
+/**
+ * {@link BackupRepository} implementation that stores files in Google Cloud 
Storage ("GCS").
+ */
+public class GCSBackupRepository implements BackupRepository {
+    private static final Logger log = 
LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+    private static final int LARGE_BLOB_THRESHOLD_BYTE_SIZE = 5 * 1024 * 1024;
+    private static final int BUFFER_SIZE = 16 * 1024 * 1024;
+    protected Storage storage;
+
+    private NamedList<Object> config = null;
+    protected String bucketName = null;
+    protected String credentialPath = null;
+    protected StorageOptions.Builder storageOptionsBuilder = null;
+
+    protected Storage initStorage() {
+        if (storage != null)
+            return storage;
+
+        try {
+            if (credentialPath == null) {
+                throw new 
IllegalArgumentException(GCSConfigParser.missingCredentialErrorMsg());
+            }
+
+            log.info("Creating GCS client using credential at {}", 
credentialPath);
+            GoogleCredentials credential = GoogleCredentials.fromStream(new 
FileInputStream(credentialPath));
+            storageOptionsBuilder.setCredentials(credential);
+            storage = storageOptionsBuilder.build().getService();
+        } catch (IOException e) {
+            throw new IllegalStateException(e);
+        }
+        return storage;
+    }
+
+    @Override
+    @SuppressWarnings({"rawtypes", "unchecked"})
+    public void init(NamedList args) {
+        this.config = (NamedList<Object>) args;
+        final GCSConfigParser configReader = new GCSConfigParser();
+        final GCSConfigParser.GCSConfig parsedConfig = 
configReader.parseConfiguration(config);
+
+        this.bucketName = parsedConfig.getBucketName();
+        this.credentialPath = parsedConfig.getCredentialPath();
+        this.storageOptionsBuilder = parsedConfig.getStorageOptionsBuilder();
+
+        initStorage();
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public <T> T getConfigProperty(String name) {
+        return (T) this.config.get(name);
+    }
+
+    @Override
+    public URI createURI(String location) {
+        Objects.requireNonNull(location);
+
+        URI result;
+        try {
+            result = new URI(location);
+        } catch (URISyntaxException e) {
+            throw new IllegalArgumentException("Error on creating URI", e);
+        }
+
+        return result;
+    }
+
+    @Override
+    public URI resolve(URI baseUri, String... pathComponents) {
+        StringBuilder builder = new StringBuilder(baseUri.toString());
+        for (String path : pathComponents) {
+            if (path != null && !path.isEmpty()) {
+                if (builder.charAt(builder.length()-1) != '/') {
+                    builder.append('/');
+                }
+                builder.append(path);
+            }
+        }
+
+        return URI.create(builder.toString());
+    }
+
+    @Override
+    public boolean exists(URI path) throws IOException {
+        if (path.toString().equals(getConfigProperty("location"))) {
+            return true;
+        }
+
+        if (path.toString().endsWith("/")) {
+            return storage.get(bucketName, path.toString(), 
Storage.BlobGetOption.fields()) != null;
+        } else {
+            final String filePath = path.toString();
+            final String directoryPath = path.toString() + "/";
+            return storage.get(bucketName, filePath, 
Storage.BlobGetOption.fields()) != null ||
+                    storage.get(bucketName, directoryPath, 
Storage.BlobGetOption.fields()) != null;
+        }
+
+    }
+
+    @Override
+    public PathType getPathType(URI path) throws IOException {
+        if (path.toString().endsWith("/"))
+            return PathType.DIRECTORY;
+
+        Blob blob = storage.get(bucketName, path.toString()+"/", 
Storage.BlobGetOption.fields());
+        if (blob != null)
+            return PathType.DIRECTORY;
+
+        return PathType.FILE;
+    }
+
+    private String toBlobName(URI path) {
+        return path.toString();
+    }
+
+    @Override
+    public String[] listAll(URI path) throws IOException {
+        String blobName = path.toString();
+        if (!blobName.endsWith("/"))
+            blobName += "/";
+
+        final String pathStr = blobName;
+        final LinkedList<String> result = new LinkedList<>();
+        storage.list(
+                bucketName,
+                Storage.BlobListOption.currentDirectory(),
+                Storage.BlobListOption.prefix(pathStr),
+                Storage.BlobListOption.fields())
+        .iterateAll().forEach(
+                blob -> {
+                    assert blob.getName().startsWith(pathStr);
+                    final String suffixName = 
blob.getName().substring(pathStr.length());
+                    if (!suffixName.isEmpty()) {
+                        // Remove trailing '/' if present
+                        if (suffixName.endsWith("/")) {
+                            result.add(suffixName.substring(0, 
suffixName.length() - 1));
+                        } else {
+                            result.add(suffixName);
+                        }
+                    }
+                });
+
+        return result.toArray(new String[0]);
+    }
+
+    @Override
+    public IndexInput openInput(URI dirPath, String fileName, IOContext ctx) 
throws IOException {
+        return openInput(dirPath, fileName, ctx, 2 * 1024 * 1024);
+    }
+
+    private IndexInput openInput(URI dirPath, String fileName, IOContext ctx, 
int bufferSize) {
+        String blobName = dirPath.toString();
+        if (!blobName.endsWith("/")) {
+            blobName += "/";
+        }
+        blobName += fileName;
+
+        final BlobId blobId = BlobId.of(bucketName, blobName);
+        final Blob blob = storage.get(blobId, 
Storage.BlobGetOption.fields(Storage.BlobField.SIZE));
+        final ReadChannel readChannel = blob.reader();
+        readChannel.setChunkSize(bufferSize);
+
+        return new BufferedIndexInput(blobName, bufferSize) {
+
+            @Override
+            public long length() {
+                return blob.getSize();
+            }
+
+            @Override
+            protected void readInternal(ByteBuffer b) throws IOException {
+                readChannel.read(b);
+            }
+
+            @Override
+            protected void seekInternal(long pos) throws IOException {
+                readChannel.seek(pos);
+            }
+
+            @Override
+            public void close() throws IOException {
+                readChannel.close();
+            }
+        };
+    }
+
+    @Override
+    public OutputStream createOutput(URI path) throws IOException {
+        final BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, 
toBlobName(path)).build();
+        final Storage.BlobWriteOption[] writeOptions = new 
Storage.BlobWriteOption[0];
+        final WriteChannel writeChannel = storage.writer(blobInfo, 
writeOptions);
+
+        return Channels.newOutputStream(new WritableByteChannel() {
+            @Override
+            public int write(ByteBuffer src) throws IOException {
+                return writeChannel.write(src);
+            }
+
+            @Override
+            public boolean isOpen() {
+                return writeChannel.isOpen();
+            }
+
+            @Override
+            public void close() throws IOException {
+                writeChannel.close();
+            }
+        });
+    }
+
+    @Override
+    public void createDirectory(URI path) throws IOException {
+        String name = path.toString();
+        if (!name.endsWith("/"))
+            name += "/";
+        storage.create(BlobInfo.newBuilder(bucketName, name).build()) ;
+    }
+
+    @Override
+    public void deleteDirectory(URI path) throws IOException {
+        List<BlobId> blobIds = allBlobsAtDir(path);
+        if (!blobIds.isEmpty()) {
+            storage.delete(blobIds);
+        } else {
+            log.info("Path:{} doesn't have any blobs", path);

Review comment:
       Yeah, at the very least this shouldn't be `INFO` level.  I'll keep it in 
but make it either DEBUG or TRACE since it might be useful for API users to 
catch logic errors in their code (specifying the wrong directory name, etc.)




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscr...@solr.apache.org
For additional commands, e-mail: issues-h...@solr.apache.org

Reply via email to