keith-turner commented on code in PR #30: URL: https://github.com/apache/accumulo-classloaders/pull/30#discussion_r2547759943
########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/LocalCachingContext.java: ########## @@ -0,0 +1,269 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import static java.nio.file.StandardCopyOption.ATOMIC_MOVE; +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; +import static java.util.Objects.hash; +import static java.util.Objects.requireNonNull; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.accumulo.classloader.lcc.cache.CacheUtils; +import org.apache.accumulo.classloader.lcc.cache.CacheUtils.LockInfo; +import org.apache.accumulo.classloader.lcc.definition.ContextDefinition; +import org.apache.accumulo.classloader.lcc.definition.Resource; +import org.apache.accumulo.classloader.lcc.resolvers.FileResolver; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory.ContextClassLoaderException; +import org.apache.accumulo.core.util.Retry; +import org.apache.accumulo.core.util.Retry.RetryFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public final class LocalCachingContext { + + private static class ClassPathElement { + private final FileResolver resolver; + private final URL localCachedCopyLocation; + private final String localCachedCopyDigest; + + public ClassPathElement(FileResolver resolver, URL localCachedCopy, + String localCachedCopyDigest) { + this.resolver = requireNonNull(resolver, "resolver must be supplied"); + this.localCachedCopyLocation = + requireNonNull(localCachedCopy, "local cached copy location must be supplied"); + this.localCachedCopyDigest = + requireNonNull(localCachedCopyDigest, "local cached copy md5 must be supplied"); + } + + public URL getLocalCachedCopyLocation() { + return localCachedCopyLocation; + } + + @Override + public int hashCode() { + return hash(localCachedCopyDigest, localCachedCopyLocation, resolver); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ClassPathElement other = (ClassPathElement) obj; + return Objects.equals(localCachedCopyDigest, other.localCachedCopyDigest) + && Objects.equals(localCachedCopyLocation, other.localCachedCopyLocation) + && Objects.equals(resolver, other.resolver); + } + + @Override + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append("source: ").append(resolver.getURL()); + buf.append(", cached copy:").append(localCachedCopyLocation); + return buf.toString(); + } + } + + private static final Logger LOG = LoggerFactory.getLogger(LocalCachingContext.class); + + private final Path contextCacheDir; + private final String contextName; + private final Set<ClassPathElement> elements = new HashSet<>(); + private final AtomicReference<URLClassLoader> classloader = new AtomicReference<>(); + private final AtomicReference<ContextDefinition> definition = new AtomicReference<>(); + private final RetryFactory retryFactory = Retry.builder().infiniteRetries() + .retryAfter(1, TimeUnit.SECONDS).incrementBy(1, TimeUnit.SECONDS).maxWait(5, TimeUnit.MINUTES) + .backOffFactor(2).logInterval(1, TimeUnit.SECONDS).createFactory(); + + public LocalCachingContext(ContextDefinition contextDefinition) + throws IOException, ContextClassLoaderException { + this.definition.set(requireNonNull(contextDefinition, "definition must be supplied")); + this.contextName = this.definition.get().getContextName(); + this.contextCacheDir = CacheUtils.createOrGetContextCacheDir(contextName); + } + + public ContextDefinition getDefinition() { + return definition.get(); + } + + private ClassPathElement cacheResource(final Resource resource) + throws InterruptedException, IOException, ContextClassLoaderException, URISyntaxException { + final FileResolver source = FileResolver.resolve(resource.getURL()); + final Path tmpCacheLocation = + contextCacheDir.resolve(source.getFileName() + "_" + resource.getChecksum() + "_tmp"); + final Path finalCacheLocation = + contextCacheDir.resolve(source.getFileName() + "_" + resource.getChecksum()); + final File cacheFile = finalCacheLocation.toFile(); + if (!Files.exists(finalCacheLocation)) { + Retry retry = retryFactory.createRetry(); + boolean successful = false; + while (!successful) { + LOG.trace("Caching resource {} at {}", source.getURL(), cacheFile.getAbsolutePath()); + try (InputStream is = source.getInputStream()) { + Files.copy(is, tmpCacheLocation, REPLACE_EXISTING); + Files.move(tmpCacheLocation, finalCacheLocation, ATOMIC_MOVE); + successful = true; + retry.logCompletion(LOG, + "Resource " + source.getURL() + " cached locally as " + finalCacheLocation); + } catch (IOException e) { + LOG.error("Error copying resource from {}. Retrying...", source.getURL(), e); Review Comment: The destination info could be helpful for debugging, like if the code is using different config than you expect and its not copy to the place you are looking. ```suggestion LOG.error("Error copying resource from {} to {}. Retrying...", source.getURL(), finalCacheLocation, e); ``` ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/LocalCachingContextClassLoaderFactory.java: ########## @@ -0,0 +1,193 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.accumulo.classloader.lcc.cache.CacheUtils; +import org.apache.accumulo.classloader.lcc.definition.ContextDefinition; +import org.apache.accumulo.classloader.lcc.definition.Resource; +import org.apache.accumulo.classloader.lcc.resolvers.FileResolver; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +/** + * A ContextClassLoaderFactory implementation that creates and maintains a ClassLoader for a named + * context. This factory expects the parameter passed to {@link #getClassLoader(String)} to be the + * URL of a json formatted {@link ContextDefinition} file. The file contains an interval at which + * this class should monitor the file for changes and a list of {@link Resource} objects. Each + * resource is defined by a URL to the file and an expected MD5 hash value. + * <p> + * The URLs supplied for the context definition file and for the resources can use one of the + * following protocols: file://, http://, or hdfs://. + * <p> + * As this class processes the ContextDefinition it fetches the contents of the resource from the + * resource URL and caches it in a directory on the local filesystem. This class uses the value of + * the system property {@link Constants#CACHE_DIR_PROPERTY} as the root directory and creates a + * sub-directory for each context name. Each context cache directory contains a lock file and a copy + * of each fetched resource that is named using the following format: fileName_checksum. + * <p> + * The lock file prevents processes from manipulating the contexts of the context cache directory + * concurrently, which enables the cache directories to be shared among multiple processes on the + * host. + * <p> + * Note that because the cache directory is shared among multiple processes, and one process can't + * know what the other processes are doing, this class cannot clean up the shared cache directory. + * It is left to the user to remove unused context cache directories and unused old files within a + * context cache directory. + */ +public class LocalCachingContextClassLoaderFactory implements ContextClassLoaderFactory { + + private static final Logger LOG = + LoggerFactory.getLogger(LocalCachingContextClassLoaderFactory.class); + + private final Cache<String,LocalCachingContext> contexts = + Caffeine.newBuilder().expireAfterAccess(24, TimeUnit.HOURS).build(); + + private ContextDefinition parseContextDefinition(final URL url) + throws ContextClassLoaderException { + LOG.trace("Retrieving context definition file from {}", url); + final FileResolver resolver = FileResolver.resolve(url); + try { + try (InputStream is = resolver.getInputStream()) { + ContextDefinition def = + Constants.GSON.fromJson(new InputStreamReader(is, UTF_8), ContextDefinition.class); + if (def == null) { + throw new ContextClassLoaderException( + "ContextDefinition null for context definition file: " + resolver.getURL()); + } + return def; + } + } catch (IOException e) { + throw new ContextClassLoaderException( + "Error reading context definition file: " + resolver.getURL(), e); + } + } + + /** + * Schedule a task to execute at {@code interval} seconds to update the LocalCachingContext if the + * ContextDefinition has changed. The task schedules a follow-on task at the update interval value + * (if it changed). + */ + private void monitorContext(final String contextLocation, int interval) { + Constants.EXECUTOR.schedule(() -> { + final LocalCachingContext classLoader = contexts.getIfPresent(contextLocation); Review Comment: We discussed that this cache access by the background refresh task could keep the cache entry from ever expiring. Need to avoid accessing the cache here. This could be a follow on issue. We discussed using a weaf ref or the cache eviction notification mechanism as ways to avoid this cache access. ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/Constants.java: ########## @@ -0,0 +1,39 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; + +import org.apache.commons.codec.digest.DigestUtils; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class Constants { + + public static final String CACHE_DIR_PROPERTY = "accumulo.classloader.cache.dir"; + public static final ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(0); + public static final Gson GSON = new GsonBuilder().disableJdkUnsafe().create(); + + public static DigestUtils getChecksummer() { + return new DigestUtils("MD5"); Review Comment: ```suggestion return new DigestUtils("SHA256"); ``` ########## modules/local-caching-classloader/src/test/java/org/apache/accumulo/classloader/lcc/LocalCachingContextClassLoaderFactoryTest.java: ########## @@ -0,0 +1,667 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import static org.apache.accumulo.classloader.lcc.TestUtils.createContextDefinitionFile; +import static org.apache.accumulo.classloader.lcc.TestUtils.testClassFailsToLoad; +import static org.apache.accumulo.classloader.lcc.TestUtils.testClassLoads; +import static org.apache.accumulo.classloader.lcc.TestUtils.updateContextDefinitionFile; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; + +import org.apache.accumulo.classloader.lcc.TestUtils.TestClassInfo; +import org.apache.accumulo.classloader.lcc.definition.ContextDefinition; +import org.apache.accumulo.classloader.lcc.definition.Resource; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory.ContextClassLoaderException; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.FsUrlStreamHandlerFactory; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hdfs.MiniDFSCluster; +import org.eclipse.jetty.server.Server; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +public class LocalCachingContextClassLoaderFactoryTest { + + private static final LocalCachingContextClassLoaderFactory FACTORY = + new LocalCachingContextClassLoaderFactory(); + private static final int MONITOR_INTERVAL_SECS = 5; + private static MiniDFSCluster hdfs; + private static FileSystem fs; + private static Server jetty; + private static URL jarAOrigLocation; + private static URL jarBOrigLocation; + private static URL jarCOrigLocation; + private static URL jarDOrigLocation; + private static URL jarEOrigLocation; + private static URL localAllContext; + private static URL hdfsAllContext; + private static URL jettyAllContext; + private static TestClassInfo classA; + private static TestClassInfo classB; + private static TestClassInfo classC; + private static TestClassInfo classD; + + @TempDir + private static java.nio.file.Path tempDir; + + @BeforeAll + public static void beforeAll() throws Exception { + String tmp = tempDir.resolve("base").toUri().toString(); + System.setProperty(Constants.CACHE_DIR_PROPERTY, tmp); + + // Find the Test jar files + jarAOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestA/TestA.jar"); + assertNotNull(jarAOrigLocation); + jarBOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestB/TestB.jar"); + assertNotNull(jarBOrigLocation); + jarCOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestC/TestC.jar"); + assertNotNull(jarCOrigLocation); + jarDOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestD/TestD.jar"); + assertNotNull(jarDOrigLocation); + jarEOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestE/TestE.jar"); + assertNotNull(jarEOrigLocation); + + // Put B into HDFS + hdfs = TestUtils.getMiniCluster(); + URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory(hdfs.getConfiguration(0))); + + fs = hdfs.getFileSystem(); + assertTrue(fs.mkdirs(new Path("/contextB"))); + final Path dst = new Path("/contextB/TestB.jar"); + fs.copyFromLocalFile(new Path(jarBOrigLocation.toURI()), dst); + assertTrue(fs.exists(dst)); + final URL jarBHdfsLocation = new URL(fs.getUri().toString() + dst.toUri().toString()); + + // Have Jetty serve up files from Jar C directory + java.nio.file.Path jarCParentDirectory = + java.nio.file.Path.of(jarCOrigLocation.toURI()).getParent(); + assertNotNull(jarCParentDirectory); + jetty = TestUtils.getJetty(jarCParentDirectory); + final URL jarCJettyLocation = jetty.getURI().resolve("TestC.jar").toURL(); + + // ContextDefinition with all jars + ContextDefinition allJarsDef = ContextDefinition.create("all", MONITOR_INTERVAL_SECS, + jarAOrigLocation, jarBHdfsLocation, jarCJettyLocation, jarDOrigLocation); + String allJarsDefJson = allJarsDef.toJson(); + + // Create local context definition in jar C directory + File localDefFile = jarCParentDirectory.resolve("allContextDefinition.json").toFile(); + Files.writeString(localDefFile.toPath(), allJarsDefJson, StandardOpenOption.CREATE); + assertTrue(Files.exists(localDefFile.toPath())); + + Path hdfsDefFile = new Path("/allContextDefinition.json"); + fs.copyFromLocalFile(new Path(localDefFile.toURI()), hdfsDefFile); + assertTrue(fs.exists(hdfsDefFile)); + + localAllContext = localDefFile.toURI().toURL(); + hdfsAllContext = new URL(fs.getUri().toString() + hdfsDefFile.toUri().toString()); + jettyAllContext = jetty.getURI().resolve("allContextDefinition.json").toURL(); + + classA = new TestClassInfo("test.TestObjectA", "Hello from A"); + classB = new TestClassInfo("test.TestObjectB", "Hello from B"); + classC = new TestClassInfo("test.TestObjectC", "Hello from C"); + classD = new TestClassInfo("test.TestObjectD", "Hello from D"); + } + + @AfterAll + public static void afterAll() throws Exception { + System.clearProperty(Constants.CACHE_DIR_PROPERTY); + if (jetty != null) { + jetty.stop(); + jetty.join(); + } + if (hdfs != null) { + hdfs.shutdown(); + } + } + + @AfterEach + public void afterEach() { + FACTORY.resetForTests(); + } + + @Test + public void testCreateFromLocal() throws Exception { + final ClassLoader cl = FACTORY.getClassLoader(localAllContext.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + } + + @Test + public void testCreateFromHdfs() throws Exception { + final ClassLoader cl = FACTORY.getClassLoader(hdfsAllContext.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + } + + @Test + public void testCreateFromHttp() throws Exception { + final ClassLoader cl = FACTORY.getClassLoader(jettyAllContext.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + } + + @Test + public void testInvalidContextDefinitionURL() { + ContextClassLoaderException ex = + assertThrows(ContextClassLoaderException.class, () -> FACTORY.getClassLoader("/not/a/URL")); + assertEquals("Error getting classloader for context: Expected valid URL to context definition " + + "file but received: /not/a/URL", ex.getMessage()); + } + + @Test + public void testInitialContextDefinitionEmpty() throws Exception { + // Create a new context definition file in HDFS, but with no content + final Path def = createContextDefinitionFile(fs, "EmptyContextDefinitionFile.json", null); + final URL emptyDefUrl = new URL(fs.getUri().toString() + def.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(emptyDefUrl.toString())); + assertEquals( + "Error getting classloader for context: ContextDefinition null for context definition " + + "file: " + emptyDefUrl.toString(), + ex.getMessage()); + } + + @Test + public void testInitialInvalidJson() throws Exception { + // Create a new context definition file in HDFS, but with invalid content + ContextDefinition def = + ContextDefinition.create("invalid", MONITOR_INTERVAL_SECS, jarAOrigLocation); + // write out invalid json + final Path invalid = createContextDefinitionFile(fs, "InvalidContextDefinitionFile.json", + def.toJson().substring(0, 4)); + final URL invalidDefUrl = new URL(fs.getUri().toString() + invalid.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(invalidDefUrl.toString())); + assertTrue(ex.getMessage().startsWith( + "Error getting classloader for context: com.google.gson.stream.MalformedJsonException")); + } + + @Test + public void testInitial() throws Exception { + ContextDefinition def = + ContextDefinition.create("initial", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path initial = + createContextDefinitionFile(fs, "InitialContextDefinitionFile.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ClassLoader cl = FACTORY.getClassLoader(initialDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + } + + @Test + public void testInitialNonExistentResource() throws Exception { + // copy jarA to some other name + java.nio.file.Path jarAPath = java.nio.file.Path.of(jarAOrigLocation.toURI()); + java.nio.file.Path jarAPathParent = jarAPath.getParent(); + assertNotNull(jarAPathParent); + java.nio.file.Path jarACopy = jarAPathParent.resolve("jarACopy.jar"); + assertTrue(!Files.exists(jarACopy)); + Files.copy(jarAPath, jarACopy, StandardCopyOption.REPLACE_EXISTING); + assertTrue(Files.exists(jarACopy)); + + ContextDefinition def = + ContextDefinition.create("initial", MONITOR_INTERVAL_SECS, jarACopy.toUri().toURL()); + + Files.delete(jarACopy); + assertTrue(!Files.exists(jarACopy)); + + final Path initial = createContextDefinitionFile(fs, + "InitialContextDefinitionFileMissingResource.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(initialDefUrl.toString())); + assertTrue(ex.getMessage().endsWith("jarACopy.jar does not exist.")); + } + + @Test + public void testInitialBadResourceURL() throws Exception { + Resource r = new Resource(); + // remove the file:// prefix from the URL + r.setLocation(jarAOrigLocation.toString().substring(6)); + r.setChecksum("1234"); + TreeSet<Resource> resources = new TreeSet<>(); + resources.add(r); + + ContextDefinition def = new ContextDefinition(); + def.setContextName("initial"); + def.setMonitorIntervalSeconds(MONITOR_INTERVAL_SECS); + def.setResources(resources); + + final Path initial = createContextDefinitionFile(fs, + "InitialContextDefinitionBadResourceURL.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(initialDefUrl.toString())); + assertTrue(ex.getMessage().startsWith("Error getting classloader for context: no protocol")); + Throwable t = ex.getCause(); + assertTrue(t instanceof MalformedURLException); + assertTrue(t.getMessage().startsWith("no protocol")); + } + + @Test + public void testInitialBadResourceChecksum() throws Exception { + Resource r = new Resource(); + r.setLocation(jarAOrigLocation.toString()); + r.setChecksum("1234"); + TreeSet<Resource> resources = new TreeSet<>(); + resources.add(r); + + ContextDefinition def = new ContextDefinition(); + def.setContextName("initial"); + def.setMonitorIntervalSeconds(MONITOR_INTERVAL_SECS); + def.setResources(resources); + + final Path initial = createContextDefinitionFile(fs, + "InitialContextDefinitionBadResourceChecksum.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(initialDefUrl.toString())); + assertTrue(ex.getMessage().startsWith("Error getting classloader for context: Checksum")); + Throwable t = ex.getCause(); + assertTrue(t instanceof IllegalStateException); + assertTrue( + t.getMessage().endsWith("TestA.jar does not match checksum in context definition 1234")); + } + + @Test + public void testUpdate() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateContextDefinitionFile.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + // Update the contents of the context definition json file + ContextDefinition updateDef = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarDOrigLocation); + updateContextDefinitionFile(fs, defFilePath, updateDef.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + assertNotEquals(cl, cl2); + + testClassFailsToLoad(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassLoads(cl2, classD); + } + + @Test + public void testUpdateSameClassNameDifferentContent() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateContextDefinitionFile.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + // Update the contents of the context definition json file + ContextDefinition updateDef = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarEOrigLocation); + updateContextDefinitionFile(fs, defFilePath, updateDef.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + assertNotEquals(cl, cl2); + + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazz = + (Class<? extends test.Test>) cl2.loadClass("test.TestObjectA"); + test.Test impl = clazz.getDeclaredConstructor().newInstance(); + assertEquals("Hello from E", impl.hello()); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + } + + @Test + public void testUpdateContextDefinitionEmpty() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateEmptyContextDefinitionFile.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + // Update the contents of the context definition json file with an empty file + updateContextDefinitionFile(fs, defFilePath, null); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + // validate that the classloader has not updated + assertEquals(cl, cl2); + testClassLoads(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + + } + + @Test + public void testUpdateNonExistentResource() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateNonExistentResource.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + // copy jarA to jarACopy + // create a ContextDefinition that references it + // delete jarACopy + java.nio.file.Path jarAPath = java.nio.file.Path.of(jarAOrigLocation.toURI()); + java.nio.file.Path jarAPathParent = jarAPath.getParent(); + assertNotNull(jarAPathParent); + java.nio.file.Path jarACopy = jarAPathParent.resolve("jarACopy.jar"); + assertTrue(!Files.exists(jarACopy)); + Files.copy(jarAPath, jarACopy, StandardCopyOption.REPLACE_EXISTING); + assertTrue(Files.exists(jarACopy)); + ContextDefinition def2 = + ContextDefinition.create("initial", MONITOR_INTERVAL_SECS, jarACopy.toUri().toURL()); + Files.delete(jarACopy); + assertTrue(!Files.exists(jarACopy)); + + updateContextDefinitionFile(fs, defFilePath, def2.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + // validate that the classloader has not updated + assertEquals(cl, cl2); + testClassLoads(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + } + + @Test + public void testUpdateBadResourceChecksum() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateBadResourceChecksum.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + Resource r = new Resource(); + r.setLocation(jarAOrigLocation.toString()); + r.setChecksum("1234"); + TreeSet<Resource> resources = new TreeSet<>(); + resources.add(r); + + ContextDefinition def2 = new ContextDefinition(); + def2.setContextName("update"); + def2.setMonitorIntervalSeconds(MONITOR_INTERVAL_SECS); + def2.setResources(resources); + + updateContextDefinitionFile(fs, defFilePath, def2.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + // validate that the classloader has not updated + assertEquals(cl, cl2); + testClassLoads(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + } + + @Test + public void testUpdateBadResourceURL() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateBadResourceChecksum.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + Resource r = new Resource(); + // remove the file:// prefix from the URL + r.setLocation(jarAOrigLocation.toString().substring(6)); + r.setChecksum("1234"); + TreeSet<Resource> resources = new TreeSet<>(); + resources.add(r); + + ContextDefinition def2 = new ContextDefinition(); + def2.setContextName("initial"); + def2.setMonitorIntervalSeconds(MONITOR_INTERVAL_SECS); + def2.setResources(resources); + + updateContextDefinitionFile(fs, defFilePath, def2.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + // validate that the classloader has not updated + assertEquals(cl, cl2); + testClassLoads(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + } + + @Test + public void testUpdateInvalidJson() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateInvalidContextDefinitionFile.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + ContextDefinition updateDef = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarDOrigLocation); + updateContextDefinitionFile(fs, defFilePath, updateDef.toJson().substring(0, 4)); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + // validate that the classloader has not updated + assertEquals(cl, cl2); + testClassLoads(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + + // Re-write the updated context definition such that it is now valid + updateContextDefinitionFile(fs, defFilePath, updateDef.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl3 = FACTORY.getClassLoader(updateDefUrl.toString()); + + assertEquals(cl, cl2); + assertNotEquals(cl, cl3); + testClassFailsToLoad(cl3, classA); + testClassFailsToLoad(cl3, classB); + testClassFailsToLoad(cl3, classC); + testClassLoads(cl3, classD); + } + + @Test + public void testChangingContext() throws Exception { + ContextDefinition def = ContextDefinition.create("update", MONITOR_INTERVAL_SECS, + jarAOrigLocation, jarBOrigLocation, jarCOrigLocation, jarDOrigLocation); + final Path update = + createContextDefinitionFile(fs, "UpdateChangingContextDefinition.json", def.toJson()); + final URL updatedDefUrl = new URL(fs.getUri().toString() + update.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updatedDefUrl.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + + final List<URL> masterList = new ArrayList<>(); + masterList.add(jarAOrigLocation); + masterList.add(jarBOrigLocation); + masterList.add(jarCOrigLocation); + masterList.add(jarDOrigLocation); + + List<URL> priorList = masterList; + ClassLoader priorCL = cl; + + for (int i = 0; i < 20; i++) { + final List<URL> updatedList = new ArrayList<>(masterList); + Collections.shuffle(updatedList); + final URL removed = updatedList.remove(0); + + // Update the contents of the context definition json file + ContextDefinition updateDef = ContextDefinition.create("update", MONITOR_INTERVAL_SECS, + updatedList.toArray(new URL[] {})); + updateContextDefinitionFile(fs, update, updateDef.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader updatedClassLoader = FACTORY.getClassLoader(updatedDefUrl.toString()); + + if (updatedList.equals(priorList)) { + assertEquals(priorCL, updatedClassLoader); + } else { + assertNotEquals(cl, updatedClassLoader); + for (URL u : updatedList) { + if (u.equals(jarAOrigLocation)) { + testClassLoads(updatedClassLoader, classA); + } else if (u.equals(jarBOrigLocation)) { + testClassLoads(updatedClassLoader, classB); + } else if (u.equals(jarCOrigLocation)) { + testClassLoads(updatedClassLoader, classC); + } else if (u.equals(jarDOrigLocation)) { + testClassLoads(updatedClassLoader, classD); + } + } + } + if (removed.equals(jarAOrigLocation)) { + testClassFailsToLoad(updatedClassLoader, classA); + } else if (removed.equals(jarBOrigLocation)) { + testClassFailsToLoad(updatedClassLoader, classB); + } else if (removed.equals(jarCOrigLocation)) { + testClassFailsToLoad(updatedClassLoader, classC); + } else if (removed.equals(jarDOrigLocation)) { + testClassFailsToLoad(updatedClassLoader, classD); + } Review Comment: Seems like at least one of these ifs should match, so could add this to defend against future changes to the test or test env that make none of them match. ```suggestion } else { fail(); } ``` ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/cache/CacheUtils.java: ########## @@ -0,0 +1,133 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc.cache; + +import static java.nio.file.attribute.PosixFilePermission.GROUP_READ; +import static java.nio.file.attribute.PosixFilePermission.OTHERS_READ; +import static java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE; +import static java.nio.file.attribute.PosixFilePermission.OWNER_READ; +import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE; +import static java.util.Objects.requireNonNull; + +import java.io.IOException; +import java.net.URI; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.OverlappingFileLockException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.EnumSet; +import java.util.Set; + +import org.apache.accumulo.classloader.lcc.Constants; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory.ContextClassLoaderException; + +public class CacheUtils { + + private static final Set<PosixFilePermission> CACHE_DIR_PERMS = + EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, OTHERS_READ); + private static final FileAttribute<Set<PosixFilePermission>> PERMISSIONS = + PosixFilePermissions.asFileAttribute(CACHE_DIR_PERMS); + private static final String lockFileName = "lock_file"; + + public static class LockInfo { + + private final FileChannel channel; + private final FileLock lock; + + public LockInfo(FileChannel channel, FileLock lock) { + this.channel = requireNonNull(channel, "channel must be supplied"); + this.lock = requireNonNull(lock, "lock must be supplied"); + } + + FileChannel getChannel() { + return channel; + } + + FileLock getLock() { + return lock; + } + + public void unlock() throws IOException { + lock.release(); + channel.close(); + } + + } + + private static Path mkdir(final Path p) throws IOException { + try { + return Files.createDirectory(p, PERMISSIONS); + } catch (FileAlreadyExistsException e) { + return p; + } + } + + public static Path createBaseCacheDir() throws IOException, ContextClassLoaderException { + final String prop = Constants.CACHE_DIR_PROPERTY; + final String cacheDir = System.getProperty(prop); + if (cacheDir == null) { + throw new ContextClassLoaderException("System property " + prop + " not set."); + } + return mkdir(Path.of(URI.create(cacheDir))); + } + + public static Path createOrGetContextCacheDir(final String contextName) + throws IOException, ContextClassLoaderException { + Path baseContextDir = createBaseCacheDir(); + return mkdir(baseContextDir.resolve(contextName)); + } + + /** + * Acquire an exclusive lock on the "lock_file" file in the context cache directory. Returns null + * if lock can not be acquired. Caller MUST call LockInfo.unlock when done manipulating the cache + * directory + */ + public static LockInfo lockContextCacheDir(final Path contextCacheDir) Review Comment: In a follow on PR would be nice to add a test that spins up multiple proccess that try to load the same context and verify that all get their classes w/ error. That would test this code and other code in multiprocess env. ########## modules/local-caching-classloader/src/test/java/org/apache/accumulo/classloader/lcc/LocalCachingContextClassLoaderFactoryTest.java: ########## @@ -0,0 +1,667 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import static org.apache.accumulo.classloader.lcc.TestUtils.createContextDefinitionFile; +import static org.apache.accumulo.classloader.lcc.TestUtils.testClassFailsToLoad; +import static org.apache.accumulo.classloader.lcc.TestUtils.testClassLoads; +import static org.apache.accumulo.classloader.lcc.TestUtils.updateContextDefinitionFile; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; + +import org.apache.accumulo.classloader.lcc.TestUtils.TestClassInfo; +import org.apache.accumulo.classloader.lcc.definition.ContextDefinition; +import org.apache.accumulo.classloader.lcc.definition.Resource; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory.ContextClassLoaderException; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.FsUrlStreamHandlerFactory; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hdfs.MiniDFSCluster; +import org.eclipse.jetty.server.Server; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +public class LocalCachingContextClassLoaderFactoryTest { + + private static final LocalCachingContextClassLoaderFactory FACTORY = + new LocalCachingContextClassLoaderFactory(); + private static final int MONITOR_INTERVAL_SECS = 5; + private static MiniDFSCluster hdfs; + private static FileSystem fs; + private static Server jetty; + private static URL jarAOrigLocation; + private static URL jarBOrigLocation; + private static URL jarCOrigLocation; + private static URL jarDOrigLocation; + private static URL jarEOrigLocation; + private static URL localAllContext; + private static URL hdfsAllContext; + private static URL jettyAllContext; + private static TestClassInfo classA; + private static TestClassInfo classB; + private static TestClassInfo classC; + private static TestClassInfo classD; + + @TempDir + private static java.nio.file.Path tempDir; + + @BeforeAll + public static void beforeAll() throws Exception { + String tmp = tempDir.resolve("base").toUri().toString(); + System.setProperty(Constants.CACHE_DIR_PROPERTY, tmp); + + // Find the Test jar files + jarAOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestA/TestA.jar"); + assertNotNull(jarAOrigLocation); + jarBOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestB/TestB.jar"); + assertNotNull(jarBOrigLocation); + jarCOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestC/TestC.jar"); + assertNotNull(jarCOrigLocation); + jarDOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestD/TestD.jar"); + assertNotNull(jarDOrigLocation); + jarEOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestE/TestE.jar"); + assertNotNull(jarEOrigLocation); + + // Put B into HDFS + hdfs = TestUtils.getMiniCluster(); + URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory(hdfs.getConfiguration(0))); + + fs = hdfs.getFileSystem(); + assertTrue(fs.mkdirs(new Path("/contextB"))); + final Path dst = new Path("/contextB/TestB.jar"); + fs.copyFromLocalFile(new Path(jarBOrigLocation.toURI()), dst); + assertTrue(fs.exists(dst)); + final URL jarBHdfsLocation = new URL(fs.getUri().toString() + dst.toUri().toString()); + + // Have Jetty serve up files from Jar C directory + java.nio.file.Path jarCParentDirectory = + java.nio.file.Path.of(jarCOrigLocation.toURI()).getParent(); + assertNotNull(jarCParentDirectory); + jetty = TestUtils.getJetty(jarCParentDirectory); + final URL jarCJettyLocation = jetty.getURI().resolve("TestC.jar").toURL(); + + // ContextDefinition with all jars + ContextDefinition allJarsDef = ContextDefinition.create("all", MONITOR_INTERVAL_SECS, + jarAOrigLocation, jarBHdfsLocation, jarCJettyLocation, jarDOrigLocation); + String allJarsDefJson = allJarsDef.toJson(); + + // Create local context definition in jar C directory + File localDefFile = jarCParentDirectory.resolve("allContextDefinition.json").toFile(); + Files.writeString(localDefFile.toPath(), allJarsDefJson, StandardOpenOption.CREATE); + assertTrue(Files.exists(localDefFile.toPath())); + + Path hdfsDefFile = new Path("/allContextDefinition.json"); + fs.copyFromLocalFile(new Path(localDefFile.toURI()), hdfsDefFile); + assertTrue(fs.exists(hdfsDefFile)); + + localAllContext = localDefFile.toURI().toURL(); + hdfsAllContext = new URL(fs.getUri().toString() + hdfsDefFile.toUri().toString()); + jettyAllContext = jetty.getURI().resolve("allContextDefinition.json").toURL(); + + classA = new TestClassInfo("test.TestObjectA", "Hello from A"); + classB = new TestClassInfo("test.TestObjectB", "Hello from B"); + classC = new TestClassInfo("test.TestObjectC", "Hello from C"); + classD = new TestClassInfo("test.TestObjectD", "Hello from D"); + } + + @AfterAll + public static void afterAll() throws Exception { + System.clearProperty(Constants.CACHE_DIR_PROPERTY); + if (jetty != null) { + jetty.stop(); + jetty.join(); + } + if (hdfs != null) { + hdfs.shutdown(); + } + } + + @AfterEach + public void afterEach() { + FACTORY.resetForTests(); + } + + @Test + public void testCreateFromLocal() throws Exception { + final ClassLoader cl = FACTORY.getClassLoader(localAllContext.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + } + + @Test + public void testCreateFromHdfs() throws Exception { + final ClassLoader cl = FACTORY.getClassLoader(hdfsAllContext.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + } + + @Test + public void testCreateFromHttp() throws Exception { + final ClassLoader cl = FACTORY.getClassLoader(jettyAllContext.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + } + + @Test + public void testInvalidContextDefinitionURL() { + ContextClassLoaderException ex = + assertThrows(ContextClassLoaderException.class, () -> FACTORY.getClassLoader("/not/a/URL")); + assertEquals("Error getting classloader for context: Expected valid URL to context definition " + + "file but received: /not/a/URL", ex.getMessage()); + } + + @Test + public void testInitialContextDefinitionEmpty() throws Exception { + // Create a new context definition file in HDFS, but with no content + final Path def = createContextDefinitionFile(fs, "EmptyContextDefinitionFile.json", null); + final URL emptyDefUrl = new URL(fs.getUri().toString() + def.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(emptyDefUrl.toString())); + assertEquals( + "Error getting classloader for context: ContextDefinition null for context definition " + + "file: " + emptyDefUrl.toString(), + ex.getMessage()); + } + + @Test + public void testInitialInvalidJson() throws Exception { + // Create a new context definition file in HDFS, but with invalid content + ContextDefinition def = + ContextDefinition.create("invalid", MONITOR_INTERVAL_SECS, jarAOrigLocation); + // write out invalid json + final Path invalid = createContextDefinitionFile(fs, "InvalidContextDefinitionFile.json", + def.toJson().substring(0, 4)); + final URL invalidDefUrl = new URL(fs.getUri().toString() + invalid.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(invalidDefUrl.toString())); + assertTrue(ex.getMessage().startsWith( + "Error getting classloader for context: com.google.gson.stream.MalformedJsonException")); + } + + @Test + public void testInitial() throws Exception { + ContextDefinition def = + ContextDefinition.create("initial", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path initial = + createContextDefinitionFile(fs, "InitialContextDefinitionFile.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ClassLoader cl = FACTORY.getClassLoader(initialDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + } + + @Test + public void testInitialNonExistentResource() throws Exception { + // copy jarA to some other name + java.nio.file.Path jarAPath = java.nio.file.Path.of(jarAOrigLocation.toURI()); + java.nio.file.Path jarAPathParent = jarAPath.getParent(); + assertNotNull(jarAPathParent); + java.nio.file.Path jarACopy = jarAPathParent.resolve("jarACopy.jar"); + assertTrue(!Files.exists(jarACopy)); + Files.copy(jarAPath, jarACopy, StandardCopyOption.REPLACE_EXISTING); + assertTrue(Files.exists(jarACopy)); + + ContextDefinition def = + ContextDefinition.create("initial", MONITOR_INTERVAL_SECS, jarACopy.toUri().toURL()); + + Files.delete(jarACopy); + assertTrue(!Files.exists(jarACopy)); + + final Path initial = createContextDefinitionFile(fs, + "InitialContextDefinitionFileMissingResource.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(initialDefUrl.toString())); + assertTrue(ex.getMessage().endsWith("jarACopy.jar does not exist.")); + } + + @Test + public void testInitialBadResourceURL() throws Exception { + Resource r = new Resource(); + // remove the file:// prefix from the URL + r.setLocation(jarAOrigLocation.toString().substring(6)); + r.setChecksum("1234"); + TreeSet<Resource> resources = new TreeSet<>(); + resources.add(r); + + ContextDefinition def = new ContextDefinition(); + def.setContextName("initial"); + def.setMonitorIntervalSeconds(MONITOR_INTERVAL_SECS); + def.setResources(resources); + + final Path initial = createContextDefinitionFile(fs, + "InitialContextDefinitionBadResourceURL.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(initialDefUrl.toString())); + assertTrue(ex.getMessage().startsWith("Error getting classloader for context: no protocol")); + Throwable t = ex.getCause(); + assertTrue(t instanceof MalformedURLException); + assertTrue(t.getMessage().startsWith("no protocol")); + } + + @Test + public void testInitialBadResourceChecksum() throws Exception { + Resource r = new Resource(); + r.setLocation(jarAOrigLocation.toString()); + r.setChecksum("1234"); + TreeSet<Resource> resources = new TreeSet<>(); + resources.add(r); + + ContextDefinition def = new ContextDefinition(); + def.setContextName("initial"); + def.setMonitorIntervalSeconds(MONITOR_INTERVAL_SECS); + def.setResources(resources); + + final Path initial = createContextDefinitionFile(fs, + "InitialContextDefinitionBadResourceChecksum.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(initialDefUrl.toString())); + assertTrue(ex.getMessage().startsWith("Error getting classloader for context: Checksum")); + Throwable t = ex.getCause(); + assertTrue(t instanceof IllegalStateException); + assertTrue( + t.getMessage().endsWith("TestA.jar does not match checksum in context definition 1234")); + } + + @Test + public void testUpdate() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateContextDefinitionFile.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + // Update the contents of the context definition json file + ContextDefinition updateDef = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarDOrigLocation); + updateContextDefinitionFile(fs, defFilePath, updateDef.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + assertNotEquals(cl, cl2); + + testClassFailsToLoad(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassLoads(cl2, classD); + } + + @Test + public void testUpdateSameClassNameDifferentContent() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateContextDefinitionFile.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + // Update the contents of the context definition json file + ContextDefinition updateDef = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarEOrigLocation); + updateContextDefinitionFile(fs, defFilePath, updateDef.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + assertNotEquals(cl, cl2); + + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazz = + (Class<? extends test.Test>) cl2.loadClass("test.TestObjectA"); + test.Test impl = clazz.getDeclaredConstructor().newInstance(); + assertEquals("Hello from E", impl.hello()); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + } + + @Test + public void testUpdateContextDefinitionEmpty() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateEmptyContextDefinitionFile.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + // Update the contents of the context definition json file with an empty file + updateContextDefinitionFile(fs, defFilePath, null); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + // validate that the classloader has not updated + assertEquals(cl, cl2); + testClassLoads(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + + } + + @Test + public void testUpdateNonExistentResource() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateNonExistentResource.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + // copy jarA to jarACopy + // create a ContextDefinition that references it + // delete jarACopy + java.nio.file.Path jarAPath = java.nio.file.Path.of(jarAOrigLocation.toURI()); + java.nio.file.Path jarAPathParent = jarAPath.getParent(); + assertNotNull(jarAPathParent); + java.nio.file.Path jarACopy = jarAPathParent.resolve("jarACopy.jar"); + assertTrue(!Files.exists(jarACopy)); + Files.copy(jarAPath, jarACopy, StandardCopyOption.REPLACE_EXISTING); + assertTrue(Files.exists(jarACopy)); + ContextDefinition def2 = + ContextDefinition.create("initial", MONITOR_INTERVAL_SECS, jarACopy.toUri().toURL()); + Files.delete(jarACopy); + assertTrue(!Files.exists(jarACopy)); + + updateContextDefinitionFile(fs, defFilePath, def2.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + // validate that the classloader has not updated + assertEquals(cl, cl2); + testClassLoads(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + } + + @Test + public void testUpdateBadResourceChecksum() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateBadResourceChecksum.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + Resource r = new Resource(); + r.setLocation(jarAOrigLocation.toString()); + r.setChecksum("1234"); + TreeSet<Resource> resources = new TreeSet<>(); + resources.add(r); + + ContextDefinition def2 = new ContextDefinition(); + def2.setContextName("update"); + def2.setMonitorIntervalSeconds(MONITOR_INTERVAL_SECS); + def2.setResources(resources); + + updateContextDefinitionFile(fs, defFilePath, def2.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + // validate that the classloader has not updated + assertEquals(cl, cl2); + testClassLoads(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + } + + @Test + public void testUpdateBadResourceURL() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateBadResourceChecksum.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + Resource r = new Resource(); + // remove the file:// prefix from the URL + r.setLocation(jarAOrigLocation.toString().substring(6)); + r.setChecksum("1234"); + TreeSet<Resource> resources = new TreeSet<>(); + resources.add(r); + + ContextDefinition def2 = new ContextDefinition(); + def2.setContextName("initial"); + def2.setMonitorIntervalSeconds(MONITOR_INTERVAL_SECS); + def2.setResources(resources); + + updateContextDefinitionFile(fs, defFilePath, def2.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + // validate that the classloader has not updated + assertEquals(cl, cl2); + testClassLoads(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + } + + @Test + public void testUpdateInvalidJson() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateInvalidContextDefinitionFile.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + ContextDefinition updateDef = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarDOrigLocation); + updateContextDefinitionFile(fs, defFilePath, updateDef.toJson().substring(0, 4)); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + // validate that the classloader has not updated + assertEquals(cl, cl2); + testClassLoads(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassFailsToLoad(cl2, classD); + + // Re-write the updated context definition such that it is now valid + updateContextDefinitionFile(fs, defFilePath, updateDef.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl3 = FACTORY.getClassLoader(updateDefUrl.toString()); + + assertEquals(cl, cl2); + assertNotEquals(cl, cl3); + testClassFailsToLoad(cl3, classA); + testClassFailsToLoad(cl3, classB); + testClassFailsToLoad(cl3, classC); + testClassLoads(cl3, classD); + } + + @Test + public void testChangingContext() throws Exception { + ContextDefinition def = ContextDefinition.create("update", MONITOR_INTERVAL_SECS, + jarAOrigLocation, jarBOrigLocation, jarCOrigLocation, jarDOrigLocation); + final Path update = + createContextDefinitionFile(fs, "UpdateChangingContextDefinition.json", def.toJson()); + final URL updatedDefUrl = new URL(fs.getUri().toString() + update.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updatedDefUrl.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + + final List<URL> masterList = new ArrayList<>(); + masterList.add(jarAOrigLocation); + masterList.add(jarBOrigLocation); + masterList.add(jarCOrigLocation); + masterList.add(jarDOrigLocation); + + List<URL> priorList = masterList; + ClassLoader priorCL = cl; + + for (int i = 0; i < 20; i++) { + final List<URL> updatedList = new ArrayList<>(masterList); + Collections.shuffle(updatedList); + final URL removed = updatedList.remove(0); + + // Update the contents of the context definition json file + ContextDefinition updateDef = ContextDefinition.create("update", MONITOR_INTERVAL_SECS, + updatedList.toArray(new URL[] {})); + updateContextDefinitionFile(fs, update, updateDef.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader updatedClassLoader = FACTORY.getClassLoader(updatedDefUrl.toString()); + + if (updatedList.equals(priorList)) { + assertEquals(priorCL, updatedClassLoader); + } else { + assertNotEquals(cl, updatedClassLoader); + for (URL u : updatedList) { + if (u.equals(jarAOrigLocation)) { + testClassLoads(updatedClassLoader, classA); + } else if (u.equals(jarBOrigLocation)) { + testClassLoads(updatedClassLoader, classB); + } else if (u.equals(jarCOrigLocation)) { + testClassLoads(updatedClassLoader, classC); + } else if (u.equals(jarDOrigLocation)) { + testClassLoads(updatedClassLoader, classD); + } Review Comment: ```suggestion } else { fail(); } ``` ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/cache/CacheUtils.java: ########## @@ -0,0 +1,133 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc.cache; + +import static java.nio.file.attribute.PosixFilePermission.GROUP_READ; +import static java.nio.file.attribute.PosixFilePermission.OTHERS_READ; +import static java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE; +import static java.nio.file.attribute.PosixFilePermission.OWNER_READ; +import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE; +import static java.util.Objects.requireNonNull; + +import java.io.IOException; +import java.net.URI; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.OverlappingFileLockException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.EnumSet; +import java.util.Set; + +import org.apache.accumulo.classloader.lcc.Constants; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory.ContextClassLoaderException; + +public class CacheUtils { + + private static final Set<PosixFilePermission> CACHE_DIR_PERMS = + EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, OTHERS_READ); Review Comment: Maybe make this more restrictive to start with, sometimes classpaths contain config and code. If the restrictive default causes problems, can change it later. ```suggestion EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE); ``` ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/resolvers/LocalFileResolver.java: ########## @@ -0,0 +1,64 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc.resolvers; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory.ContextClassLoaderException; +import org.apache.hadoop.shaded.org.apache.commons.io.FileUtils; + +public final class LocalFileResolver extends FileResolver { + + private final File file; + + public LocalFileResolver(URL url) throws ContextClassLoaderException { + super(url); + if (url.getHost() != null && !url.getHost().isBlank()) { + throw new ContextClassLoaderException( + "Unsupported file url, only local files are supported. host = " + url.getHost()); + } + try { + final URI uri = url.toURI(); + final Path path = Path.of(uri); + if (Files.notExists(Path.of(uri))) { + throw new ContextClassLoaderException("File: " + url + " does not exist."); + } + file = path.toFile(); + } catch (URISyntaxException e) { + throw new ContextClassLoaderException("Error creating URI from url: " + url, e); + } + } + + @Override + public String getFileName() { + return file.getName(); + } + + @Override + public FileInputStream getInputStream() throws IOException { + return FileUtils.openInputStream(file); Review Comment: This uses built in java code instead of hadoop code. Also avoids using a shaded package. ```suggestion public InputStream getInputStream() throws IOException { return new BufferedInputStream(Files.newInputStream(file.toPath())); ``` ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/LocalCachingContextClassLoaderFactory.java: ########## @@ -0,0 +1,193 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.accumulo.classloader.lcc.cache.CacheUtils; +import org.apache.accumulo.classloader.lcc.definition.ContextDefinition; +import org.apache.accumulo.classloader.lcc.definition.Resource; +import org.apache.accumulo.classloader.lcc.resolvers.FileResolver; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +/** + * A ContextClassLoaderFactory implementation that creates and maintains a ClassLoader for a named + * context. This factory expects the parameter passed to {@link #getClassLoader(String)} to be the + * URL of a json formatted {@link ContextDefinition} file. The file contains an interval at which + * this class should monitor the file for changes and a list of {@link Resource} objects. Each + * resource is defined by a URL to the file and an expected MD5 hash value. + * <p> + * The URLs supplied for the context definition file and for the resources can use one of the + * following protocols: file://, http://, or hdfs://. + * <p> + * As this class processes the ContextDefinition it fetches the contents of the resource from the + * resource URL and caches it in a directory on the local filesystem. This class uses the value of + * the system property {@link Constants#CACHE_DIR_PROPERTY} as the root directory and creates a Review Comment: ```suggestion * the system property {@value Constants#CACHE_DIR_PROPERTY} as the root directory and creates a ``` ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/LocalCachingContextClassLoaderFactory.java: ########## @@ -0,0 +1,193 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.accumulo.classloader.lcc.cache.CacheUtils; +import org.apache.accumulo.classloader.lcc.definition.ContextDefinition; +import org.apache.accumulo.classloader.lcc.definition.Resource; +import org.apache.accumulo.classloader.lcc.resolvers.FileResolver; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +/** + * A ContextClassLoaderFactory implementation that creates and maintains a ClassLoader for a named + * context. This factory expects the parameter passed to {@link #getClassLoader(String)} to be the + * URL of a json formatted {@link ContextDefinition} file. The file contains an interval at which + * this class should monitor the file for changes and a list of {@link Resource} objects. Each + * resource is defined by a URL to the file and an expected MD5 hash value. + * <p> + * The URLs supplied for the context definition file and for the resources can use one of the + * following protocols: file://, http://, or hdfs://. + * <p> + * As this class processes the ContextDefinition it fetches the contents of the resource from the + * resource URL and caches it in a directory on the local filesystem. This class uses the value of + * the system property {@link Constants#CACHE_DIR_PROPERTY} as the root directory and creates a + * sub-directory for each context name. Each context cache directory contains a lock file and a copy + * of each fetched resource that is named using the following format: fileName_checksum. + * <p> + * The lock file prevents processes from manipulating the contexts of the context cache directory + * concurrently, which enables the cache directories to be shared among multiple processes on the + * host. + * <p> + * Note that because the cache directory is shared among multiple processes, and one process can't + * know what the other processes are doing, this class cannot clean up the shared cache directory. + * It is left to the user to remove unused context cache directories and unused old files within a + * context cache directory. + */ +public class LocalCachingContextClassLoaderFactory implements ContextClassLoaderFactory { Review Comment: This could have an init method that gets the cache dir from accumulo site config instead of an env var. That would allow the user to put all of the config related to this in the site file as opposed to configuring in the site file and accumulo-env.sh. ``` @Override public void init(ContextClassLoaderEnvironment env) { } ``` If we wanted to do this, would probably be best as a follow on done when testing using this w/ accumulo. ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/LocalCachingContextClassLoaderFactory.java: ########## @@ -0,0 +1,193 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.accumulo.classloader.lcc.cache.CacheUtils; +import org.apache.accumulo.classloader.lcc.definition.ContextDefinition; +import org.apache.accumulo.classloader.lcc.definition.Resource; +import org.apache.accumulo.classloader.lcc.resolvers.FileResolver; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +/** + * A ContextClassLoaderFactory implementation that creates and maintains a ClassLoader for a named + * context. This factory expects the parameter passed to {@link #getClassLoader(String)} to be the + * URL of a json formatted {@link ContextDefinition} file. The file contains an interval at which + * this class should monitor the file for changes and a list of {@link Resource} objects. Each + * resource is defined by a URL to the file and an expected MD5 hash value. + * <p> + * The URLs supplied for the context definition file and for the resources can use one of the + * following protocols: file://, http://, or hdfs://. + * <p> + * As this class processes the ContextDefinition it fetches the contents of the resource from the + * resource URL and caches it in a directory on the local filesystem. This class uses the value of + * the system property {@link Constants#CACHE_DIR_PROPERTY} as the root directory and creates a + * sub-directory for each context name. Each context cache directory contains a lock file and a copy + * of each fetched resource that is named using the following format: fileName_checksum. + * <p> + * The lock file prevents processes from manipulating the contexts of the context cache directory + * concurrently, which enables the cache directories to be shared among multiple processes on the + * host. + * <p> + * Note that because the cache directory is shared among multiple processes, and one process can't + * know what the other processes are doing, this class cannot clean up the shared cache directory. + * It is left to the user to remove unused context cache directories and unused old files within a + * context cache directory. + */ +public class LocalCachingContextClassLoaderFactory implements ContextClassLoaderFactory { + + private static final Logger LOG = + LoggerFactory.getLogger(LocalCachingContextClassLoaderFactory.class); + + private final Cache<String,LocalCachingContext> contexts = + Caffeine.newBuilder().expireAfterAccess(24, TimeUnit.HOURS).build(); + + private ContextDefinition parseContextDefinition(final URL url) + throws ContextClassLoaderException { + LOG.trace("Retrieving context definition file from {}", url); + final FileResolver resolver = FileResolver.resolve(url); + try { + try (InputStream is = resolver.getInputStream()) { + ContextDefinition def = + Constants.GSON.fromJson(new InputStreamReader(is, UTF_8), ContextDefinition.class); + if (def == null) { + throw new ContextClassLoaderException( + "ContextDefinition null for context definition file: " + resolver.getURL()); + } + return def; + } + } catch (IOException e) { + throw new ContextClassLoaderException( + "Error reading context definition file: " + resolver.getURL(), e); + } + } + + /** + * Schedule a task to execute at {@code interval} seconds to update the LocalCachingContext if the + * ContextDefinition has changed. The task schedules a follow-on task at the update interval value + * (if it changed). + */ + private void monitorContext(final String contextLocation, int interval) { + Constants.EXECUTOR.schedule(() -> { + final LocalCachingContext classLoader = contexts.getIfPresent(contextLocation); + if (classLoader == null) { + // context has been removed from the map, no need to check for update + return; + } + final AtomicInteger nextInterval = new AtomicInteger(interval); + final ContextDefinition currentDef = classLoader.getDefinition(); + try { + final URL contextLocationUrl = new URL(contextLocation); + final ContextDefinition update = parseContextDefinition(contextLocationUrl); + if (!Arrays.equals(currentDef.getChecksum(), update.getChecksum())) { + LOG.debug("Context definition for {} has changed", contextLocation); + if (!currentDef.getContextName().equals(update.getContextName())) { + LOG.warn( + "Context name changed for context {}, but context cache directory will remain {} (old={}, new={})", + contextLocation, currentDef.getContextName(), currentDef.getContextName(), + update.getContextName()); + } + classLoader.update(update); + nextInterval.set(update.getMonitorIntervalSeconds()); + } else { + LOG.trace("Context definition for {} has not changed", contextLocation); + } + } catch (ContextClassLoaderException | InterruptedException | IOException + | NoSuchAlgorithmException | URISyntaxException e) { + LOG.error("Error parsing updated context definition at {}. Classloader NOT updated!", + contextLocation, e); + } finally { + monitorContext(contextLocation, nextInterval.get()); + } + }, interval, TimeUnit.SECONDS); + LOG.trace("Monitoring context definition file {} for changes at {} second intervals", + contextLocation, interval); + } + + // for tests only + void resetForTests() { + // Removing the contexts will cause the + // background monitor task to end + contexts.invalidateAll(); + contexts.cleanUp(); + } + + @Override + public ClassLoader getClassLoader(final String contextLocation) + throws ContextClassLoaderException { + requireNonNull(contextLocation, "context name must be supplied"); + try { + final URL contextLocationUrl = new URL(contextLocation); + final AtomicBoolean newlyCreated = new AtomicBoolean(false); + final LocalCachingContext ccl = contexts.get(contextLocation, cn -> { + try { + CacheUtils.createBaseCacheDir(); + ContextDefinition def = parseContextDefinition(contextLocationUrl); + LocalCachingContext newCcl = new LocalCachingContext(def); + newCcl.initialize(); + newlyCreated.set(true); Review Comment: Why not call monitorContext here? ########## modules/local-caching-classloader/src/test/java/org/apache/accumulo/classloader/lcc/LocalCachingContextClassLoaderFactoryTest.java: ########## @@ -0,0 +1,391 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.List; + +import org.apache.accumulo.classloader.lcc.definition.ContextDefinition; +import org.apache.accumulo.classloader.lcc.definition.Resource; +import org.apache.accumulo.classloader.lcc.resolvers.FileResolver; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory.ContextClassLoaderException; +import org.apache.hadoop.fs.FSDataOutputStream; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.FsUrlStreamHandlerFactory; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hdfs.MiniDFSCluster; +import org.eclipse.jetty.server.Server; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +public class LocalCachingContextClassLoaderFactoryTest { + + private static final int MONITOR_INTERVAL_SECS = 5; + private static MiniDFSCluster hdfs; + private static FileSystem fs; + private static Server jetty; + private static URL jarAOrigLocation; + private static URL jarBOrigLocation; + private static URL jarCOrigLocation; + private static URL jarDOrigLocation; + private static URL localAllContext; + private static URL hdfsAllContext; + private static URL jettyAllContext; + + @TempDir + private static java.nio.file.Path tempDir; + + @BeforeAll + public static void beforeAll() throws Exception { + String tmp = tempDir.resolve("base").toUri().toString(); + System.setProperty(Constants.CACHE_DIR_PROPERTY, tmp); + + // Find the Test jar files + jarAOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestA/TestA.jar"); + assertNotNull(jarAOrigLocation); + jarBOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestB/TestB.jar"); + assertNotNull(jarBOrigLocation); + jarCOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestC/TestC.jar"); + assertNotNull(jarCOrigLocation); + jarDOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestD/TestD.jar"); + assertNotNull(jarDOrigLocation); + + // Put B into HDFS + hdfs = TestUtils.getMiniCluster(); + URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory(hdfs.getConfiguration(0))); + + fs = hdfs.getFileSystem(); + assertTrue(fs.mkdirs(new Path("/contextB"))); + final Path dst = new Path("/contextB/TestB.jar"); + fs.copyFromLocalFile(new Path(jarBOrigLocation.toURI()), dst); + assertTrue(fs.exists(dst)); + final URL jarBHdfsLocation = new URL(fs.getUri().toString() + dst.toUri().toString()); + + // Put C into Jetty + java.nio.file.Path jarCParentDirectory = Paths.get(jarCOrigLocation.toURI()).getParent(); + assertNotNull(jarCParentDirectory); + jetty = TestUtils.getJetty(jarCParentDirectory); + final URL jarCJettyLocation = jetty.getURI().resolve("TestC.jar").toURL(); + + // ContextDefinition with all jars + ContextDefinition allJarsDef = createContextDef("all", jarAOrigLocation, jarBHdfsLocation, Review Comment: This could be a follow on, would be helpful to create a little main class or script that a user could point at a dir and it spits out some json. That could be added to readme. ########## modules/local-caching-classloader/src/test/java/org/apache/accumulo/classloader/lcc/LocalCachingContextClassLoaderFactoryTest.java: ########## @@ -0,0 +1,667 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import static org.apache.accumulo.classloader.lcc.TestUtils.createContextDefinitionFile; +import static org.apache.accumulo.classloader.lcc.TestUtils.testClassFailsToLoad; +import static org.apache.accumulo.classloader.lcc.TestUtils.testClassLoads; +import static org.apache.accumulo.classloader.lcc.TestUtils.updateContextDefinitionFile; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; + +import org.apache.accumulo.classloader.lcc.TestUtils.TestClassInfo; +import org.apache.accumulo.classloader.lcc.definition.ContextDefinition; +import org.apache.accumulo.classloader.lcc.definition.Resource; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory.ContextClassLoaderException; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.FsUrlStreamHandlerFactory; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hdfs.MiniDFSCluster; +import org.eclipse.jetty.server.Server; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +public class LocalCachingContextClassLoaderFactoryTest { + + private static final LocalCachingContextClassLoaderFactory FACTORY = + new LocalCachingContextClassLoaderFactory(); + private static final int MONITOR_INTERVAL_SECS = 5; + private static MiniDFSCluster hdfs; + private static FileSystem fs; + private static Server jetty; + private static URL jarAOrigLocation; + private static URL jarBOrigLocation; + private static URL jarCOrigLocation; + private static URL jarDOrigLocation; + private static URL jarEOrigLocation; + private static URL localAllContext; + private static URL hdfsAllContext; + private static URL jettyAllContext; + private static TestClassInfo classA; + private static TestClassInfo classB; + private static TestClassInfo classC; + private static TestClassInfo classD; + + @TempDir + private static java.nio.file.Path tempDir; + + @BeforeAll + public static void beforeAll() throws Exception { + String tmp = tempDir.resolve("base").toUri().toString(); + System.setProperty(Constants.CACHE_DIR_PROPERTY, tmp); + + // Find the Test jar files + jarAOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestA/TestA.jar"); + assertNotNull(jarAOrigLocation); + jarBOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestB/TestB.jar"); + assertNotNull(jarBOrigLocation); + jarCOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestC/TestC.jar"); + assertNotNull(jarCOrigLocation); + jarDOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestD/TestD.jar"); + assertNotNull(jarDOrigLocation); + jarEOrigLocation = + LocalCachingContextClassLoaderFactoryTest.class.getResource("/ClassLoaderTestE/TestE.jar"); + assertNotNull(jarEOrigLocation); + + // Put B into HDFS + hdfs = TestUtils.getMiniCluster(); + URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory(hdfs.getConfiguration(0))); + + fs = hdfs.getFileSystem(); + assertTrue(fs.mkdirs(new Path("/contextB"))); + final Path dst = new Path("/contextB/TestB.jar"); + fs.copyFromLocalFile(new Path(jarBOrigLocation.toURI()), dst); + assertTrue(fs.exists(dst)); + final URL jarBHdfsLocation = new URL(fs.getUri().toString() + dst.toUri().toString()); + + // Have Jetty serve up files from Jar C directory + java.nio.file.Path jarCParentDirectory = + java.nio.file.Path.of(jarCOrigLocation.toURI()).getParent(); + assertNotNull(jarCParentDirectory); + jetty = TestUtils.getJetty(jarCParentDirectory); + final URL jarCJettyLocation = jetty.getURI().resolve("TestC.jar").toURL(); + + // ContextDefinition with all jars + ContextDefinition allJarsDef = ContextDefinition.create("all", MONITOR_INTERVAL_SECS, + jarAOrigLocation, jarBHdfsLocation, jarCJettyLocation, jarDOrigLocation); + String allJarsDefJson = allJarsDef.toJson(); + + // Create local context definition in jar C directory + File localDefFile = jarCParentDirectory.resolve("allContextDefinition.json").toFile(); + Files.writeString(localDefFile.toPath(), allJarsDefJson, StandardOpenOption.CREATE); + assertTrue(Files.exists(localDefFile.toPath())); + + Path hdfsDefFile = new Path("/allContextDefinition.json"); + fs.copyFromLocalFile(new Path(localDefFile.toURI()), hdfsDefFile); + assertTrue(fs.exists(hdfsDefFile)); + + localAllContext = localDefFile.toURI().toURL(); + hdfsAllContext = new URL(fs.getUri().toString() + hdfsDefFile.toUri().toString()); + jettyAllContext = jetty.getURI().resolve("allContextDefinition.json").toURL(); + + classA = new TestClassInfo("test.TestObjectA", "Hello from A"); + classB = new TestClassInfo("test.TestObjectB", "Hello from B"); + classC = new TestClassInfo("test.TestObjectC", "Hello from C"); + classD = new TestClassInfo("test.TestObjectD", "Hello from D"); + } + + @AfterAll + public static void afterAll() throws Exception { + System.clearProperty(Constants.CACHE_DIR_PROPERTY); + if (jetty != null) { + jetty.stop(); + jetty.join(); + } + if (hdfs != null) { + hdfs.shutdown(); + } + } + + @AfterEach + public void afterEach() { + FACTORY.resetForTests(); + } + + @Test + public void testCreateFromLocal() throws Exception { + final ClassLoader cl = FACTORY.getClassLoader(localAllContext.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + } + + @Test + public void testCreateFromHdfs() throws Exception { + final ClassLoader cl = FACTORY.getClassLoader(hdfsAllContext.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + } + + @Test + public void testCreateFromHttp() throws Exception { + final ClassLoader cl = FACTORY.getClassLoader(jettyAllContext.toString()); + testClassLoads(cl, classA); + testClassLoads(cl, classB); + testClassLoads(cl, classC); + testClassLoads(cl, classD); + } + + @Test + public void testInvalidContextDefinitionURL() { + ContextClassLoaderException ex = + assertThrows(ContextClassLoaderException.class, () -> FACTORY.getClassLoader("/not/a/URL")); + assertEquals("Error getting classloader for context: Expected valid URL to context definition " + + "file but received: /not/a/URL", ex.getMessage()); + } + + @Test + public void testInitialContextDefinitionEmpty() throws Exception { + // Create a new context definition file in HDFS, but with no content + final Path def = createContextDefinitionFile(fs, "EmptyContextDefinitionFile.json", null); + final URL emptyDefUrl = new URL(fs.getUri().toString() + def.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(emptyDefUrl.toString())); + assertEquals( + "Error getting classloader for context: ContextDefinition null for context definition " + + "file: " + emptyDefUrl.toString(), + ex.getMessage()); + } + + @Test + public void testInitialInvalidJson() throws Exception { + // Create a new context definition file in HDFS, but with invalid content + ContextDefinition def = + ContextDefinition.create("invalid", MONITOR_INTERVAL_SECS, jarAOrigLocation); + // write out invalid json + final Path invalid = createContextDefinitionFile(fs, "InvalidContextDefinitionFile.json", + def.toJson().substring(0, 4)); + final URL invalidDefUrl = new URL(fs.getUri().toString() + invalid.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(invalidDefUrl.toString())); + assertTrue(ex.getMessage().startsWith( + "Error getting classloader for context: com.google.gson.stream.MalformedJsonException")); + } + + @Test + public void testInitial() throws Exception { + ContextDefinition def = + ContextDefinition.create("initial", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path initial = + createContextDefinitionFile(fs, "InitialContextDefinitionFile.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ClassLoader cl = FACTORY.getClassLoader(initialDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + } + + @Test + public void testInitialNonExistentResource() throws Exception { + // copy jarA to some other name + java.nio.file.Path jarAPath = java.nio.file.Path.of(jarAOrigLocation.toURI()); + java.nio.file.Path jarAPathParent = jarAPath.getParent(); + assertNotNull(jarAPathParent); + java.nio.file.Path jarACopy = jarAPathParent.resolve("jarACopy.jar"); + assertTrue(!Files.exists(jarACopy)); + Files.copy(jarAPath, jarACopy, StandardCopyOption.REPLACE_EXISTING); + assertTrue(Files.exists(jarACopy)); + + ContextDefinition def = + ContextDefinition.create("initial", MONITOR_INTERVAL_SECS, jarACopy.toUri().toURL()); + + Files.delete(jarACopy); + assertTrue(!Files.exists(jarACopy)); + + final Path initial = createContextDefinitionFile(fs, + "InitialContextDefinitionFileMissingResource.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(initialDefUrl.toString())); + assertTrue(ex.getMessage().endsWith("jarACopy.jar does not exist.")); + } + + @Test + public void testInitialBadResourceURL() throws Exception { + Resource r = new Resource(); + // remove the file:// prefix from the URL + r.setLocation(jarAOrigLocation.toString().substring(6)); + r.setChecksum("1234"); + TreeSet<Resource> resources = new TreeSet<>(); + resources.add(r); + + ContextDefinition def = new ContextDefinition(); + def.setContextName("initial"); + def.setMonitorIntervalSeconds(MONITOR_INTERVAL_SECS); + def.setResources(resources); + + final Path initial = createContextDefinitionFile(fs, + "InitialContextDefinitionBadResourceURL.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(initialDefUrl.toString())); + assertTrue(ex.getMessage().startsWith("Error getting classloader for context: no protocol")); + Throwable t = ex.getCause(); + assertTrue(t instanceof MalformedURLException); + assertTrue(t.getMessage().startsWith("no protocol")); + } + + @Test + public void testInitialBadResourceChecksum() throws Exception { + Resource r = new Resource(); + r.setLocation(jarAOrigLocation.toString()); + r.setChecksum("1234"); + TreeSet<Resource> resources = new TreeSet<>(); + resources.add(r); + + ContextDefinition def = new ContextDefinition(); + def.setContextName("initial"); + def.setMonitorIntervalSeconds(MONITOR_INTERVAL_SECS); + def.setResources(resources); + + final Path initial = createContextDefinitionFile(fs, + "InitialContextDefinitionBadResourceChecksum.json", def.toJson()); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> FACTORY.getClassLoader(initialDefUrl.toString())); + assertTrue(ex.getMessage().startsWith("Error getting classloader for context: Checksum")); + Throwable t = ex.getCause(); + assertTrue(t instanceof IllegalStateException); + assertTrue( + t.getMessage().endsWith("TestA.jar does not match checksum in context definition 1234")); + } + + @Test + public void testUpdate() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateContextDefinitionFile.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + // Update the contents of the context definition json file + ContextDefinition updateDef = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarDOrigLocation); + updateContextDefinitionFile(fs, defFilePath, updateDef.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + assertNotEquals(cl, cl2); + + testClassFailsToLoad(cl2, classA); + testClassFailsToLoad(cl2, classB); + testClassFailsToLoad(cl2, classC); + testClassLoads(cl2, classD); + } + + @Test + public void testUpdateSameClassNameDifferentContent() throws Exception { + final ContextDefinition def = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarAOrigLocation); + final Path defFilePath = + createContextDefinitionFile(fs, "UpdateContextDefinitionFile.json", def.toJson()); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final ClassLoader cl = FACTORY.getClassLoader(updateDefUrl.toString()); + + testClassLoads(cl, classA); + testClassFailsToLoad(cl, classB); + testClassFailsToLoad(cl, classC); + testClassFailsToLoad(cl, classD); + + // Update the contents of the context definition json file + ContextDefinition updateDef = + ContextDefinition.create("update", MONITOR_INTERVAL_SECS, jarEOrigLocation); + updateContextDefinitionFile(fs, defFilePath, updateDef.toJson()); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = FACTORY.getClassLoader(updateDefUrl.toString()); + + assertNotEquals(cl, cl2); + + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazz = + (Class<? extends test.Test>) cl2.loadClass("test.TestObjectA"); Review Comment: Could remove this string literal. ```suggestion (Class<? extends test.Test>) cl2.loadClass(classA.getClassName()); ``` ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/LocalCachingContextClassLoaderFactory.java: ########## @@ -0,0 +1,193 @@ +/* + * 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 + * + * https://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.accumulo.classloader.lcc; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.accumulo.classloader.lcc.cache.CacheUtils; +import org.apache.accumulo.classloader.lcc.definition.ContextDefinition; +import org.apache.accumulo.classloader.lcc.definition.Resource; +import org.apache.accumulo.classloader.lcc.resolvers.FileResolver; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +/** + * A ContextClassLoaderFactory implementation that creates and maintains a ClassLoader for a named + * context. This factory expects the parameter passed to {@link #getClassLoader(String)} to be the + * URL of a json formatted {@link ContextDefinition} file. The file contains an interval at which + * this class should monitor the file for changes and a list of {@link Resource} objects. Each + * resource is defined by a URL to the file and an expected MD5 hash value. + * <p> + * The URLs supplied for the context definition file and for the resources can use one of the + * following protocols: file://, http://, or hdfs://. + * <p> + * As this class processes the ContextDefinition it fetches the contents of the resource from the + * resource URL and caches it in a directory on the local filesystem. This class uses the value of + * the system property {@link Constants#CACHE_DIR_PROPERTY} as the root directory and creates a + * sub-directory for each context name. Each context cache directory contains a lock file and a copy + * of each fetched resource that is named using the following format: fileName_checksum. + * <p> + * The lock file prevents processes from manipulating the contexts of the context cache directory + * concurrently, which enables the cache directories to be shared among multiple processes on the + * host. + * <p> + * Note that because the cache directory is shared among multiple processes, and one process can't + * know what the other processes are doing, this class cannot clean up the shared cache directory. + * It is left to the user to remove unused context cache directories and unused old files within a + * context cache directory. + */ +public class LocalCachingContextClassLoaderFactory implements ContextClassLoaderFactory { + + private static final Logger LOG = + LoggerFactory.getLogger(LocalCachingContextClassLoaderFactory.class); + + private final Cache<String,LocalCachingContext> contexts = + Caffeine.newBuilder().expireAfterAccess(24, TimeUnit.HOURS).build(); + + private ContextDefinition parseContextDefinition(final URL url) + throws ContextClassLoaderException { + LOG.trace("Retrieving context definition file from {}", url); + final FileResolver resolver = FileResolver.resolve(url); + try { + try (InputStream is = resolver.getInputStream()) { + ContextDefinition def = + Constants.GSON.fromJson(new InputStreamReader(is, UTF_8), ContextDefinition.class); + if (def == null) { + throw new ContextClassLoaderException( + "ContextDefinition null for context definition file: " + resolver.getURL()); + } + return def; + } + } catch (IOException e) { + throw new ContextClassLoaderException( + "Error reading context definition file: " + resolver.getURL(), e); + } + } + + /** + * Schedule a task to execute at {@code interval} seconds to update the LocalCachingContext if the + * ContextDefinition has changed. The task schedules a follow-on task at the update interval value + * (if it changed). + */ + private void monitorContext(final String contextLocation, int interval) { + Constants.EXECUTOR.schedule(() -> { + final LocalCachingContext classLoader = contexts.getIfPresent(contextLocation); + if (classLoader == null) { + // context has been removed from the map, no need to check for update + return; + } + final AtomicInteger nextInterval = new AtomicInteger(interval); Review Comment: Seems like this could be int, would slightly simplify the code. ```suggestion int nextInterval = interval; ``` -- 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. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
