You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by no...@apache.org on 2020/01/07 05:40:18 UTC

[lucene-solr] branch jira/solr14158 updated: download public keys automatically when it does not exist locally

This is an automated email from the ASF dual-hosted git repository.

noble pushed a commit to branch jira/solr14158
in repository https://gitbox.apache.org/repos/asf/lucene-solr.git


The following commit(s) were added to refs/heads/jira/solr14158 by this push:
     new 01c32b4  download public keys automatically when it does not exist locally
01c32b4 is described below

commit 01c32b420e4de8535f1c6d9650f2da866196419d
Author: noble <no...@apache.org>
AuthorDate: Tue Jan 7 16:39:55 2020 +1100

    download public keys automatically when it does not exist locally
---
 .../java/org/apache/solr/core/CoreContainer.java   |  6 +--
 .../apache/solr/filestore/DistribPackageStore.java | 39 ++++++++-------
 .../org/apache/solr/filestore/PackageStoreAPI.java | 56 +++++++++++++---------
 .../java/org/apache/solr/pkg/PackageLoader.java    | 21 ++++++--
 .../src/test/org/apache/solr/pkg/TestPackages.java |  2 +-
 5 files changed, 79 insertions(+), 45 deletions(-)

diff --git a/solr/core/src/java/org/apache/solr/core/CoreContainer.java b/solr/core/src/java/org/apache/solr/core/CoreContainer.java
index f494f50..b757edc 100644
--- a/solr/core/src/java/org/apache/solr/core/CoreContainer.java
+++ b/solr/core/src/java/org/apache/solr/core/CoreContainer.java
@@ -652,6 +652,9 @@ public class CoreContainer {
       // use deprecated API for back-compat, remove in 9.0
       pkiAuthenticationPlugin.initializeMetrics(solrMetricsContext, "/authentication/pki");
       TracerConfigurator.loadTracer(loader, cfg.getTracerConfiguratorPluginInfo(), getZkController().getZkStateReader());
+      packageLoader = new PackageLoader(this);
+      containerHandlers.getApiBag().register(new AnnotatedApi(packageLoader.getPackageAPI().editAPI), Collections.EMPTY_MAP);
+      containerHandlers.getApiBag().register(new AnnotatedApi(packageLoader.getPackageAPI().readAPI), Collections.EMPTY_MAP);
     }
 
     MDCLoggingContext.setNode(this);
