keith-turner commented on code in PR #30: URL: https://github.com/apache/accumulo-classloaders/pull/30#discussion_r2543748557
########## 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, + jarCJettyLocation, jarDOrigLocation); + String allJarsDefJson = allJarsDef.toJson(); + System.out.println(allJarsDefJson); + + File localDefFile = new File(jarCParentDirectory.toFile(), "allContextDefinition.json"); + 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(); + + } + + @AfterAll + public static void afterAll() throws Exception { + if (jetty != null) { Review Comment: This could help avoid that props tmp dir from this test potentially being seen by other test. ```suggestion System.clearProperty(Constants.CACHE_DIR_PROPERTY); if (jetty != null) { ``` ########## modules/local-caching-classloader/src/test/java/org/apache/accumulo/classloader/lcc/cache/CacheUtilsTest.java: ########## @@ -0,0 +1,154 @@ +/* + * 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 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.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.accumulo.classloader.lcc.Constants; +import org.apache.accumulo.classloader.lcc.cache.CacheUtils.LockInfo; +import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory.ContextClassLoaderException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CacheUtilsTest { + + private static final Logger LOG = LoggerFactory.getLogger(CacheUtilsTest.class); + + @TempDir + private static Path tempDir; + + @BeforeEach + public void beforeEach() { + String tmp = tempDir.resolve("base").toUri().toString(); + LOG.info("Setting cache base directory to {}", tmp); + System.setProperty(Constants.CACHE_DIR_PROPERTY, tmp); Review Comment: would be good to clear this in an after each ########## modules/local-caching-classloader/src/test/java/org/apache/accumulo/classloader/lcc/LocalCachingContextTest.java: ########## @@ -0,0 +1,221 @@ +/* + * 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.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.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +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.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 LocalCachingContextTest { + + private static final String CONTEXT_NAME = "TEST_CONTEXT"; + private static final int MONITOR_INTERVAL_SECS = 5; + private static MiniDFSCluster hdfs; + private static Server jetty; + private static ContextDefinition def; + + @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 + final URL jarAOrigLocation = + LocalCachingContextTest.class.getResource("/ClassLoaderTestA/TestA.jar"); + assertNotNull(jarAOrigLocation); + final URL jarBOrigLocation = + LocalCachingContextTest.class.getResource("/ClassLoaderTestB/TestB.jar"); + assertNotNull(jarBOrigLocation); + final URL jarCOrigLocation = + LocalCachingContextTest.class.getResource("/ClassLoaderTestC/TestC.jar"); + assertNotNull(jarCOrigLocation); + + // Put B into HDFS + hdfs = TestUtils.getMiniCluster(); + final FileSystem 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)); + URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory(hdfs.getConfiguration(0))); + final URL jarBNewLocation = new URL(fs.getUri().toString() + dst.toUri().toString()); + + // Put C into Jetty + java.nio.file.Path jarCParentDirectory = Paths.get(jarCOrigLocation.toURI()).getParent(); + jetty = TestUtils.getJetty(jarCParentDirectory); + final URL jarCNewLocation = jetty.getURI().resolve("TestC.jar").toURL(); + + // Create ContextDefinition with all three resources + final List<Resource> resources = new ArrayList<>(); + resources.add(new Resource(jarAOrigLocation.toString(), + TestUtils.computeResourceChecksum(jarAOrigLocation))); + resources.add(new Resource(jarBNewLocation.toString(), + TestUtils.computeResourceChecksum(jarBOrigLocation))); + resources.add(new Resource(jarCNewLocation.toString(), + TestUtils.computeResourceChecksum(jarCOrigLocation))); + + def = new ContextDefinition(CONTEXT_NAME, MONITOR_INTERVAL_SECS, resources); + } + + @AfterAll + public static void afterAll() throws Exception { + jetty.stop(); Review Comment: ```suggestion System.clearProperty(Constants.CACHE_DIR_PROPERTY); jetty.stop(); ``` ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/LocalCachingContextClassLoaderFactory.java: ########## @@ -0,0 +1,182 @@ +/* + * 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 {}", + contextLocation, currentDef.getContextName()); + } + classLoader.update(update); + nextInterval.set(update.getMonitorIntervalSeconds()); + } else { + LOG.debug("Context definition for {} has not changed", contextLocation); Review Comment: This will be a routine occurrence, maybe it should log at trace instead of debug. ########## 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, + jarCJettyLocation, jarDOrigLocation); + String allJarsDefJson = allJarsDef.toJson(); + System.out.println(allJarsDefJson); + + File localDefFile = new File(jarCParentDirectory.toFile(), "allContextDefinition.json"); + 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(); + + } + + @AfterAll + public static void afterAll() throws Exception { + if (jetty != null) { + jetty.stop(); + jetty.join(); + } + if (hdfs != null) { + hdfs.shutdown(); + } + } + + @Test + public void testInvalidContextDefinitionURL() { + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path empty = new Path("/contextDefs/EmptyContextDefinitionFile.json"); + assertTrue(fs.createNewFile(empty)); + assertTrue(fs.exists(empty)); + final URL emptyDefUrl = new URL(fs.getUri().toString() + empty.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 testInitialContextDefinitionInvalid() throws Exception { + // Create a new context definition file in HDFS, but with invalid content + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path invalid = new Path("/contextDefs/InvalidContextDefinitionFile.json"); + try (FSDataOutputStream out = fs.create(invalid)) { + ContextDefinition def = createContextDef("invalid", jarAOrigLocation); + out.writeBytes(def.toJson().substring(0, 4)); + } + assertTrue(fs.exists(invalid)); + final URL invalidDefUrl = new URL(fs.getUri().toString() + invalid.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 { + // Create a new context definition file in HDFS, but with invalid content + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path initial = new Path("/contextDefs/InitialContextDefinitionFile.json"); + try (FSDataOutputStream out = fs.create(initial)) { + ContextDefinition def = createContextDef("initial", jarAOrigLocation); + out.writeBytes(def.toJson()); + } + assertTrue(fs.exists(initial)); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + ClassLoader cl = factory.getClassLoader(initialDefUrl.toString()); + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazzA = + (Class<? extends test.Test>) cl.loadClass("test.TestObjectA"); + test.Test a1 = clazzA.getDeclaredConstructor().newInstance(); + assertEquals("Hello from A", a1.hello()); + } + + @Test + public void testUpdate() throws Exception { + // Create a new context definition file in HDFS + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path defFilePath = new Path("/contextDefs/UpdateContextDefinitionFile.json"); + final ContextDefinition def = createContextDef("update", jarAOrigLocation); + try (FSDataOutputStream out = fs.create(defFilePath)) { + out.writeBytes(def.toJson()); + } + assertTrue(fs.exists(defFilePath)); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final LocalCachingContextClassLoaderFactory factory = + new LocalCachingContextClassLoaderFactory(); + final ClassLoader cl = factory.getClassLoader(updateDefUrl.toString()); + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazzA = + (Class<? extends test.Test>) cl.loadClass("test.TestObjectA"); + test.Test a1 = clazzA.getDeclaredConstructor().newInstance(); + assertEquals("Hello from A", a1.hello()); + + // Update the contents of the context definition json file + fs.delete(defFilePath, false); + assertFalse(fs.exists(defFilePath)); + + ContextDefinition updateDef = createContextDef("update", jarDOrigLocation); + try (FSDataOutputStream out = fs.create(defFilePath)) { + out.writeBytes(updateDef.toJson()); + } + assertTrue(fs.exists(defFilePath)); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = factory.getClassLoader(updateDefUrl.toString()); + assertThrows(ClassNotFoundException.class, () -> cl2.loadClass("test.TestObjectA")); + + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazzD = + (Class<? extends test.Test>) cl2.loadClass("test.TestObjectD"); + test.Test d1 = clazzD.getDeclaredConstructor().newInstance(); + assertEquals("Hello from D", d1.hello()); + + } + + @Test + public void testUpdateInvalid() throws Exception { + // Create a new context definition file in HDFS, but with invalid content + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path defFilePath = new Path("/contextDefs/UpdateContextDefinitionFile.json"); + final ContextDefinition def = createContextDef("update", jarAOrigLocation); + try (FSDataOutputStream out = fs.create(defFilePath)) { + out.writeBytes(def.toJson()); + } + assertTrue(fs.exists(defFilePath)); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final LocalCachingContextClassLoaderFactory factory = + new LocalCachingContextClassLoaderFactory(); + final ClassLoader cl = factory.getClassLoader(updateDefUrl.toString()); + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazzA = + (Class<? extends test.Test>) cl.loadClass("test.TestObjectA"); + test.Test a1 = clazzA.getDeclaredConstructor().newInstance(); + assertEquals("Hello from A", a1.hello()); + + // Update the contents of the context definition json file + fs.delete(defFilePath, false); + assertFalse(fs.exists(defFilePath)); + + ContextDefinition updateDef = createContextDef("update", jarDOrigLocation); + try (FSDataOutputStream out = fs.create(defFilePath)) { + out.writeBytes(updateDef.toJson().substring(0, 4)); + } + assertTrue(fs.exists(defFilePath)); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = factory.getClassLoader(updateDefUrl.toString()); + + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazzA2 = + (Class<? extends test.Test>) cl2.loadClass("test.TestObjectA"); + test.Test a2 = clazzA2.getDeclaredConstructor().newInstance(); + assertEquals("Hello from A", a2.hello()); + assertEquals(clazzA, clazzA2); + + assertThrows(ClassNotFoundException.class, () -> cl2.loadClass("test.TestObjectD")); Review Comment: Would be good to test if the definition is fixed that things start working to ensure its not left in a bad state indefinitely. Seems like could just add more to this test to do that, update the defFilePAth for a 3rd time w/ good json. ########## 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, + jarCJettyLocation, jarDOrigLocation); + String allJarsDefJson = allJarsDef.toJson(); + System.out.println(allJarsDefJson); + + File localDefFile = new File(jarCParentDirectory.toFile(), "allContextDefinition.json"); + 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(); + + } + + @AfterAll + public static void afterAll() throws Exception { + if (jetty != null) { + jetty.stop(); + jetty.join(); + } + if (hdfs != null) { + hdfs.shutdown(); + } + } + + @Test + public void testInvalidContextDefinitionURL() { + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path empty = new Path("/contextDefs/EmptyContextDefinitionFile.json"); + assertTrue(fs.createNewFile(empty)); + assertTrue(fs.exists(empty)); + final URL emptyDefUrl = new URL(fs.getUri().toString() + empty.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 testInitialContextDefinitionInvalid() throws Exception { + // Create a new context definition file in HDFS, but with invalid content + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path invalid = new Path("/contextDefs/InvalidContextDefinitionFile.json"); + try (FSDataOutputStream out = fs.create(invalid)) { + ContextDefinition def = createContextDef("invalid", jarAOrigLocation); + out.writeBytes(def.toJson().substring(0, 4)); + } + assertTrue(fs.exists(invalid)); + final URL invalidDefUrl = new URL(fs.getUri().toString() + invalid.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 { + // Create a new context definition file in HDFS, but with invalid content + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path initial = new Path("/contextDefs/InitialContextDefinitionFile.json"); + try (FSDataOutputStream out = fs.create(initial)) { + ContextDefinition def = createContextDef("initial", jarAOrigLocation); + out.writeBytes(def.toJson()); + } + assertTrue(fs.exists(initial)); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + ClassLoader cl = factory.getClassLoader(initialDefUrl.toString()); + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazzA = + (Class<? extends test.Test>) cl.loadClass("test.TestObjectA"); + test.Test a1 = clazzA.getDeclaredConstructor().newInstance(); + assertEquals("Hello from A", a1.hello()); + } + + @Test + public void testUpdate() throws Exception { + // Create a new context definition file in HDFS + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path defFilePath = new Path("/contextDefs/UpdateContextDefinitionFile.json"); + final ContextDefinition def = createContextDef("update", jarAOrigLocation); + try (FSDataOutputStream out = fs.create(defFilePath)) { + out.writeBytes(def.toJson()); + } + assertTrue(fs.exists(defFilePath)); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final LocalCachingContextClassLoaderFactory factory = + new LocalCachingContextClassLoaderFactory(); + final ClassLoader cl = factory.getClassLoader(updateDefUrl.toString()); + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazzA = + (Class<? extends test.Test>) cl.loadClass("test.TestObjectA"); + test.Test a1 = clazzA.getDeclaredConstructor().newInstance(); + assertEquals("Hello from A", a1.hello()); + Review Comment: prior to the update it would be good to verify D is not around for some unexpected reason ```suggestion assertThrows(ClassNotFoundException.class, () -> cl.loadClass("test.TestObjectD")); ``` ########## 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, + jarCJettyLocation, jarDOrigLocation); + String allJarsDefJson = allJarsDef.toJson(); + System.out.println(allJarsDefJson); + + File localDefFile = new File(jarCParentDirectory.toFile(), "allContextDefinition.json"); + 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(); + + } + + @AfterAll + public static void afterAll() throws Exception { + if (jetty != null) { + jetty.stop(); + jetty.join(); + } + if (hdfs != null) { + hdfs.shutdown(); + } + } + + @Test + public void testInvalidContextDefinitionURL() { + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path empty = new Path("/contextDefs/EmptyContextDefinitionFile.json"); + assertTrue(fs.createNewFile(empty)); + assertTrue(fs.exists(empty)); + final URL emptyDefUrl = new URL(fs.getUri().toString() + empty.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 testInitialContextDefinitionInvalid() throws Exception { + // Create a new context definition file in HDFS, but with invalid content + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path invalid = new Path("/contextDefs/InvalidContextDefinitionFile.json"); + try (FSDataOutputStream out = fs.create(invalid)) { + ContextDefinition def = createContextDef("invalid", jarAOrigLocation); + out.writeBytes(def.toJson().substring(0, 4)); Review Comment: Took me a minute to see this little jewel. ```suggestion // create malformed json out.writeBytes(def.toJson().substring(0, 4)); ``` ########## 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, + jarCJettyLocation, jarDOrigLocation); + String allJarsDefJson = allJarsDef.toJson(); + System.out.println(allJarsDefJson); + + File localDefFile = new File(jarCParentDirectory.toFile(), "allContextDefinition.json"); + 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(); + + } + + @AfterAll + public static void afterAll() throws Exception { + if (jetty != null) { + jetty.stop(); + jetty.join(); + } + if (hdfs != null) { + hdfs.shutdown(); + } + } + + @Test + public void testInvalidContextDefinitionURL() { + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path empty = new Path("/contextDefs/EmptyContextDefinitionFile.json"); + assertTrue(fs.createNewFile(empty)); + assertTrue(fs.exists(empty)); + final URL emptyDefUrl = new URL(fs.getUri().toString() + empty.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 testInitialContextDefinitionInvalid() throws Exception { + // Create a new context definition file in HDFS, but with invalid content + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path invalid = new Path("/contextDefs/InvalidContextDefinitionFile.json"); + try (FSDataOutputStream out = fs.create(invalid)) { + ContextDefinition def = createContextDef("invalid", jarAOrigLocation); + out.writeBytes(def.toJson().substring(0, 4)); + } + assertTrue(fs.exists(invalid)); + final URL invalidDefUrl = new URL(fs.getUri().toString() + invalid.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + ContextClassLoaderException ex = assertThrows(ContextClassLoaderException.class, + () -> factory.getClassLoader(invalidDefUrl.toString())); + assertTrue(ex.getMessage().startsWith( + "Error getting classloader for context: com.google.gson.stream.MalformedJsonException")); + } + Review Comment: Could add some more test for cases that should cause `factory.getClassLoader` to fail. * Valid json with a resource entry that has an incorrect hash * Valid json with a resource entry that points to a non existent file * Valid json with a resource enttry that has a malformed URI ########## 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: How would you expect a user to create this json? ########## modules/local-caching-classloader/README.md: ########## @@ -0,0 +1,69 @@ +<!-- +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +--> + +# Local Caching ClassLoader + +The LocalCachingContextClassLoaderFactory is an Accumulo ContextClassLoaderFactory implementation that creates and maintains a +LocalCachingContext. The `LocalCachingContextClassLoaderFactory.getClassLoader(String)` method expects the method +argument to be a valid `file`, `hdfs`, `http` or `https` URL to a context definition file. + +The context definition file is a JSON formatted file that contains the name of the context, the interval in seconds at which +the context definition file should be monitored, and a list of classpath resources. The LocalCachingContextClassLoaderFactory +creates the LocalCachingContext based on the initial contents of the context definition file, and updates the classloader +as changes are noticed based on the monitoring interval. An example of the context definition file is below. + +``` +{ + "contextName": "myContext", + "monitorIntervalSeconds": 5, + "resources": [ + { + "location": "file:/home/user/ClassLoaderTestA/TestA.jar", + "checksum": "a10883244d70d971ec25cbfa69b6f08f" + }, + { + "location": "hdfs://localhost:8020/contextB/TestB.jar", + "checksum": "a02a3b7026528156fb782dcdecaaa097" + }, + { + "location": "http://localhost:80/TestC.jar", + "checksum": "f464e66f6d07a41c656e8f4679509215" + } + ] +} +``` + +The system property `accumulo.classloader.cache.dir` is required to be set to a local directory on the host. The +LocalCachingContext creates a directory at this location for each named context. Each context cache directory +contains a lock file and a copy of each fetched resource that is named in the context definition file using the format: +`fileName_checksum`. The lock file is used with Java's `FileChannel.tryLock` to enable exclusive access (on supported +platforms) to the directory from different processes on the same host. + +## Cleanup + +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. Review Comment: Not a change for this PR, but maybe we could get this automated later using hard links in the FS. Each process creates its own hard links to the main file and when a file is no longer in use by a process it removes its own hard link. The main file can be removed by any process when it has no hard links. Would need to do something to handle process death, would need to be able to detect dirs for dead processes and remove all their links. ########## modules/local-caching-classloader/src/test/java/org/apache/accumulo/classloader/lcc/LocalCachingContextTest.java: ########## @@ -0,0 +1,221 @@ +/* + * 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.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.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +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.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 LocalCachingContextTest { + + private static final String CONTEXT_NAME = "TEST_CONTEXT"; + private static final int MONITOR_INTERVAL_SECS = 5; + private static MiniDFSCluster hdfs; + private static Server jetty; + private static ContextDefinition def; + + @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 + final URL jarAOrigLocation = + LocalCachingContextTest.class.getResource("/ClassLoaderTestA/TestA.jar"); + assertNotNull(jarAOrigLocation); + final URL jarBOrigLocation = + LocalCachingContextTest.class.getResource("/ClassLoaderTestB/TestB.jar"); + assertNotNull(jarBOrigLocation); + final URL jarCOrigLocation = + LocalCachingContextTest.class.getResource("/ClassLoaderTestC/TestC.jar"); + assertNotNull(jarCOrigLocation); + + // Put B into HDFS + hdfs = TestUtils.getMiniCluster(); + final FileSystem 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)); + URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory(hdfs.getConfiguration(0))); + final URL jarBNewLocation = new URL(fs.getUri().toString() + dst.toUri().toString()); + + // Put C into Jetty + java.nio.file.Path jarCParentDirectory = Paths.get(jarCOrigLocation.toURI()).getParent(); + jetty = TestUtils.getJetty(jarCParentDirectory); + final URL jarCNewLocation = jetty.getURI().resolve("TestC.jar").toURL(); + + // Create ContextDefinition with all three resources + final List<Resource> resources = new ArrayList<>(); + resources.add(new Resource(jarAOrigLocation.toString(), + TestUtils.computeResourceChecksum(jarAOrigLocation))); + resources.add(new Resource(jarBNewLocation.toString(), + TestUtils.computeResourceChecksum(jarBOrigLocation))); + resources.add(new Resource(jarCNewLocation.toString(), + TestUtils.computeResourceChecksum(jarCOrigLocation))); + + def = new ContextDefinition(CONTEXT_NAME, MONITOR_INTERVAL_SECS, resources); + } + + @AfterAll + public static void afterAll() throws Exception { + jetty.stop(); + jetty.join(); Review Comment: Would probably be good to check jetty and hdfs are null like the other unit test does in after all. ########## 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, + jarCJettyLocation, jarDOrigLocation); + String allJarsDefJson = allJarsDef.toJson(); + System.out.println(allJarsDefJson); + + File localDefFile = new File(jarCParentDirectory.toFile(), "allContextDefinition.json"); + 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(); + + } + + @AfterAll + public static void afterAll() throws Exception { + if (jetty != null) { + jetty.stop(); + jetty.join(); + } + if (hdfs != null) { + hdfs.shutdown(); + } + } + + @Test + public void testInvalidContextDefinitionURL() { + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path empty = new Path("/contextDefs/EmptyContextDefinitionFile.json"); + assertTrue(fs.createNewFile(empty)); + assertTrue(fs.exists(empty)); + final URL emptyDefUrl = new URL(fs.getUri().toString() + empty.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 testInitialContextDefinitionInvalid() throws Exception { + // Create a new context definition file in HDFS, but with invalid content + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path invalid = new Path("/contextDefs/InvalidContextDefinitionFile.json"); + try (FSDataOutputStream out = fs.create(invalid)) { + ContextDefinition def = createContextDef("invalid", jarAOrigLocation); + out.writeBytes(def.toJson().substring(0, 4)); + } + assertTrue(fs.exists(invalid)); + final URL invalidDefUrl = new URL(fs.getUri().toString() + invalid.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + 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 { + // Create a new context definition file in HDFS, but with invalid content + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path initial = new Path("/contextDefs/InitialContextDefinitionFile.json"); + try (FSDataOutputStream out = fs.create(initial)) { + ContextDefinition def = createContextDef("initial", jarAOrigLocation); + out.writeBytes(def.toJson()); + } + assertTrue(fs.exists(initial)); + final URL initialDefUrl = new URL(fs.getUri().toString() + initial.toUri().toString()); + + LocalCachingContextClassLoaderFactory factory = new LocalCachingContextClassLoaderFactory(); + ClassLoader cl = factory.getClassLoader(initialDefUrl.toString()); + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazzA = + (Class<? extends test.Test>) cl.loadClass("test.TestObjectA"); + test.Test a1 = clazzA.getDeclaredConstructor().newInstance(); + assertEquals("Hello from A", a1.hello()); + } + + @Test + public void testUpdate() throws Exception { + // Create a new context definition file in HDFS + assertTrue(fs.mkdirs(new Path("/contextDefs"))); + final Path defFilePath = new Path("/contextDefs/UpdateContextDefinitionFile.json"); + final ContextDefinition def = createContextDef("update", jarAOrigLocation); + try (FSDataOutputStream out = fs.create(defFilePath)) { + out.writeBytes(def.toJson()); + } + assertTrue(fs.exists(defFilePath)); + final URL updateDefUrl = new URL(fs.getUri().toString() + defFilePath.toUri().toString()); + + final LocalCachingContextClassLoaderFactory factory = + new LocalCachingContextClassLoaderFactory(); + final ClassLoader cl = factory.getClassLoader(updateDefUrl.toString()); + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazzA = + (Class<? extends test.Test>) cl.loadClass("test.TestObjectA"); + test.Test a1 = clazzA.getDeclaredConstructor().newInstance(); + assertEquals("Hello from A", a1.hello()); + + // Update the contents of the context definition json file + fs.delete(defFilePath, false); + assertFalse(fs.exists(defFilePath)); + + ContextDefinition updateDef = createContextDef("update", jarDOrigLocation); + try (FSDataOutputStream out = fs.create(defFilePath)) { + out.writeBytes(updateDef.toJson()); + } + assertTrue(fs.exists(defFilePath)); + + // wait 2x the monitor interval + Thread.sleep(MONITOR_INTERVAL_SECS * 2 * 1000); + + final ClassLoader cl2 = factory.getClassLoader(updateDefUrl.toString()); + assertThrows(ClassNotFoundException.class, () -> cl2.loadClass("test.TestObjectA")); + + @SuppressWarnings("unchecked") + Class<? extends test.Test> clazzD = + (Class<? extends test.Test>) cl2.loadClass("test.TestObjectD"); + test.Test d1 = clazzD.getDeclaredConstructor().newInstance(); + assertEquals("Hello from D", d1.hello()); + + } + Review Comment: Would be good to test an update the replaces the same class name w/ a differ version of the class. ########## modules/local-caching-classloader/src/main/java/org/apache/accumulo/classloader/lcc/definition/ContextDefinition.java: ########## @@ -0,0 +1,102 @@ +/* + * 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.definition; + +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.Objects; + +import org.apache.accumulo.classloader.lcc.Constants; + +import com.google.common.base.Preconditions; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; + +@SuppressFBWarnings(value = {"EI_EXPOSE_REP", "EI_EXPOSE_REP2"}) +public class ContextDefinition { + private String contextName; + private int monitorIntervalSeconds; + private List<Resource> resources; + private volatile transient byte[] checksum = null; + + public ContextDefinition() {} + + public ContextDefinition(String contextName, int monitorIntervalSeconds, + List<Resource> resources) { + this.contextName = Objects.requireNonNull(contextName, "context name must be supplied"); + Preconditions.checkArgument(monitorIntervalSeconds > 0, + "monitor interval must be greater than zero"); + this.monitorIntervalSeconds = monitorIntervalSeconds; + this.resources = Objects.requireNonNull(resources, "resources must be supplied"); + } + + public String getContextName() { + return contextName; + } + + public int getMonitorIntervalSeconds() { + return monitorIntervalSeconds; + } + + public List<Resource> getResources() { + return resources; + } + + public void setContextName(String contextName) { + this.contextName = contextName; + } + + public void setMonitorIntervalSeconds(int monitorIntervalSeconds) { + this.monitorIntervalSeconds = monitorIntervalSeconds; + } + + public void setResources(List<Resource> resources) { + this.resources = resources; + } + + @Override + public int hashCode() { + return Objects.hash(contextName, monitorIntervalSeconds, resources); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ContextDefinition other = (ContextDefinition) obj; + return Objects.equals(contextName, other.contextName) + && monitorIntervalSeconds == other.monitorIntervalSeconds + && Objects.equals(resources, other.resources); + } + + public synchronized byte[] getChecksum() throws NoSuchAlgorithmException { + if (checksum == null) { + checksum = Constants.getChecksummer().digest(toJson()); Review Comment: Not sure if this json generation is deterministic and will always produce the same json for the same data. It could reorder things and still be correct json. Could hash the individual elements instead of the json like `hash(ctxName+interval+res0+res1+...)` w/ the resources sorted in some way. Sorting the resources would also help the `equals()` and `hashCode()` methods out as those currently compare list which could have the same contents in diff order Maybe making the `resources` instance var a treeset would benefit all of these methods. -- 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]
