chatman commented on a change in pull request #929: SOLR-13821: Package Store 
for storing package artefacts
URL: https://github.com/apache/lucene-solr/pull/929#discussion_r331948124
 
 

 ##########
 File path: solr/core/src/java/org/apache/solr/filestore/PackageStoreAPI.java
 ##########
 @@ -0,0 +1,273 @@
+/*
+ * 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.filestore;
+
+import java.io.IOException;
+import java.lang.invoke.MethodHandles;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.codec.digest.DigestUtils;
+import org.apache.solr.api.Command;
+import org.apache.solr.api.EndPoint;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.cloud.CloudUtil;
+import org.apache.solr.common.MapWriter;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.CommonParams;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.params.SolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.StrUtils;
+import org.apache.solr.common.util.Utils;
+import org.apache.solr.core.CoreContainer;
+import org.apache.solr.core.SolrCore;
+import org.apache.solr.request.SolrQueryRequest;
+import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.security.PermissionNameProvider;
+import org.apache.solr.util.CryptoKeys;
+import org.apache.solr.util.SimplePostTool;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.server.ByteBufferInputStream;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.apache.solr.handler.ReplicationHandler.FILE_STREAM;
+
+
+public class PackageStoreAPI {
+  private static final Logger log = 
LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+  public static final String PACKAGESTORE_DIRECTORY = "filestore";
+
+
+  private final CoreContainer coreContainer;
+  PackageStore packageStore;
+  public final FSRead readAPI = new FSRead();
+  public final FSWrite writeAPI = new FSWrite();
+
+  public PackageStoreAPI(CoreContainer coreContainer) {
+    this.coreContainer = coreContainer;
+    packageStore = new DistribPackageStore(coreContainer);
+  }
+
+  public PackageStore getPackageStore() {
+    return packageStore;
+  }
+
+  @EndPoint(
+      path = "/cluster/files/*",
+      method = SolrRequest.METHOD.POST,
+      permission = PermissionNameProvider.Name.FILESTORE_WRITE_PERM)
+  public class FSWrite {
+
+    static final String TMP_ZK_NODE = "/packageStoreWriteInProgress";
+
+    @Command
+    public void upload(SolrQueryRequest req, SolrQueryResponse rsp) {
+      try {
+        coreContainer.getZkController().getZkClient().create(TMP_ZK_NODE, 
"true".getBytes(UTF_8),
+            CreateMode.EPHEMERAL, true);
+
+        Iterable<ContentStream> streams = req.getContentStreams();
+        if (streams == null) throw new 
SolrException(SolrException.ErrorCode.BAD_REQUEST, "no payload");
+        String path = req.getPathTemplateValues().get("*");
+        if (path == null) {
+          throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No 
path");
+        }
+        validateName(path);
+        ContentStream stream = streams.iterator().next();
+        try {
+          ByteBuffer buf = 
SimplePostTool.inputStreamToByteArray(stream.getStream());
+          String sha512 = DigestUtils.sha512Hex(new 
ByteBufferInputStream(buf));
+          List<String> signatures = readSignatures(req, buf);
+          Map<String, Object> vals = new HashMap<>();
+          vals.put(MetaData.SHA512, sha512);
+          if (signatures != null) {
+            vals.put("sig", signatures);
+          }
+          packageStore.put(new PackageStore.FileEntry(buf, new MetaData(vals), 
path));
+          rsp.add(CommonParams.FILE, path);
+        } catch (IOException e) {
+          throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
+        }
+      } catch (InterruptedException e) {
+        log.error("Unexpected error", e);
+      } catch (KeeperException.NodeExistsException e) {
+        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "A write 
is already in process , try later");
+      } catch (KeeperException e) {
+        log.error("Unexpected error", e);
+      } finally {
+        try {
+          coreContainer.getZkController().getZkClient().delete(TMP_ZK_NODE, 
-1, true);
+        } catch (Exception e) {
+          log.error("Unexpected error  ", e);
+        }
+      }
+    }
+
+    private List<String> readSignatures(SolrQueryRequest req, ByteBuffer buf)
+        throws SolrException {
+      String[] signatures = req.getParams().getParams("sig");
+      if (signatures == null || signatures.length == 0) return null;
+      List<String> sigs = Arrays.asList(signatures);
+      validate(sigs, buf);
+      return sigs;
+    }
+
+    public void validate(List<String> sigs,
+                         ByteBuffer buf) throws SolrException {
+      Map<String, byte[]> keys = CloudUtil.getTrustedKeys(
+          coreContainer.getZkController().getZkClient(), "exe");
+      if(keys == null || keys.isEmpty()){
+        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
+            "ZK does not have any keys");
+      }
+      CryptoKeys cryptoKeys = null;
+      try {
+        cryptoKeys = new CryptoKeys(keys);
+      } catch (Exception e) {
+        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
+            "Error parsing public keyts in ZooKeeper");
+      }
+      for (String sig : sigs) {
+       if(cryptoKeys.verify(sig, buf) == null){
+         throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, 
"Signature does not match any public key : " +sig );
+       }
+
+      }
+    }
+
+  }
+
+  @EndPoint(
+      path = "/node/files/*",
+      method = SolrRequest.METHOD.GET,
+      permission = PermissionNameProvider.Name.FILESTORE_READ_PERM)
+  public class FSRead {
+    @Command
+    public void read(SolrQueryRequest req, SolrQueryResponse rsp) {
+      String path = req.getPathTemplateValues().get("*");
+      String pathCopy = path;
+      String getFrom = req.getParams().get("getFrom");
+      if (getFrom != null) {
+        coreContainer.getUpdateShardHandler().getUpdateExecutor().submit(() -> 
{
+          log.debug("Downloading file {}", pathCopy);
+          try {
+            packageStore.fetch(pathCopy, getFrom);
+          } catch (Exception e) {
+            log.error("Failed to download file: " + pathCopy, e);
+          }
+          log.info("downloaded file : {}", pathCopy);
+        });
+        return;
+
+      }
+      if (path == null) {
+        path = "";
+      }
+
+      PackageStore.FileType typ = packageStore.getType(path);
+      if (typ == PackageStore.FileType.NOFILE) {
+        rsp.add("files", Collections.singletonMap(path, null));
+        return;
+      }
+      if (typ == PackageStore.FileType.DIRECTORY) {
+        rsp.add("files", Collections.singletonMap(path, 
packageStore.list(path, null)));
+        return;
+      }
+      if (req.getParams().getBool("meta", false)) {
+        if (typ == PackageStore.FileType.FILE) {
+          int idx = path.lastIndexOf('/');
+          String fileName = path.substring(idx + 1);
+          String parentPath = path.substring(0, path.lastIndexOf('/'));
+          List l = packageStore.list(parentPath, s -> s.equals(fileName));
+          rsp.add("files", Collections.singletonMap(path, l.isEmpty() ? null : 
l.get(0)));
+          return;
+        }
+      } else {
+        writeRawFile(req, rsp, path);
+      }
+    }
+
+    private void writeRawFile(SolrQueryRequest req, SolrQueryResponse rsp, 
String path) {
+      ModifiableSolrParams solrParams = new ModifiableSolrParams();
+      solrParams.add(CommonParams.WT, FILE_STREAM);
+      req.setParams(SolrParams.wrapDefaults(solrParams, req.getParams()));
+      rsp.add(FILE_STREAM, (SolrCore.RawWriter) os -> {
+        packageStore.get(path, (it) -> {
+          try {
+            org.apache.commons.io.IOUtils.copy(it.getInputStream(), os);
+          } catch (IOException e) {
+            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, 
"error reading file" + path);
 
 Review comment:
   Please change:
       "error reading file"
   to:
       "Error reading file: "
   (Notice capitalization and additional space at end of string).

----------------------------------------------------------------
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


With regards,
Apache Git Services

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

Reply via email to