@@ -744,9 +747,6 @@ public class CoreContainer {
 
     if (isZooKeeperAware()) {
       metricManager.loadClusterReporters(metricReporters, this);
-      packageLoader = new PackageLoader(this);
-      containerHandlers.getApiBag().register(new AnnotatedApi(packageLoader.getPackageAPI().editAPI), Collections.EMPTY_MAP);
-      containerHandlers.getApiBag().register(new AnnotatedApi(packageLoader.getPackageAPI().readAPI), Collections.EMPTY_MAP);
     }
 
 
diff --git a/solr/core/src/java/org/apache/solr/filestore/DistribPackageStore.java b/solr/core/src/java/org/apache/solr/filestore/DistribPackageStore.java
index 842d270..ef142e0 100644
--- a/solr/core/src/java/org/apache/solr/filestore/DistribPackageStore.java
+++ b/solr/core/src/java/org/apache/solr/filestore/DistribPackageStore.java
@@ -48,6 +48,7 @@ import org.apache.solr.core.CoreContainer;
 import org.apache.solr.filestore.PackageStoreAPI.MetaData;
 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;
@@ -59,7 +60,8 @@ import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR;
 
 public class DistribPackageStore implements PackageStore {
   static final long MAX_PKG_SIZE = Long.parseLong(System.getProperty("max.file.store.size", String.valueOf(100 * 1024 * 1024)));
-  /**This is where al the files in the package store are listed
+  /**
+   * This is where al the files in the package store are listed
    */
   static final String ZK_PACKAGESTORE = "/packagestore";
 
@@ -67,7 +69,8 @@ public class DistribPackageStore implements PackageStore {
   private final CoreContainer coreContainer;
   private Map<String, FileInfo> tmpFiles = new ConcurrentHashMap<>();
 
-  private final Path solrhome ;
+  private final Path solrhome;
+
   public DistribPackageStore(CoreContainer coreContainer) {
     this.coreContainer = coreContainer;
     solrhome = this.coreContainer.getResourceLoader().getInstancePath();
@@ -118,7 +121,6 @@ public class DistribPackageStore implements PackageStore {
     }
 
 
-
     private void persistToFile(ByteBuffer data, ByteBuffer meta) throws IOException {
       synchronized (DistribPackageStore.this) {
         this.metaData = meta;
@@ -130,8 +132,6 @@ public class DistribPackageStore implements PackageStore {
     }
 
 
-
-
     public boolean exists(boolean validateContent, boolean fetchMissing) throws IOException {
       File file = getRealpath(path).toFile();
       if (!file.exists()) {
@@ -327,8 +327,8 @@ public class DistribPackageStore implements PackageStore {
   private void distribute(FileInfo info) {
     try {
       String dirName = info.path.substring(0, info.path.lastIndexOf('/'));
-      coreContainer.getZkController().getZkClient().makePath(ZK_PACKAGESTORE + dirName,false, true);
-      coreContainer.getZkController().getZkClient().create(ZK_PACKAGESTORE + info.path , info.getDetails().getMetaData().sha512.getBytes(UTF_8),
+      coreContainer.getZkController().getZkClient().makePath(ZK_PACKAGESTORE + dirName, false, true);
+      coreContainer.getZkController().getZkClient().create(ZK_PACKAGESTORE + info.path, info.getDetails().getMetaData().sha512.getBytes(UTF_8),
           CreateMode.PERSISTENT, true);
     } catch (Exception e) {
       throw new SolrException(SERVER_ERROR, "Unable to create an entry in ZK", e);
@@ -472,12 +472,18 @@ public class DistribPackageStore implements PackageStore {
   @Override
   public void refresh(String path) {
     try {
-      List l = coreContainer.getZkController().getZkClient().getChildren(path, null, true);
+      List l = null;
+      try {
+        l = coreContainer.getZkController().getZkClient().getChildren(ZK_PACKAGESTORE+ path, null, true);
+      } catch (KeeperException.NoNodeException e) {
+        // doe not matter
+      }
       if (l != null && !l.isEmpty()) {
         List myFiles = list(path, s -> true);
         for (Object f : l) {
-          if(!myFiles.contains(f)) {
-            fetch(path+ "/"+ f.toString(), "*");
+          if (!myFiles.contains(f)) {
+            log.info("{} does not exist locally, downloading.. ",f);
+            fetch(path + "/" + f.toString(), "*");
           }
         }
       }
@@ -524,7 +530,8 @@ public class DistribPackageStore implements PackageStore {
   public static Path getPackageStoreDirPath(Path solrHome) {
     return Paths.get(solrHome.toAbsolutePath().toString(), PackageStoreAPI.PACKAGESTORE_DIRECTORY).toAbsolutePath();
   }
-  private static String  _getMetapath(String path) {
+
+  private static String _getMetapath(String path) {
     int idx = path.lastIndexOf('/');
     return path.substring(0, idx + 1) + "." + path.substring(idx + 1) + ".json";
   }
@@ -533,7 +540,7 @@ public class DistribPackageStore implements PackageStore {
    * Internal API
    */
   public static void _persistToFile(Path solrHome, String path, ByteBuffer data, ByteBuffer meta) throws IOException {
-    Path realpath = _getRealPath(path , solrHome);
+    Path realpath = _getRealPath(path, solrHome);
     File file = realpath.toFile();
     File parent = file.getParentFile();
     if (!parent.exists()) {
@@ -545,7 +552,7 @@ public class DistribPackageStore implements PackageStore {
     }
 
 
-    File metdataFile = _getRealPath(_getMetapath(path) , solrHome).toFile();
+    File metdataFile = _getRealPath(_getMetapath(path), solrHome).toFile();
 
     try (FileOutputStream fos = new FileOutputStream(metdataFile)) {
       fos.write(meta.array(), 0, meta.limit());
@@ -563,9 +570,9 @@ public class DistribPackageStore implements PackageStore {
     return _getKeys(solrhome);
   }
 
-  /**Internal API
-   */
-  public static Map<String, byte[]> _getKeys(Path solrhome) throws IOException {
+
+  // reads local keys file
+  private static Map<String, byte[]> _getKeys(Path solrhome) throws IOException {
     Map<String, byte[]> result = new HashMap<>();
     Path keysDir = _getRealPath(PackageStoreAPI.KEYS_DIR, solrhome);
 
diff --git a/solr/core/src/java/org/apache/solr/filestore/PackageStoreAPI.java b/solr/core/src/java/org/apache/solr/filestore/PackageStoreAPI.java
index 7e792a5..6a78b2c 100644
--- a/solr/core/src/java/org/apache/solr/filestore/PackageStoreAPI.java
+++ b/solr/core/src/java/org/apache/solr/filestore/PackageStoreAPI.java
@@ -112,7 +112,8 @@ public class PackageStoreAPI {
           }
           if (validateSignatures) {
             try {
-              validate(entry.meta.signatures, entry, true);
+              packageStore.refresh(KEYS_DIR);
+              validate(entry.meta.signatures, entry, false);
             } catch (Exception e) {
               log.error("Error validating package artifact", e);
               errs.accept(e.getMessage());
@@ -145,7 +146,7 @@ public class PackageStoreAPI {
             CreateMode.EPHEMERAL, true);
 
         Iterable<ContentStream> streams = req.getContentStreams();
-        if (streams == null) throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No payload");
+        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");
@@ -158,7 +159,7 @@ public class PackageStoreAPI {
           MetaData meta = _createJsonMetaData(buf, signatures);
           PackageStore.FileType type = packageStore.getType(path, true);
           if(type != PackageStore.FileType.NOFILE) {
-            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,  "Path already exists: "+ path);
+            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,  "Path already exists "+ path);
           }
           packageStore.put(new PackageStore.FileEntry(buf, meta, path));
           rsp.add(CommonParams.FILE, path);
@@ -168,7 +169,7 @@ public class PackageStoreAPI {
       } 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.");
+        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "A write is already in process , try later");
       } catch (KeeperException e) {
         log.error("Unexpected error", e);
       } finally {
@@ -185,27 +186,28 @@ public class PackageStoreAPI {
       String[] signatures = req.getParams().getParams("sig");
       if (signatures == null || signatures.length == 0) return null;
       List<String> sigs = Arrays.asList(signatures);
+      packageStore.refresh(KEYS_DIR);
       validate(sigs, buf);
       return sigs;
     }
 
-    public void validate(List<String> sigs,
-                         ByteBuffer buf) throws SolrException, IOException {
+    private void validate(List<String> sigs,
+                          ByteBuffer buf) throws SolrException, IOException {
       Map<String, byte[]> keys = packageStore.getKeys();
       if (keys == null || keys.isEmpty()) {
         throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
-            "The trusted keystore ("+KEYS_DIR+") of the package store does not have any keys");
+            "package store 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 keys in trusted keystore ("+KEYS_DIR+") of the package store");
+            "Error parsing public keys in Package store");
       }
       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 +" len: "+buf.limit()+  " content sha512: "+
+          throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Signature does not match any public key : " + sig +" len: "+buf.limit()+  " content sha512: "+
               DigestUtils.sha512Hex(new ByteBufferInputStream(buf)));
         }
 
@@ -252,7 +254,7 @@ public class PackageStoreAPI {
           } catch (Exception e) {
             log.error("Failed to download file: " + pathCopy, e);
           }
-          log.info("Downloaded file: {}", pathCopy);
+          log.info("downloaded file: {}", pathCopy);
         });
         return;
 
@@ -293,7 +295,7 @@ public class PackageStoreAPI {
           try {
             org.apache.commons.io.IOUtils.copy(it.getInputStream(), os);
           } catch (IOException e) {
-            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error reading file: " + path);
+            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error reading file" + path);
           }
         }, false);
 
@@ -329,12 +331,12 @@ public class PackageStoreAPI {
 
   public static void validateName(String path, boolean failForTrusted) {
     if (path == null) {
-      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Empty path");
+      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "empty path");
     }
     List<String> parts = StrUtils.splitSmart(path, '/', true);
     for (String part : parts) {
       if (part.charAt(0) == '.') {
-        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Cannot start with period");
+        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "cannot start with period");
       }
       for (int i = 0; i < part.length(); i++) {
         for (int j = 0; j < INVALIDCHARS.length(); j++) {
@@ -344,7 +346,7 @@ public class PackageStoreAPI {
       }
     }
     if (failForTrusted &&  TRUSTED_DIR.equals(parts.get(0))) {
-      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Trying to write into /_trusted_/ directory");
+      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "trying to write into /_trusted_/ directory");
     }
   }
 
@@ -355,18 +357,22 @@ public class PackageStoreAPI {
    * @param isFirstAttempt If there is a failure
    */
   public void validate(List<String> sigs,
-                       PackageStore.FileEntry entry, boolean isFirstAttempt) throws SolrException, IOException {
-    if(!isFirstAttempt){
+                       PackageStore.FileEntry entry,
+                       boolean isFirstAttempt) throws SolrException, IOException {
+    if (!isFirstAttempt) {
       //we are retrying because last validation failed.
       // get all keys again and try again
-      packageStore.refresh(DistribPackageStore.ZK_PACKAGESTORE+ KEYS_DIR);
+      packageStore.refresh(KEYS_DIR);
     }
 
     Map<String, byte[]> keys = packageStore.getKeys();
     if (keys == null || keys.isEmpty()) {
-     if(isFirstAttempt) validate(sigs, entry, false);
+      if(isFirstAttempt) {
+        validate(sigs, entry, false);
+        return;
+      }
       throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
-          "ZooKeeper does not have any public keys");
+          "Packagestore does not have any public keys");
     }
     CryptoKeys cryptoKeys = null;
     try {
@@ -376,16 +382,22 @@ public class PackageStoreAPI {
           "Error parsing public keys in ZooKeeper");
     }
     for (String sig : sigs) {
-      Supplier<String> errMsg = () -> "Signature does not match any public key: " + sig + ", sha256: " + entry.getMetaData().sha512;
+      Supplier<String> errMsg = () -> "Signature does not match any public key : " + sig + "sha256 " + entry.getMetaData().sha512;
       if (entry.getBuffer() != null) {
         if (cryptoKeys.verify(sig, entry.getBuffer()) == null) {
-          if(isFirstAttempt)  validate(sigs, entry, false);
+          if(isFirstAttempt) {
+            validate(sigs, entry, false);
+            return;
+          }
           throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, errMsg.get());
         }
       } else {
         InputStream inputStream = entry.getInputStream();
         if (cryptoKeys.verify(sig, inputStream) == null) {
-          if(isFirstAttempt)  validate(sigs, entry, false);
+          if(isFirstAttempt)  {
+            validate(sigs, entry, false);
+            return;
+          }
           throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, errMsg.get());
         }
 
diff --git a/solr/core/src/java/org/apache/solr/pkg/PackageLoader.java b/solr/core/src/java/org/apache/solr/pkg/PackageLoader.java
index 8783d9b..c4c40eb 100644
--- a/solr/core/src/java/org/apache/solr/pkg/PackageLoader.java
+++ b/solr/core/src/java/org/apache/solr/pkg/PackageLoader.java
@@ -168,7 +168,13 @@ public class PackageLoader implements Closeable {
         Version version = myVersions.get(v.version);
         if (version == null) {
           log.info("A new version: {} added for package: {} with artifacts {}", v.version, this.name, v.files);
-          myVersions.put(v.version, new Version(this, v));
+          Version ver = null;
+          try {
+            ver = new Version(this, v);
+          } catch (Exception e) {
+            log.error("package could not be loaded "+ ver.toString());
+          }
+          myVersions.put(v.version, ver);
           sortedVersions.add(v.version);
         }
       }
@@ -248,9 +254,13 @@ public class PackageLoader implements Closeable {
         this.parent = parent;
         this.version = v;
         List<Path> paths = new ArrayList<>();
+
+        List<String> errs = new ArrayList<>();
+        coreContainer.getPackageStoreAPI().validateFiles(version.files, true, s -> errs.add(s));
+        if(!errs.isEmpty()) {
+          throw new RuntimeException("Cannot load package: " +errs);
+        }
         for (String file : version.files) {
-          //ensure that the files are downloaded and available
-          coreContainer.getPackageStoreAPI().getPackageStore().fetch(file,null);
           paths.add(coreContainer.getPackageStoreAPI().getPackageStore().getRealpath(file));
         }
 
@@ -283,6 +293,11 @@ public class PackageLoader implements Closeable {
           closeWhileHandlingException(loader);
         }
       }
+
+      @Override
+      public String toString() {
+        return jsonStr();
+      }
     }
   }
 
diff --git a/solr/core/src/test/org/apache/solr/pkg/TestPackages.java b/solr/core/src/test/org/apache/solr/pkg/TestPackages.java
index 7fdd5c8..897383a 100644
--- a/solr/core/src/test/org/apache/solr/pkg/TestPackages.java
+++ b/solr/core/src/test/org/apache/solr/pkg/TestPackages.java
@@ -461,7 +461,7 @@ public class TestPackages extends SolrCloudTestCase {
           .build();
 
       //the files is not yet there. The command should fail with error saying "No such file"
-      expectError(req, cluster.getSolrClient(), errPath, "No such file :");
+      expectError(req, cluster.getSolrClient(), errPath, "No such file:");
 
 
       //post the jar file. No signature is sent