You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@accumulo.apache.org by "dlmarion (via GitHub)" <gi...@apache.org> on 2025/08/20 21:24:58 UTC

[PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

dlmarion opened a new pull request, #5811:
URL: https://github.com/apache/accumulo/pull/5811

   (no comment)


-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "keith-turner (via GitHub)" <gi...@apache.org>.
keith-turner commented on PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#issuecomment-3211754638

   > In any other thread, the VM would be halted without closing. I'm thinking that the finally block from AbstractServer.startServer should be removed. Thoughts?
   
   Are you thinking of something like the following?  This would only call close when there is no exception in runServer. 
   
   ```java
     public static void startServer(AbstractServer server, Logger LOG) throws Exception {
       try {
         server.runServer();
         server.close();
       } catch (Exception e) {
         System.err
             .println(server.getClass().getSimpleName() + " died, exception thrown from runServer.");
         e.printStackTrace();
         LOG.error("{} died, exception thrown from runServer.", server.getClass().getSimpleName(), e);
         throw e;
       }
     }
   ```
   
   Or is the call to close() not needed at all in this code because of the comment about `AbstractServer.close()`?
   


-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion merged PR #5811:
URL: https://github.com/apache/accumulo/pull/5811


-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2290885339


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT_SimpleSuite.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT_SimpleSuite extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), compactorArgs.toArray(new String[] {})};
+          break;
+        case GARBAGE_COLLECTOR:
+          serverClass = SimpleGarbageCollector.class;
+          methodName = "logStats";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new String[] {}};
+          break;
+        case MANAGER:
+          serverClass = Manager.class;
+          methodName = "mainWait";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(), new String[] {}};
+          break;
+        case SCAN_SERVER:
+          List<String> scanServerArgs = new ArrayList<>();
+          scanServerArgs.add("-o");
+          scanServerArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = ScanServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), scanServerArgs.toArray(new String[] {})};
+          break;
+        case TABLET_SERVER:
+          List<String> tabletServerArgs = new ArrayList<>();
+          tabletServerArgs.add("-o");
+          tabletServerArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = TabletServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(),
+              tabletServerArgs.toArray(new String[] {})};
+          break;
+        case MONITOR:
+        case ZOOKEEPER:
+        default:
+          throw new UnsupportedOperationException(st + " is not currently supported");
+      }
+
+      final Implementation implementation;
+      switch (behavior) {
+        case ERROR:
+          implementation =
+              ExceptionMethod.throwing(StackOverflowError.class, "throwing unknown error");
+          break;
+        case EXCEPTION:
+          implementation =
+              ExceptionMethod.throwing(RuntimeException.class, "throwing runtime exception");
+          break;
+        case SHUTDOWN:
+          implementation =
+              MethodCall.invoke(AbstractServer.class.getMethod("requestShutdownForTests"));
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+
+      // Dynamically create the subclass with the specified behavior, load it
+      // into the JVM, and return it's Class.
+      // creates a subclass of server class defining a public constructor that
+      // takes an Integer, but calls the server class constructor with the
+      // appropriate args. Calls to the intercepted method name are intercepted
+      // by the supplied implementation
+      final Class<? extends AbstractServer> dynamicServerType =
+          new ByteBuddy().subclass(serverClass, ConstructorStrategy.Default.NO_CONSTRUCTORS)
+              .name("org.apache.accumulo.test.functional.exit_codes." + serverClass.getSimpleName()
+                  + "_" + behavior.name())
+              .defineConstructor(Visibility.PUBLIC).withParameters(Integer.class)
+              .intercept(MethodCall.invoke(serverClass.getDeclaredConstructor(ctorParams)).onSuper()
+                  .with(ctorArgs))
+              .method(ElementMatchers.named(methodName)).intercept(implementation).make()
+              .load(serverClass.getClassLoader()).getLoaded();
+
+      // Find and invoke the constructor of the dynamically created class
+      final Constructor<? extends AbstractServer> ctor =
+          dynamicServerType.getDeclaredConstructor(Integer.class);
+      final AbstractServer dynamicServerInstance = ctor.newInstance(1);
+
+      // Start the server process
+      AbstractServer.startServer(dynamicServerInstance, LoggerFactory.getLogger(serverClass));
+    }
+
+  }
+
+  @BeforeAll
+  public static void beforeTests() throws Exception {
+    // Start MiniCluster so that getCluster() does not
+    // return null,
+    SharedMiniClusterBase.startMiniCluster();
+    getCluster().getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);
+  }
+
+  @AfterAll
+  public static void afterTests() {
+    SharedMiniClusterBase.stopMiniCluster();
+  }
+
+  // Junit doesn't support more than one parameterized
+  // argument to a test method. We need to generate
+  // the arguments here.
+  static Stream<Arguments> generateWorkerProcessArguments() {
+    List<Arguments> args = new ArrayList<>();
+    for (ServerType st : ServerType.values()) {
+      if (st == ServerType.COMPACTOR || st == ServerType.SCAN_SERVER
+          || st == ServerType.TABLET_SERVER) {
+        for (TerminalBehavior tb : TerminalBehavior.values()) {
+          args.add(Arguments.of(st, tb));
+        }
+      }
+    }
+    return args.stream();
+  }
+
+  @ParameterizedTest
+  @MethodSource("generateWorkerProcessArguments")
+  public void testWorkerProcesses(ServerType server, TerminalBehavior behavior) throws Exception {
+    Map<String,String> properties = new HashMap<>();
+    properties.put(ProcessProxy.PROXY_CLASS, server.name());
+    properties.put(ProcessProxy.PROXY_METHOD_BEHAVIOR, behavior.name());
+    getCluster().getConfig().setSystemProperties(properties);
+    ProcessInfo pi = getCluster()._exec(ProcessProxy.class, server, Map.of(), new String[] {});
+    Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000);
+    int exitValue = pi.getProcess().exitValue();
+    if (server != ServerType.SCAN_SERVER) {
+      if (behavior == TerminalBehavior.SHUTDOWN) {
+        assertEquals(0, exitValue);
+      } else {
+        assertEquals(1, exitValue);
+      }

Review Comment:
   Added in d41dbcc



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "keith-turner (via GitHub)" <gi...@apache.org>.
keith-turner commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2299034598


##########
server/base/src/main/java/org/apache/accumulo/server/AbstractServer.java:
##########
@@ -84,15 +84,6 @@ public static void startServer(AbstractServer server, Logger LOG) throws Excepti
       e.printStackTrace();
       LOG.error("{} died, exception thrown from runServer.", server.getClass().getSimpleName(), e);
       throw e;
-    } finally {

Review Comment:
   A bit futher up could change the catch to `catch(Exception e)` instead of `catch(Throwable e)`.  The only reason it was catching Throwable was in case the finally block threw an exception.



##########
server/base/src/main/java/org/apache/accumulo/server/AbstractServer.java:
##########
@@ -476,8 +470,22 @@ public void startServiceLockVerificationThread() {
 
   @Override
   public void close() {
-    if (context != null) {
-      context.close();
+
+    context.getLowMemoryDetector().logGCInfo(getConfiguration());
+
+    // Must set shutdown as completed before calling super.close().

Review Comment:
   This comment mentions calling `super.close()`, but do not see that.



##########
server/compactor/src/main/java/org/apache/accumulo/compactor/Compactor.java:
##########
@@ -829,237 +829,241 @@ public void run() {
         getConfiguration().getTimeInMillis(Property.COMPACTOR_CANCEL_CHECK_INTERVAL));
 
     LOG.info("Compactor started, waiting for work");
-    try {
-
-      final AtomicReference<Throwable> err = new AtomicReference<>();
-      final LogSorter logSorter = new LogSorter(this);
-      long nextSortLogsCheckTime = System.currentTimeMillis();
 
-      while (!isShutdownRequested()) {
-        if (Thread.currentThread().isInterrupted()) {
-          LOG.info("Server process thread has been interrupted, shutting down");
-          break;
-        }
-        try {
-          // mark compactor as idle while not in the compaction loop
-          updateIdleStatus(true);
+    final AtomicReference<Throwable> err = new AtomicReference<>();
+    final LogSorter logSorter = new LogSorter(this);
+    long nextSortLogsCheckTime = System.currentTimeMillis();
 
-          currentCompactionId.set(null);
-          err.set(null);
-          JOB_HOLDER.reset();
-
-          if (System.currentTimeMillis() > nextSortLogsCheckTime) {
-            // Attempt to process all existing log sorting work serially in this thread.
-            // When no work remains, this call will return so that we can look for compaction
-            // work.
-            LOG.debug("Checking to see if any recovery logs need sorting");
+    while (!isShutdownRequested()) {
+      if (Thread.currentThread().isInterrupted()) {
+        LOG.info("Server process thread has been interrupted, shutting down");
+        break;
+      }
+      try {
+        // mark compactor as idle while not in the compaction loop
+        updateIdleStatus(true);
+
+        currentCompactionId.set(null);
+        err.set(null);
+        JOB_HOLDER.reset();
+
+        if (System.currentTimeMillis() > nextSortLogsCheckTime) {
+          // Attempt to process all existing log sorting work serially in this thread.
+          // When no work remains, this call will return so that we can look for compaction
+          // work.
+          LOG.debug("Checking to see if any recovery logs need sorting");
+          try {
             nextSortLogsCheckTime = logSorter.sortLogsIfNeeded();
+          } catch (KeeperException e) {
+            LOG.error("Error sorting logs", e);
           }
+        }
 
-          performFailureProcessing(errorHistory);
+        performFailureProcessing(errorHistory);
 
-          TExternalCompactionJob job;
-          try {
-            TNextCompactionJob next = getNextJob(getNextId());
-            job = next.getJob();
-            if (!job.isSetExternalCompactionId()) {
-              LOG.trace("No external compactions in queue {}", this.getResourceGroup());
-              UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
-              continue;
-            }
-            if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
-              throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
-                  + " does not match supplied eci " + currentCompactionId.get());
-            }
-          } catch (RetriesExceededException e2) {
-            LOG.warn("Retries exceeded getting next job. Retrying...");
+        TExternalCompactionJob job;
+        try {
+          TNextCompactionJob next = getNextJob(getNextId());
+          job = next.getJob();
+          if (!job.isSetExternalCompactionId()) {
+            LOG.trace("No external compactions in queue {}", this.getResourceGroup());
+            UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
             continue;
           }
-          LOG.debug("Received next compaction job: {}", job);
+          if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
+            throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
+                + " does not match supplied eci " + currentCompactionId.get());
+          }
+        } catch (RetriesExceededException e2) {
+          LOG.warn("Retries exceeded getting next job. Retrying...");
+          continue;
+        }
+        LOG.debug("Received next compaction job: {}", job);
 
-          final LongAdder totalInputEntries = new LongAdder();
-          final LongAdder totalInputBytes = new LongAdder();
-          final CountDownLatch started = new CountDownLatch(1);
-          final CountDownLatch stopped = new CountDownLatch(1);
+        final LongAdder totalInputEntries = new LongAdder();
+        final LongAdder totalInputBytes = new LongAdder();
+        final CountDownLatch started = new CountDownLatch(1);
+        final CountDownLatch stopped = new CountDownLatch(1);
 
-          final FileCompactorRunnable fcr =
-              createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
+        final FileCompactorRunnable fcr =
+            createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
 
-          final Thread compactionThread = Threads.createNonCriticalThread(
-              "Compaction job for tablet " + job.getExtent().toString(), fcr);
+        final Thread compactionThread = Threads.createNonCriticalThread(
+            "Compaction job for tablet " + job.getExtent().toString(), fcr);
 
-          JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
+        JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
 
-          try {
-            // mark compactor as busy while compacting
-            updateIdleStatus(false);
+        try {
+          // mark compactor as busy while compacting
+          updateIdleStatus(false);
 
+          try {
             // Need to call FileCompactorRunnable.initialize after calling JOB_HOLDER.set
             fcr.initialize();
-
-            compactionThread.start(); // start the compactionThread
-            started.await(); // wait until the compactor is started
-            final long inputEntries = totalInputEntries.sum();
-            final long waitTime = calculateProgressCheckTime(totalInputBytes.sum());
-            LOG.debug("Progress checks will occur every {} seconds", waitTime);
-            String percentComplete = "unknown";
-
-            while (!stopped.await(waitTime, TimeUnit.SECONDS)) {
-              List<CompactionInfo> running =
-                  org.apache.accumulo.server.compaction.FileCompactor.getRunningCompactions();
-              if (!running.isEmpty()) {
-                // Compaction has started. There should only be one in the list
-                CompactionInfo info = running.get(0);
-                if (info != null) {
-                  final long entriesRead = info.getEntriesRead();
-                  final long entriesWritten = info.getEntriesWritten();
-                  if (inputEntries > 0) {
-                    percentComplete = Float.toString((entriesRead / (float) inputEntries) * 100);
-                  }
-                  String message = String.format(
-                      "Compaction in progress, read %d of %d input entries ( %s %s ), written %d entries",
-                      entriesRead, inputEntries, percentComplete, "%", entriesWritten);
-                  watcher.run();
-                  try {
-                    LOG.debug("Updating coordinator with compaction progress: {}.", message);
-                    TCompactionStatusUpdate update = new TCompactionStatusUpdate(
-                        TCompactionState.IN_PROGRESS, message, inputEntries, entriesRead,
-                        entriesWritten, fcr.getCompactionAge().toNanos());
-                    updateCompactionState(job, update);
-                  } catch (RetriesExceededException e) {
-                    LOG.warn("Error updating coordinator with compaction progress, error: {}",
-                        e.getMessage());
-                  }
-                }
-              } else {
-                LOG.debug("Waiting on compaction thread to finish, but no RUNNING compaction");
-              }
-            }
-            compactionThread.join();
-            LOG.trace("Compaction thread finished.");
-            // Run the watcher again to clear out the finished compaction and set the
-            // stuck count to zero.
-            watcher.run();
-
-            if (err.get() != null) {
-              // maybe the error occured because the table was deleted or something like that, so
-              // force a cancel check to possibly reduce noise in the logs
-              checkIfCanceled();
+          } catch (RetriesExceededException e) {
+            LOG.error(
+                "Error starting FileCompactableRunnable, cancelling compaction and moving to next job.",
+                e);
+            try {
+              cancel(job.getExternalCompactionId());
+            } catch (TException e1) {
+              LOG.error("Error cancelling compaction.", e1);
             }
+            continue;
+          } finally {
+            currentCompactionId.set(null);

Review Comment:
   Does not seem like this should be cleared here because its used for dead compaction detection and it should be set for the entire time that a compactor is running a compaction.



##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";

Review Comment:
   What happens w/ the test if this method does not exists?  Does the test fail?  
   Seems like maybe it would fail because the SHUTDOWN case would expect an exit code of zero but would see some other exit code.  But not sure.  
   
   Wondering if instead of this run time overriding if it would be possible to do it at compile time instead w/ something like the following.  Then if someone changes a method name they will get a compile time error.
   
   ```java
   class ExitCompactor extends  Compactor {
   
     private final TerminalBehavior terminalBehavior;
   
     protected ExitCompactor(ConfigOpts opts, String[] args, TerminalBehavior terminalBehavior) {
       super(opts, args);
       this.terminalBehavior = terminalBehavior;
     }
   
     @Override
     public void updateIdleStatus(boolean idle){
       switch (terminalBehavior){
         case SHUTDOWN:
           super.requestShutdownForTests();
           break;
         case ERROR:
           throw new StackOverflowError();
         case EXCEPTION:
           throw new RuntimeException();
       }
     }
   }
   ```
   
   



##########
server/compactor/src/main/java/org/apache/accumulo/compactor/Compactor.java:
##########
@@ -829,237 +829,241 @@ public void run() {
         getConfiguration().getTimeInMillis(Property.COMPACTOR_CANCEL_CHECK_INTERVAL));
 
     LOG.info("Compactor started, waiting for work");
-    try {
-
-      final AtomicReference<Throwable> err = new AtomicReference<>();
-      final LogSorter logSorter = new LogSorter(this);
-      long nextSortLogsCheckTime = System.currentTimeMillis();
 
-      while (!isShutdownRequested()) {
-        if (Thread.currentThread().isInterrupted()) {
-          LOG.info("Server process thread has been interrupted, shutting down");
-          break;
-        }
-        try {
-          // mark compactor as idle while not in the compaction loop
-          updateIdleStatus(true);
+    final AtomicReference<Throwable> err = new AtomicReference<>();
+    final LogSorter logSorter = new LogSorter(this);
+    long nextSortLogsCheckTime = System.currentTimeMillis();
 
-          currentCompactionId.set(null);
-          err.set(null);
-          JOB_HOLDER.reset();
-
-          if (System.currentTimeMillis() > nextSortLogsCheckTime) {
-            // Attempt to process all existing log sorting work serially in this thread.
-            // When no work remains, this call will return so that we can look for compaction
-            // work.
-            LOG.debug("Checking to see if any recovery logs need sorting");
+    while (!isShutdownRequested()) {
+      if (Thread.currentThread().isInterrupted()) {
+        LOG.info("Server process thread has been interrupted, shutting down");
+        break;
+      }
+      try {
+        // mark compactor as idle while not in the compaction loop
+        updateIdleStatus(true);
+
+        currentCompactionId.set(null);
+        err.set(null);
+        JOB_HOLDER.reset();
+
+        if (System.currentTimeMillis() > nextSortLogsCheckTime) {
+          // Attempt to process all existing log sorting work serially in this thread.
+          // When no work remains, this call will return so that we can look for compaction
+          // work.
+          LOG.debug("Checking to see if any recovery logs need sorting");
+          try {
             nextSortLogsCheckTime = logSorter.sortLogsIfNeeded();
+          } catch (KeeperException e) {
+            LOG.error("Error sorting logs", e);
           }
+        }
 
-          performFailureProcessing(errorHistory);
+        performFailureProcessing(errorHistory);
 
-          TExternalCompactionJob job;
-          try {
-            TNextCompactionJob next = getNextJob(getNextId());
-            job = next.getJob();
-            if (!job.isSetExternalCompactionId()) {
-              LOG.trace("No external compactions in queue {}", this.getResourceGroup());
-              UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
-              continue;
-            }
-            if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
-              throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
-                  + " does not match supplied eci " + currentCompactionId.get());
-            }
-          } catch (RetriesExceededException e2) {
-            LOG.warn("Retries exceeded getting next job. Retrying...");
+        TExternalCompactionJob job;
+        try {
+          TNextCompactionJob next = getNextJob(getNextId());
+          job = next.getJob();
+          if (!job.isSetExternalCompactionId()) {
+            LOG.trace("No external compactions in queue {}", this.getResourceGroup());
+            UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
             continue;
           }
-          LOG.debug("Received next compaction job: {}", job);
+          if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
+            throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
+                + " does not match supplied eci " + currentCompactionId.get());
+          }
+        } catch (RetriesExceededException e2) {
+          LOG.warn("Retries exceeded getting next job. Retrying...");
+          continue;
+        }
+        LOG.debug("Received next compaction job: {}", job);
 
-          final LongAdder totalInputEntries = new LongAdder();
-          final LongAdder totalInputBytes = new LongAdder();
-          final CountDownLatch started = new CountDownLatch(1);
-          final CountDownLatch stopped = new CountDownLatch(1);
+        final LongAdder totalInputEntries = new LongAdder();
+        final LongAdder totalInputBytes = new LongAdder();
+        final CountDownLatch started = new CountDownLatch(1);
+        final CountDownLatch stopped = new CountDownLatch(1);
 
-          final FileCompactorRunnable fcr =
-              createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
+        final FileCompactorRunnable fcr =
+            createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
 
-          final Thread compactionThread = Threads.createNonCriticalThread(
-              "Compaction job for tablet " + job.getExtent().toString(), fcr);
+        final Thread compactionThread = Threads.createNonCriticalThread(
+            "Compaction job for tablet " + job.getExtent().toString(), fcr);
 
-          JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
+        JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
 
-          try {
-            // mark compactor as busy while compacting
-            updateIdleStatus(false);
+        try {
+          // mark compactor as busy while compacting
+          updateIdleStatus(false);
 
+          try {
             // Need to call FileCompactorRunnable.initialize after calling JOB_HOLDER.set
             fcr.initialize();
-
-            compactionThread.start(); // start the compactionThread
-            started.await(); // wait until the compactor is started
-            final long inputEntries = totalInputEntries.sum();
-            final long waitTime = calculateProgressCheckTime(totalInputBytes.sum());
-            LOG.debug("Progress checks will occur every {} seconds", waitTime);
-            String percentComplete = "unknown";
-
-            while (!stopped.await(waitTime, TimeUnit.SECONDS)) {
-              List<CompactionInfo> running =
-                  org.apache.accumulo.server.compaction.FileCompactor.getRunningCompactions();
-              if (!running.isEmpty()) {
-                // Compaction has started. There should only be one in the list
-                CompactionInfo info = running.get(0);
-                if (info != null) {
-                  final long entriesRead = info.getEntriesRead();
-                  final long entriesWritten = info.getEntriesWritten();
-                  if (inputEntries > 0) {
-                    percentComplete = Float.toString((entriesRead / (float) inputEntries) * 100);
-                  }
-                  String message = String.format(
-                      "Compaction in progress, read %d of %d input entries ( %s %s ), written %d entries",
-                      entriesRead, inputEntries, percentComplete, "%", entriesWritten);
-                  watcher.run();
-                  try {
-                    LOG.debug("Updating coordinator with compaction progress: {}.", message);
-                    TCompactionStatusUpdate update = new TCompactionStatusUpdate(
-                        TCompactionState.IN_PROGRESS, message, inputEntries, entriesRead,
-                        entriesWritten, fcr.getCompactionAge().toNanos());
-                    updateCompactionState(job, update);
-                  } catch (RetriesExceededException e) {
-                    LOG.warn("Error updating coordinator with compaction progress, error: {}",
-                        e.getMessage());
-                  }
-                }
-              } else {
-                LOG.debug("Waiting on compaction thread to finish, but no RUNNING compaction");
-              }
-            }
-            compactionThread.join();
-            LOG.trace("Compaction thread finished.");
-            // Run the watcher again to clear out the finished compaction and set the
-            // stuck count to zero.
-            watcher.run();
-
-            if (err.get() != null) {
-              // maybe the error occured because the table was deleted or something like that, so
-              // force a cancel check to possibly reduce noise in the logs
-              checkIfCanceled();
+          } catch (RetriesExceededException e) {
+            LOG.error(
+                "Error starting FileCompactableRunnable, cancelling compaction and moving to next job.",
+                e);
+            try {
+              cancel(job.getExternalCompactionId());
+            } catch (TException e1) {
+              LOG.error("Error cancelling compaction.", e1);
             }
+            continue;
+          } finally {
+            currentCompactionId.set(null);
+          }
 
-            if (compactionThread.isInterrupted() || JOB_HOLDER.isCancelled()
-                || (err.get() != null && err.get().getClass().equals(InterruptedException.class))) {
-              LOG.warn("Compaction thread was interrupted, sending CANCELLED state");
-              try {
-                TCompactionStatusUpdate update =
-                    new TCompactionStatusUpdate(TCompactionState.CANCELLED, "Compaction cancelled",
-                        -1, -1, -1, fcr.getCompactionAge().toNanos());
-                updateCompactionState(job, update);
-                updateCompactionFailed(job, InterruptedException.class.getName());
-                cancelled.incrementAndGet();
-              } catch (RetriesExceededException e) {
-                LOG.error("Error updating coordinator with compaction cancellation.", e);
-              } finally {
-                currentCompactionId.set(null);
-              }
-            } else if (err.get() != null) {
-              final KeyExtent fromThriftExtent = KeyExtent.fromThrift(job.getExtent());
-              try {
-                LOG.info("Updating coordinator with compaction failure: id: {}, extent: {}",
-                    job.getExternalCompactionId(), fromThriftExtent);
-                TCompactionStatusUpdate update = new TCompactionStatusUpdate(
-                    TCompactionState.FAILED, "Compaction failed due to: " + err.get().getMessage(),
-                    -1, -1, -1, fcr.getCompactionAge().toNanos());
-                updateCompactionState(job, update);
-                updateCompactionFailed(job, err.get().getClass().getName());
-                failed.incrementAndGet();
-                errorHistory.addError(fromThriftExtent.tableId(), err.get());
-              } catch (RetriesExceededException e) {
-                LOG.error("Error updating coordinator with compaction failure: id: {}, extent: {}",
-                    job.getExternalCompactionId(), fromThriftExtent, e);
-              } finally {
-                currentCompactionId.set(null);
-              }
-            } else {
-              try {
-                LOG.trace("Updating coordinator with compaction completion.");
-                updateCompactionCompleted(job, JOB_HOLDER.getStats());
-                completed.incrementAndGet();
-                // job completed successfully, clear the error history
-                errorHistory.clear();
-              } catch (RetriesExceededException e) {
-                LOG.error(
-                    "Error updating coordinator with compaction completion, cancelling compaction.",
-                    e);
+          compactionThread.start(); // start the compactionThread
+          started.await(); // wait until the compactor is started
+          final long inputEntries = totalInputEntries.sum();
+          final long waitTime = calculateProgressCheckTime(totalInputBytes.sum());
+          LOG.debug("Progress checks will occur every {} seconds", waitTime);
+          String percentComplete = "unknown";
+
+          while (!stopped.await(waitTime, TimeUnit.SECONDS)) {
+            List<CompactionInfo> running =
+                org.apache.accumulo.server.compaction.FileCompactor.getRunningCompactions();
+            if (!running.isEmpty()) {
+              // Compaction has started. There should only be one in the list
+              CompactionInfo info = running.get(0);
+              if (info != null) {
+                final long entriesRead = info.getEntriesRead();
+                final long entriesWritten = info.getEntriesWritten();
+                if (inputEntries > 0) {
+                  percentComplete = Float.toString((entriesRead / (float) inputEntries) * 100);
+                }
+                String message = String.format(
+                    "Compaction in progress, read %d of %d input entries ( %s %s ), written %d entries",
+                    entriesRead, inputEntries, percentComplete, "%", entriesWritten);
+                watcher.run();
                 try {
-                  cancel(job.getExternalCompactionId());
-                } catch (TException e1) {
-                  LOG.error("Error cancelling compaction.", e1);
+                  LOG.debug("Updating coordinator with compaction progress: {}.", message);
+                  TCompactionStatusUpdate update = new TCompactionStatusUpdate(
+                      TCompactionState.IN_PROGRESS, message, inputEntries, entriesRead,
+                      entriesWritten, fcr.getCompactionAge().toNanos());
+                  updateCompactionState(job, update);
+                } catch (RetriesExceededException e) {
+                  LOG.warn("Error updating coordinator with compaction progress, error: {}",
+                      e.getMessage());
                 }
-              } finally {
-                currentCompactionId.set(null);
               }
+            } else {
+              LOG.debug("Waiting on compaction thread to finish, but no RUNNING compaction");
             }
-          } catch (RuntimeException e1) {
-            LOG.error(
-                "Compactor thread was interrupted waiting for compaction to start, cancelling job",
-                e1);
+          }
+          compactionThread.join();
+          LOG.trace("Compaction thread finished.");
+          // Run the watcher again to clear out the finished compaction and set the
+          // stuck count to zero.
+          watcher.run();
+
+          if (err.get() != null) {
+            // maybe the error occured because the table was deleted or something like that, so
+            // force a cancel check to possibly reduce noise in the logs
+            checkIfCanceled();
+          }
+
+          if (compactionThread.isInterrupted() || JOB_HOLDER.isCancelled()
+              || (err.get() != null && err.get().getClass().equals(InterruptedException.class))) {
+            LOG.warn("Compaction thread was interrupted, sending CANCELLED state");
             try {
-              cancel(job.getExternalCompactionId());
-            } catch (TException e2) {
-              LOG.error("Error cancelling compaction.", e2);
+              TCompactionStatusUpdate update =
+                  new TCompactionStatusUpdate(TCompactionState.CANCELLED, "Compaction cancelled",
+                      -1, -1, -1, fcr.getCompactionAge().toNanos());
+              updateCompactionState(job, update);
+              updateCompactionFailed(job, InterruptedException.class.getName());
+              cancelled.incrementAndGet();
+            } catch (RetriesExceededException e) {
+              LOG.error("Error updating coordinator with compaction cancellation.", e);
+            } finally {
+              currentCompactionId.set(null);
             }
-          } finally {
-            currentCompactionId.set(null);
+          } else if (err.get() != null) {
+            final KeyExtent fromThriftExtent = KeyExtent.fromThrift(job.getExtent());
+            try {
+              LOG.info("Updating coordinator with compaction failure: id: {}, extent: {}",
+                  job.getExternalCompactionId(), fromThriftExtent);
+              TCompactionStatusUpdate update = new TCompactionStatusUpdate(TCompactionState.FAILED,
+                  "Compaction failed due to: " + err.get().getMessage(), -1, -1, -1,
+                  fcr.getCompactionAge().toNanos());
+              updateCompactionState(job, update);
+              updateCompactionFailed(job, err.get().getClass().getName());
+              failed.incrementAndGet();
+              errorHistory.addError(fromThriftExtent.tableId(), err.get());
+            } catch (RetriesExceededException e) {
+              LOG.error("Error updating coordinator with compaction failure: id: {}, extent: {}",
+                  job.getExternalCompactionId(), fromThriftExtent, e);
+            } finally {
+              currentCompactionId.set(null);
+            }
+          } else {
+            try {
+              LOG.trace("Updating coordinator with compaction completion.");
+              updateCompactionCompleted(job, JOB_HOLDER.getStats());
+              completed.incrementAndGet();
+              // job completed successfully, clear the error history
+              errorHistory.clear();
+            } catch (RetriesExceededException e) {
+              LOG.error(
+                  "Error updating coordinator with compaction completion, cancelling compaction.",
+                  e);
+              try {
+                cancel(job.getExternalCompactionId());
+              } catch (TException e1) {
+                LOG.error("Error cancelling compaction.", e1);
+              }
+            } finally {
+              currentCompactionId.set(null);
+            }
+          }
+        } catch (RuntimeException e1) {
+          LOG.error(
+              "Compactor thread was interrupted waiting for compaction to start, cancelling job",
+              e1);
+          try {
+            cancel(job.getExternalCompactionId());
+          } catch (TException e2) {
+            LOG.error("Error cancelling compaction.", e2);
+          }
+        } finally {
+          currentCompactionId.set(null);
 
-            // mark compactor as idle after compaction completes
-            updateIdleStatus(true);
+          // mark compactor as idle after compaction completes
+          updateIdleStatus(true);
 
-            // In the case where there is an error in the foreground code the background compaction
-            // may still be running. Must cancel it before starting another iteration of the loop to
-            // avoid multiple threads updating shared state.
-            while (compactionThread.isAlive()) {
-              compactionThread.interrupt();
-              compactionThread.join(1000);
-            }
+          // In the case where there is an error in the foreground code the background compaction
+          // may still be running. Must cancel it before starting another iteration of the loop to
+          // avoid multiple threads updating shared state.
+          while (compactionThread.isAlive()) {
+            compactionThread.interrupt();
+            compactionThread.join(1000);
           }
-        } catch (InterruptedException e) {
-          LOG.info("Interrupt Exception received, shutting down");
-          gracefulShutdown(getContext().rpcCreds());
         }
-      } // end while
-    } catch (Exception e) {
-      LOG.error("Unhandled error occurred in Compactor", e);
-    } finally {
-      // Shutdown local thrift server
-      LOG.debug("Stopping Thrift Servers");
-      if (getThriftServer() != null) {
-        getThriftServer().stop();
+      } catch (InterruptedException e) {
+        LOG.info("Interrupt Exception received, shutting down");
+        gracefulShutdown(getContext().rpcCreds());
       }
+    } // end while, shutdown requested
 
-      try {
-        LOG.debug("Closing filesystems");
-        VolumeManager mgr = getContext().getVolumeManager();
-        if (null != mgr) {
-          mgr.close();
-        }
-      } catch (IOException e) {
-        LOG.warn("Failed to close filesystem : {}", e.getMessage(), e);
-      }
+    // Shutdown local thrift server
+    LOG.debug("Stopping Thrift Servers");
+    if (getThriftServer() != null) {
+      getThriftServer().stop();
+    }
 
-      getContext().getLowMemoryDetector().logGCInfo(getConfiguration());
-      super.close();
-      getShutdownComplete().set(true);
-      LOG.info("stop requested. exiting ... ");
-      try {
-        if (null != compactorLock) {
-          compactorLock.unlock();
-        }
-      } catch (Exception e) {
-        LOG.warn("Failed to release compactor lock", e);
+    try {
+      LOG.debug("Closing filesystems");
+      VolumeManager mgr = getContext().getVolumeManager();
+      if (null != mgr) {
+        mgr.close();
       }
+    } catch (IOException e) {
+      LOG.warn("Failed to close filesystem : {}", e.getMessage(), e);
     }
 
+    super.close();

Review Comment:
   Seems like the the new pattern in this PR is that super.close() is always called at the end of each run() method.  Wondering if would make sense to push this into AbstractServer like the following.  This would centralize the pattern to one place in the code.
   
   ```java
     public void runServer() throws Exception {
       final AtomicReference<Throwable> err = new AtomicReference<>();
       serverThread = new Thread(TraceUtil.wrap(()->{
         this.run();
         close();
       }), applicationName);
   ```



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304216637


##########
server/compactor/src/main/java/org/apache/accumulo/compactor/Compactor.java:
##########
@@ -829,237 +829,241 @@ public void run() {
         getConfiguration().getTimeInMillis(Property.COMPACTOR_CANCEL_CHECK_INTERVAL));
 
     LOG.info("Compactor started, waiting for work");
-    try {
-
-      final AtomicReference<Throwable> err = new AtomicReference<>();
-      final LogSorter logSorter = new LogSorter(this);
-      long nextSortLogsCheckTime = System.currentTimeMillis();
 
-      while (!isShutdownRequested()) {
-        if (Thread.currentThread().isInterrupted()) {
-          LOG.info("Server process thread has been interrupted, shutting down");
-          break;
-        }
-        try {
-          // mark compactor as idle while not in the compaction loop
-          updateIdleStatus(true);
+    final AtomicReference<Throwable> err = new AtomicReference<>();
+    final LogSorter logSorter = new LogSorter(this);
+    long nextSortLogsCheckTime = System.currentTimeMillis();
 
-          currentCompactionId.set(null);
-          err.set(null);
-          JOB_HOLDER.reset();
-
-          if (System.currentTimeMillis() > nextSortLogsCheckTime) {
-            // Attempt to process all existing log sorting work serially in this thread.
-            // When no work remains, this call will return so that we can look for compaction
-            // work.
-            LOG.debug("Checking to see if any recovery logs need sorting");
+    while (!isShutdownRequested()) {
+      if (Thread.currentThread().isInterrupted()) {
+        LOG.info("Server process thread has been interrupted, shutting down");
+        break;
+      }
+      try {
+        // mark compactor as idle while not in the compaction loop
+        updateIdleStatus(true);
+
+        currentCompactionId.set(null);
+        err.set(null);
+        JOB_HOLDER.reset();
+
+        if (System.currentTimeMillis() > nextSortLogsCheckTime) {
+          // Attempt to process all existing log sorting work serially in this thread.
+          // When no work remains, this call will return so that we can look for compaction
+          // work.
+          LOG.debug("Checking to see if any recovery logs need sorting");
+          try {
             nextSortLogsCheckTime = logSorter.sortLogsIfNeeded();
+          } catch (KeeperException e) {
+            LOG.error("Error sorting logs", e);
           }
+        }
 
-          performFailureProcessing(errorHistory);
+        performFailureProcessing(errorHistory);
 
-          TExternalCompactionJob job;
-          try {
-            TNextCompactionJob next = getNextJob(getNextId());
-            job = next.getJob();
-            if (!job.isSetExternalCompactionId()) {
-              LOG.trace("No external compactions in queue {}", this.getResourceGroup());
-              UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
-              continue;
-            }
-            if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
-              throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
-                  + " does not match supplied eci " + currentCompactionId.get());
-            }
-          } catch (RetriesExceededException e2) {
-            LOG.warn("Retries exceeded getting next job. Retrying...");
+        TExternalCompactionJob job;
+        try {
+          TNextCompactionJob next = getNextJob(getNextId());
+          job = next.getJob();
+          if (!job.isSetExternalCompactionId()) {
+            LOG.trace("No external compactions in queue {}", this.getResourceGroup());
+            UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
             continue;
           }
-          LOG.debug("Received next compaction job: {}", job);
+          if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
+            throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
+                + " does not match supplied eci " + currentCompactionId.get());
+          }
+        } catch (RetriesExceededException e2) {
+          LOG.warn("Retries exceeded getting next job. Retrying...");
+          continue;
+        }
+        LOG.debug("Received next compaction job: {}", job);
 
-          final LongAdder totalInputEntries = new LongAdder();
-          final LongAdder totalInputBytes = new LongAdder();
-          final CountDownLatch started = new CountDownLatch(1);
-          final CountDownLatch stopped = new CountDownLatch(1);
+        final LongAdder totalInputEntries = new LongAdder();
+        final LongAdder totalInputBytes = new LongAdder();
+        final CountDownLatch started = new CountDownLatch(1);
+        final CountDownLatch stopped = new CountDownLatch(1);
 
-          final FileCompactorRunnable fcr =
-              createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
+        final FileCompactorRunnable fcr =
+            createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
 
-          final Thread compactionThread = Threads.createNonCriticalThread(
-              "Compaction job for tablet " + job.getExtent().toString(), fcr);
+        final Thread compactionThread = Threads.createNonCriticalThread(
+            "Compaction job for tablet " + job.getExtent().toString(), fcr);
 
-          JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
+        JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
 
-          try {
-            // mark compactor as busy while compacting
-            updateIdleStatus(false);
+        try {
+          // mark compactor as busy while compacting
+          updateIdleStatus(false);
 
+          try {
             // Need to call FileCompactorRunnable.initialize after calling JOB_HOLDER.set
             fcr.initialize();
-
-            compactionThread.start(); // start the compactionThread
-            started.await(); // wait until the compactor is started
-            final long inputEntries = totalInputEntries.sum();
-            final long waitTime = calculateProgressCheckTime(totalInputBytes.sum());
-            LOG.debug("Progress checks will occur every {} seconds", waitTime);
-            String percentComplete = "unknown";
-
-            while (!stopped.await(waitTime, TimeUnit.SECONDS)) {
-              List<CompactionInfo> running =
-                  org.apache.accumulo.server.compaction.FileCompactor.getRunningCompactions();
-              if (!running.isEmpty()) {
-                // Compaction has started. There should only be one in the list
-                CompactionInfo info = running.get(0);
-                if (info != null) {
-                  final long entriesRead = info.getEntriesRead();
-                  final long entriesWritten = info.getEntriesWritten();
-                  if (inputEntries > 0) {
-                    percentComplete = Float.toString((entriesRead / (float) inputEntries) * 100);
-                  }
-                  String message = String.format(
-                      "Compaction in progress, read %d of %d input entries ( %s %s ), written %d entries",
-                      entriesRead, inputEntries, percentComplete, "%", entriesWritten);
-                  watcher.run();
-                  try {
-                    LOG.debug("Updating coordinator with compaction progress: {}.", message);
-                    TCompactionStatusUpdate update = new TCompactionStatusUpdate(
-                        TCompactionState.IN_PROGRESS, message, inputEntries, entriesRead,
-                        entriesWritten, fcr.getCompactionAge().toNanos());
-                    updateCompactionState(job, update);
-                  } catch (RetriesExceededException e) {
-                    LOG.warn("Error updating coordinator with compaction progress, error: {}",
-                        e.getMessage());
-                  }
-                }
-              } else {
-                LOG.debug("Waiting on compaction thread to finish, but no RUNNING compaction");
-              }
-            }
-            compactionThread.join();
-            LOG.trace("Compaction thread finished.");
-            // Run the watcher again to clear out the finished compaction and set the
-            // stuck count to zero.
-            watcher.run();
-
-            if (err.get() != null) {
-              // maybe the error occured because the table was deleted or something like that, so
-              // force a cancel check to possibly reduce noise in the logs
-              checkIfCanceled();
+          } catch (RetriesExceededException e) {
+            LOG.error(
+                "Error starting FileCompactableRunnable, cancelling compaction and moving to next job.",
+                e);
+            try {
+              cancel(job.getExternalCompactionId());
+            } catch (TException e1) {
+              LOG.error("Error cancelling compaction.", e1);
             }
+            continue;
+          } finally {
+            currentCompactionId.set(null);

Review Comment:
   Yep, good catch.



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2290886528


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT_SimpleSuite.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT_SimpleSuite extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), compactorArgs.toArray(new String[] {})};
+          break;
+        case GARBAGE_COLLECTOR:
+          serverClass = SimpleGarbageCollector.class;
+          methodName = "logStats";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new String[] {}};
+          break;
+        case MANAGER:
+          serverClass = Manager.class;
+          methodName = "mainWait";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(), new String[] {}};
+          break;
+        case SCAN_SERVER:
+          List<String> scanServerArgs = new ArrayList<>();
+          scanServerArgs.add("-o");
+          scanServerArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = ScanServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), scanServerArgs.toArray(new String[] {})};
+          break;
+        case TABLET_SERVER:
+          List<String> tabletServerArgs = new ArrayList<>();
+          tabletServerArgs.add("-o");
+          tabletServerArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = TabletServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(),
+              tabletServerArgs.toArray(new String[] {})};
+          break;
+        case MONITOR:
+        case ZOOKEEPER:
+        default:
+          throw new UnsupportedOperationException(st + " is not currently supported");
+      }
+
+      final Implementation implementation;
+      switch (behavior) {
+        case ERROR:
+          implementation =
+              ExceptionMethod.throwing(StackOverflowError.class, "throwing unknown error");
+          break;
+        case EXCEPTION:
+          implementation =
+              ExceptionMethod.throwing(RuntimeException.class, "throwing runtime exception");
+          break;
+        case SHUTDOWN:
+          implementation =
+              MethodCall.invoke(AbstractServer.class.getMethod("requestShutdownForTests"));
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+
+      // Dynamically create the subclass with the specified behavior, load it
+      // into the JVM, and return it's Class.
+      // creates a subclass of server class defining a public constructor that
+      // takes an Integer, but calls the server class constructor with the
+      // appropriate args. Calls to the intercepted method name are intercepted
+      // by the supplied implementation
+      final Class<? extends AbstractServer> dynamicServerType =
+          new ByteBuddy().subclass(serverClass, ConstructorStrategy.Default.NO_CONSTRUCTORS)
+              .name("org.apache.accumulo.test.functional.exit_codes." + serverClass.getSimpleName()
+                  + "_" + behavior.name())
+              .defineConstructor(Visibility.PUBLIC).withParameters(Integer.class)
+              .intercept(MethodCall.invoke(serverClass.getDeclaredConstructor(ctorParams)).onSuper()
+                  .with(ctorArgs))
+              .method(ElementMatchers.named(methodName)).intercept(implementation).make()
+              .load(serverClass.getClassLoader()).getLoaded();
+
+      // Find and invoke the constructor of the dynamically created class
+      final Constructor<? extends AbstractServer> ctor =
+          dynamicServerType.getDeclaredConstructor(Integer.class);
+      final AbstractServer dynamicServerInstance = ctor.newInstance(1);
+
+      // Start the server process
+      AbstractServer.startServer(dynamicServerInstance, LoggerFactory.getLogger(serverClass));
+    }
+
+  }
+
+  @BeforeAll
+  public static void beforeTests() throws Exception {
+    // Start MiniCluster so that getCluster() does not
+    // return null,
+    SharedMiniClusterBase.startMiniCluster();
+    getCluster().getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);
+  }
+
+  @AfterAll
+  public static void afterTests() {
+    SharedMiniClusterBase.stopMiniCluster();
+  }
+
+  // Junit doesn't support more than one parameterized
+  // argument to a test method. We need to generate
+  // the arguments here.
+  static Stream<Arguments> generateWorkerProcessArguments() {
+    List<Arguments> args = new ArrayList<>();
+    for (ServerType st : ServerType.values()) {
+      if (st == ServerType.COMPACTOR || st == ServerType.SCAN_SERVER
+          || st == ServerType.TABLET_SERVER) {
+        for (TerminalBehavior tb : TerminalBehavior.values()) {
+          args.add(Arguments.of(st, tb));
+        }
+      }
+    }
+    return args.stream();
+  }
+
+  @ParameterizedTest
+  @MethodSource("generateWorkerProcessArguments")
+  public void testWorkerProcesses(ServerType server, TerminalBehavior behavior) throws Exception {
+    Map<String,String> properties = new HashMap<>();
+    properties.put(ProcessProxy.PROXY_CLASS, server.name());
+    properties.put(ProcessProxy.PROXY_METHOD_BEHAVIOR, behavior.name());
+    getCluster().getConfig().setSystemProperties(properties);
+    ProcessInfo pi = getCluster()._exec(ProcessProxy.class, server, Map.of(), new String[] {});
+    Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000);
+    int exitValue = pi.getProcess().exitValue();
+    if (server != ServerType.SCAN_SERVER) {

Review Comment:
   Fixed in d41dbcc



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2290922436


##########
server/manager/src/main/java/org/apache/accumulo/manager/Manager.java:
##########
@@ -1206,7 +1206,7 @@ boolean canSuspendTablets() {
         break;
       }
       try {
-        Thread.sleep(500);
+        mainWait();
       } catch (InterruptedException e) {
         log.info("Interrupt Exception received, shutting down");
         gracefulShutdown(context.rpcCreds());

Review Comment:
   I checked a few other server types and they have the same pattern.



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304808809


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT.java:
##########
@@ -0,0 +1,334 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT extends SharedMiniClusterBase {
+
+  public static enum TerminalBehavior {
+    SHUTDOWN, EXCEPTION, ERROR
+  };
+
+  public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+  public static TerminalBehavior getTerminalBehavior() {
+    final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+    Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+    return TerminalBehavior.valueOf(methodBehavior);
+  }
+
+  public static class ExitCompactor extends Compactor {
+
+    public static void main(String[] args) throws Exception {
+      List<String> compactorArgs = new ArrayList<>();
+      compactorArgs.add("-o");
+      compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+      AbstractServer.startServer(new ExitCompactor(getTerminalBehavior(), compactorArgs),
+          LoggerFactory.getLogger(ExitCompactor.class));
+    }
+
+    private final TerminalBehavior behavior;
+
+    public ExitCompactor(TerminalBehavior behavior, List<String> compactorArgs) {
+      super(new ConfigOpts(), compactorArgs.toArray(new String[] {}));
+      this.behavior = behavior;
+    }
+
+    @Override
+    public void updateIdleStatus(boolean isIdle) {
+      switch (behavior) {
+        case ERROR:
+          throw new StackOverflowError("throwing stack overflow error");
+        case EXCEPTION:
+          throw new RuntimeException("throwing runtime exception");
+        case SHUTDOWN:
+          requestShutdownForTests();
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+    }
+  }
+
+  public static class ExitScanServer extends ScanServer {
+
+    public static void main(String[] args) throws Exception {
+      List<String> sserverArgs = new ArrayList<>();
+      sserverArgs.add("-o");
+      sserverArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+      AbstractServer.startServer(new ExitScanServer(getTerminalBehavior(), sserverArgs),
+          LoggerFactory.getLogger(ExitScanServer.class));
+    }
+
+    private final TerminalBehavior behavior;
+
+    public ExitScanServer(TerminalBehavior behavior, List<String> sserverArgs) {
+      super(new ConfigOpts(), sserverArgs.toArray(new String[] {}));
+      this.behavior = behavior;
+    }
+
+    @Override
+    public void updateIdleStatus(boolean isIdle) {
+      switch (behavior) {
+        case ERROR:
+          throw new StackOverflowError("throwing stack overflow error");
+        case EXCEPTION:
+          throw new RuntimeException("throwing runtime exception");
+        case SHUTDOWN:
+          requestShutdownForTests();
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+    }
+  }
+
+  public static class ExitTabletServer extends TabletServer {
+
+    public static void main(String[] args) throws Exception {
+      List<String> tserverArgs = new ArrayList<>();
+      tserverArgs.add("-o");
+      tserverArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+      AbstractServer.startServer(new ExitTabletServer(getTerminalBehavior(), tserverArgs),
+          LoggerFactory.getLogger(ExitTabletServer.class));
+    }
+
+    private final TerminalBehavior behavior;
+
+    public ExitTabletServer(TerminalBehavior behavior, List<String> tserverArgs) {
+      super(new ConfigOpts(), ServerContext::new, tserverArgs.toArray(new String[] {}));
+      this.behavior = behavior;
+    }
+
+    @Override
+    public void updateIdleStatus(boolean isIdle) {
+      switch (behavior) {
+        case ERROR:
+          throw new StackOverflowError("throwing stack overflow error");
+        case EXCEPTION:
+          throw new RuntimeException("throwing runtime exception");
+        case SHUTDOWN:
+          requestShutdownForTests();
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+    }
+  }
+
+  public static class ExitGC extends SimpleGarbageCollector {
+
+    public static void main(String[] args) throws Exception {
+      AbstractServer.startServer(new ExitGC(getTerminalBehavior()),
+          LoggerFactory.getLogger(ExitGC.class));
+    }
+
+    private final TerminalBehavior behavior;
+
+    public ExitGC(TerminalBehavior behavior) {
+      super(new ConfigOpts(), new String[] {});
+      this.behavior = behavior;
+    }
+
+    @Override
+    public void logStats() {
+      switch (behavior) {
+        case ERROR:
+          throw new StackOverflowError("throwing stack overflow error");
+        case EXCEPTION:
+          throw new RuntimeException("throwing runtime exception");
+        case SHUTDOWN:
+          requestShutdownForTests();
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+    }
+  }
+
+  public static class ExitManager extends Manager {
+
+    public static void main(String[] args) throws Exception {
+      AbstractServer.startServer(new ExitManager(getTerminalBehavior()),
+          LoggerFactory.getLogger(ExitManager.class));
+    }
+
+    private final TerminalBehavior behavior;
+
+    public ExitManager(TerminalBehavior behavior) throws IOException {
+      super(new ConfigOpts(), ServerContext::new, new String[] {});
+      this.behavior = behavior;
+    }
+
+    @Override
+    public void mainWait() throws InterruptedException {
+      switch (behavior) {
+        case ERROR:
+          throw new StackOverflowError("throwing stack overflow error");
+        case EXCEPTION:
+          throw new RuntimeException("throwing runtime exception");
+        case SHUTDOWN:
+          requestShutdownForTests();
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+    }
+  }
+
+  @BeforeAll
+  public static void beforeTests() throws Exception {
+    // Start MiniCluster so that getCluster() does not
+    // return null,
+    SharedMiniClusterBase.startMiniCluster();
+    getCluster().getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);
+  }
+
+  @AfterAll
+  public static void afterTests() {
+    SharedMiniClusterBase.stopMiniCluster();
+  }
+
+  // Junit doesn't support more than one parameterized
+  // argument to a test method. We need to generate
+  // the arguments here.
+  static Stream<Arguments> generateWorkerProcessArguments() {
+    List<Arguments> args = new ArrayList<>();
+    for (ServerType st : ServerType.values()) {
+      if (st == ServerType.COMPACTOR || st == ServerType.SCAN_SERVER
+          || st == ServerType.TABLET_SERVER) {
+        for (TerminalBehavior tb : TerminalBehavior.values()) {
+          args.add(Arguments.of(st, tb));
+        }
+      }
+    }
+    return args.stream();
+  }
+
+  @ParameterizedTest
+  @MethodSource("generateWorkerProcessArguments")
+  public void testWorkerProcesses(ServerType server, TerminalBehavior behavior) throws Exception {
+    Map<String,String> properties = new HashMap<>();
+    properties.put(PROXY_METHOD_BEHAVIOR, behavior.name());
+    getCluster().getConfig().setSystemProperties(properties);
+    Class<?> serverClass = null;
+    switch (server) {
+      case COMPACTOR:
+        serverClass = ExitCompactor.class;
+        break;
+      case SCAN_SERVER:
+        serverClass = ExitScanServer.class;
+        break;
+      case TABLET_SERVER:
+        serverClass = ExitTabletServer.class;
+        break;
+      case GARBAGE_COLLECTOR:
+      case MANAGER:
+      case MONITOR:
+      case ZOOKEEPER:
+      default:
+        throw new IllegalArgumentException("Unhandled type");
+    }
+    ProcessInfo pi = getCluster()._exec(serverClass, server, Map.of(), new String[] {});
+    Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000);
+    int exitValue = pi.getProcess().exitValue();
+    assertEquals(behavior == TerminalBehavior.SHUTDOWN ? 0 : 1, exitValue);
+  }
+
+  @ParameterizedTest
+  @EnumSource
+  public void testGarbageCollector(TerminalBehavior behavior) throws Exception {
+    Map<String,String> properties = new HashMap<>();
+    properties.put(PROXY_METHOD_BEHAVIOR, behavior.name());
+    getCluster().getConfig().setSystemProperties(properties);
+    ProcessInfo pi =
+        getCluster()._exec(ExitGC.class, ServerType.GARBAGE_COLLECTOR, Map.of(), new String[] {});
+    if (behavior == TerminalBehavior.SHUTDOWN) {
+      Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000);
+      int exitValue = pi.getProcess().exitValue();
+      assertEquals(0, exitValue);
+    } else if (behavior == TerminalBehavior.EXCEPTION) {
+      // GarbageCollector logs exceptions and keeps going.
+      // We need to let this time out and then
+      // terminate the process.
+      IllegalStateException ise = assertThrows(IllegalStateException.class,
+          () -> Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000));

Review Comment:
   I can change to 1m. The other two tests for the GC take 30-35s



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304602754


##########
server/compactor/src/main/java/org/apache/accumulo/compactor/Compactor.java:
##########
@@ -829,237 +829,241 @@ public void run() {
         getConfiguration().getTimeInMillis(Property.COMPACTOR_CANCEL_CHECK_INTERVAL));
 
     LOG.info("Compactor started, waiting for work");
-    try {
-
-      final AtomicReference<Throwable> err = new AtomicReference<>();
-      final LogSorter logSorter = new LogSorter(this);
-      long nextSortLogsCheckTime = System.currentTimeMillis();
 
-      while (!isShutdownRequested()) {
-        if (Thread.currentThread().isInterrupted()) {
-          LOG.info("Server process thread has been interrupted, shutting down");
-          break;
-        }
-        try {
-          // mark compactor as idle while not in the compaction loop
-          updateIdleStatus(true);
+    final AtomicReference<Throwable> err = new AtomicReference<>();
+    final LogSorter logSorter = new LogSorter(this);
+    long nextSortLogsCheckTime = System.currentTimeMillis();
 
-          currentCompactionId.set(null);
-          err.set(null);
-          JOB_HOLDER.reset();
-
-          if (System.currentTimeMillis() > nextSortLogsCheckTime) {
-            // Attempt to process all existing log sorting work serially in this thread.
-            // When no work remains, this call will return so that we can look for compaction
-            // work.
-            LOG.debug("Checking to see if any recovery logs need sorting");
+    while (!isShutdownRequested()) {
+      if (Thread.currentThread().isInterrupted()) {
+        LOG.info("Server process thread has been interrupted, shutting down");
+        break;
+      }
+      try {
+        // mark compactor as idle while not in the compaction loop
+        updateIdleStatus(true);
+
+        currentCompactionId.set(null);
+        err.set(null);
+        JOB_HOLDER.reset();
+
+        if (System.currentTimeMillis() > nextSortLogsCheckTime) {
+          // Attempt to process all existing log sorting work serially in this thread.
+          // When no work remains, this call will return so that we can look for compaction
+          // work.
+          LOG.debug("Checking to see if any recovery logs need sorting");
+          try {
             nextSortLogsCheckTime = logSorter.sortLogsIfNeeded();
+          } catch (KeeperException e) {
+            LOG.error("Error sorting logs", e);
           }
+        }
 
-          performFailureProcessing(errorHistory);
+        performFailureProcessing(errorHistory);
 
-          TExternalCompactionJob job;
-          try {
-            TNextCompactionJob next = getNextJob(getNextId());
-            job = next.getJob();
-            if (!job.isSetExternalCompactionId()) {
-              LOG.trace("No external compactions in queue {}", this.getResourceGroup());
-              UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
-              continue;
-            }
-            if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
-              throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
-                  + " does not match supplied eci " + currentCompactionId.get());
-            }
-          } catch (RetriesExceededException e2) {
-            LOG.warn("Retries exceeded getting next job. Retrying...");
+        TExternalCompactionJob job;
+        try {
+          TNextCompactionJob next = getNextJob(getNextId());
+          job = next.getJob();
+          if (!job.isSetExternalCompactionId()) {
+            LOG.trace("No external compactions in queue {}", this.getResourceGroup());
+            UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
             continue;
           }
-          LOG.debug("Received next compaction job: {}", job);
+          if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
+            throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
+                + " does not match supplied eci " + currentCompactionId.get());
+          }
+        } catch (RetriesExceededException e2) {
+          LOG.warn("Retries exceeded getting next job. Retrying...");
+          continue;
+        }
+        LOG.debug("Received next compaction job: {}", job);
 
-          final LongAdder totalInputEntries = new LongAdder();
-          final LongAdder totalInputBytes = new LongAdder();
-          final CountDownLatch started = new CountDownLatch(1);
-          final CountDownLatch stopped = new CountDownLatch(1);
+        final LongAdder totalInputEntries = new LongAdder();
+        final LongAdder totalInputBytes = new LongAdder();
+        final CountDownLatch started = new CountDownLatch(1);
+        final CountDownLatch stopped = new CountDownLatch(1);
 
-          final FileCompactorRunnable fcr =
-              createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
+        final FileCompactorRunnable fcr =
+            createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
 
-          final Thread compactionThread = Threads.createNonCriticalThread(
-              "Compaction job for tablet " + job.getExtent().toString(), fcr);
+        final Thread compactionThread = Threads.createNonCriticalThread(
+            "Compaction job for tablet " + job.getExtent().toString(), fcr);
 
-          JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
+        JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
 
-          try {
-            // mark compactor as busy while compacting
-            updateIdleStatus(false);
+        try {
+          // mark compactor as busy while compacting
+          updateIdleStatus(false);
 
+          try {
             // Need to call FileCompactorRunnable.initialize after calling JOB_HOLDER.set
             fcr.initialize();
-
-            compactionThread.start(); // start the compactionThread
-            started.await(); // wait until the compactor is started
-            final long inputEntries = totalInputEntries.sum();
-            final long waitTime = calculateProgressCheckTime(totalInputBytes.sum());
-            LOG.debug("Progress checks will occur every {} seconds", waitTime);
-            String percentComplete = "unknown";
-
-            while (!stopped.await(waitTime, TimeUnit.SECONDS)) {
-              List<CompactionInfo> running =
-                  org.apache.accumulo.server.compaction.FileCompactor.getRunningCompactions();
-              if (!running.isEmpty()) {
-                // Compaction has started. There should only be one in the list
-                CompactionInfo info = running.get(0);
-                if (info != null) {
-                  final long entriesRead = info.getEntriesRead();
-                  final long entriesWritten = info.getEntriesWritten();
-                  if (inputEntries > 0) {
-                    percentComplete = Float.toString((entriesRead / (float) inputEntries) * 100);
-                  }
-                  String message = String.format(
-                      "Compaction in progress, read %d of %d input entries ( %s %s ), written %d entries",
-                      entriesRead, inputEntries, percentComplete, "%", entriesWritten);
-                  watcher.run();
-                  try {
-                    LOG.debug("Updating coordinator with compaction progress: {}.", message);
-                    TCompactionStatusUpdate update = new TCompactionStatusUpdate(
-                        TCompactionState.IN_PROGRESS, message, inputEntries, entriesRead,
-                        entriesWritten, fcr.getCompactionAge().toNanos());
-                    updateCompactionState(job, update);
-                  } catch (RetriesExceededException e) {
-                    LOG.warn("Error updating coordinator with compaction progress, error: {}",
-                        e.getMessage());
-                  }
-                }
-              } else {
-                LOG.debug("Waiting on compaction thread to finish, but no RUNNING compaction");
-              }
-            }
-            compactionThread.join();
-            LOG.trace("Compaction thread finished.");
-            // Run the watcher again to clear out the finished compaction and set the
-            // stuck count to zero.
-            watcher.run();
-
-            if (err.get() != null) {
-              // maybe the error occured because the table was deleted or something like that, so
-              // force a cancel check to possibly reduce noise in the logs
-              checkIfCanceled();
+          } catch (RetriesExceededException e) {
+            LOG.error(
+                "Error starting FileCompactableRunnable, cancelling compaction and moving to next job.",
+                e);
+            try {
+              cancel(job.getExternalCompactionId());
+            } catch (TException e1) {
+              LOG.error("Error cancelling compaction.", e1);
             }
+            continue;
+          } finally {
+            currentCompactionId.set(null);
+          }
 
-            if (compactionThread.isInterrupted() || JOB_HOLDER.isCancelled()
-                || (err.get() != null && err.get().getClass().equals(InterruptedException.class))) {
-              LOG.warn("Compaction thread was interrupted, sending CANCELLED state");
-              try {
-                TCompactionStatusUpdate update =
-                    new TCompactionStatusUpdate(TCompactionState.CANCELLED, "Compaction cancelled",
-                        -1, -1, -1, fcr.getCompactionAge().toNanos());
-                updateCompactionState(job, update);
-                updateCompactionFailed(job, InterruptedException.class.getName());
-                cancelled.incrementAndGet();
-              } catch (RetriesExceededException e) {
-                LOG.error("Error updating coordinator with compaction cancellation.", e);
-              } finally {
-                currentCompactionId.set(null);
-              }
-            } else if (err.get() != null) {
-              final KeyExtent fromThriftExtent = KeyExtent.fromThrift(job.getExtent());
-              try {
-                LOG.info("Updating coordinator with compaction failure: id: {}, extent: {}",
-                    job.getExternalCompactionId(), fromThriftExtent);
-                TCompactionStatusUpdate update = new TCompactionStatusUpdate(
-                    TCompactionState.FAILED, "Compaction failed due to: " + err.get().getMessage(),
-                    -1, -1, -1, fcr.getCompactionAge().toNanos());
-                updateCompactionState(job, update);
-                updateCompactionFailed(job, err.get().getClass().getName());
-                failed.incrementAndGet();
-                errorHistory.addError(fromThriftExtent.tableId(), err.get());
-              } catch (RetriesExceededException e) {
-                LOG.error("Error updating coordinator with compaction failure: id: {}, extent: {}",
-                    job.getExternalCompactionId(), fromThriftExtent, e);
-              } finally {
-                currentCompactionId.set(null);
-              }
-            } else {
-              try {
-                LOG.trace("Updating coordinator with compaction completion.");
-                updateCompactionCompleted(job, JOB_HOLDER.getStats());
-                completed.incrementAndGet();
-                // job completed successfully, clear the error history
-                errorHistory.clear();
-              } catch (RetriesExceededException e) {
-                LOG.error(
-                    "Error updating coordinator with compaction completion, cancelling compaction.",
-                    e);
+          compactionThread.start(); // start the compactionThread
+          started.await(); // wait until the compactor is started
+          final long inputEntries = totalInputEntries.sum();
+          final long waitTime = calculateProgressCheckTime(totalInputBytes.sum());
+          LOG.debug("Progress checks will occur every {} seconds", waitTime);
+          String percentComplete = "unknown";
+
+          while (!stopped.await(waitTime, TimeUnit.SECONDS)) {
+            List<CompactionInfo> running =
+                org.apache.accumulo.server.compaction.FileCompactor.getRunningCompactions();
+            if (!running.isEmpty()) {
+              // Compaction has started. There should only be one in the list
+              CompactionInfo info = running.get(0);
+              if (info != null) {
+                final long entriesRead = info.getEntriesRead();
+                final long entriesWritten = info.getEntriesWritten();
+                if (inputEntries > 0) {
+                  percentComplete = Float.toString((entriesRead / (float) inputEntries) * 100);
+                }
+                String message = String.format(
+                    "Compaction in progress, read %d of %d input entries ( %s %s ), written %d entries",
+                    entriesRead, inputEntries, percentComplete, "%", entriesWritten);
+                watcher.run();
                 try {
-                  cancel(job.getExternalCompactionId());
-                } catch (TException e1) {
-                  LOG.error("Error cancelling compaction.", e1);
+                  LOG.debug("Updating coordinator with compaction progress: {}.", message);
+                  TCompactionStatusUpdate update = new TCompactionStatusUpdate(
+                      TCompactionState.IN_PROGRESS, message, inputEntries, entriesRead,
+                      entriesWritten, fcr.getCompactionAge().toNanos());
+                  updateCompactionState(job, update);
+                } catch (RetriesExceededException e) {
+                  LOG.warn("Error updating coordinator with compaction progress, error: {}",
+                      e.getMessage());
                 }
-              } finally {
-                currentCompactionId.set(null);
               }
+            } else {
+              LOG.debug("Waiting on compaction thread to finish, but no RUNNING compaction");
             }
-          } catch (RuntimeException e1) {
-            LOG.error(
-                "Compactor thread was interrupted waiting for compaction to start, cancelling job",
-                e1);
+          }
+          compactionThread.join();
+          LOG.trace("Compaction thread finished.");
+          // Run the watcher again to clear out the finished compaction and set the
+          // stuck count to zero.
+          watcher.run();
+
+          if (err.get() != null) {
+            // maybe the error occured because the table was deleted or something like that, so
+            // force a cancel check to possibly reduce noise in the logs
+            checkIfCanceled();
+          }
+
+          if (compactionThread.isInterrupted() || JOB_HOLDER.isCancelled()
+              || (err.get() != null && err.get().getClass().equals(InterruptedException.class))) {
+            LOG.warn("Compaction thread was interrupted, sending CANCELLED state");
             try {
-              cancel(job.getExternalCompactionId());
-            } catch (TException e2) {
-              LOG.error("Error cancelling compaction.", e2);
+              TCompactionStatusUpdate update =
+                  new TCompactionStatusUpdate(TCompactionState.CANCELLED, "Compaction cancelled",
+                      -1, -1, -1, fcr.getCompactionAge().toNanos());
+              updateCompactionState(job, update);
+              updateCompactionFailed(job, InterruptedException.class.getName());
+              cancelled.incrementAndGet();
+            } catch (RetriesExceededException e) {
+              LOG.error("Error updating coordinator with compaction cancellation.", e);
+            } finally {
+              currentCompactionId.set(null);
             }
-          } finally {
-            currentCompactionId.set(null);
+          } else if (err.get() != null) {
+            final KeyExtent fromThriftExtent = KeyExtent.fromThrift(job.getExtent());
+            try {
+              LOG.info("Updating coordinator with compaction failure: id: {}, extent: {}",
+                  job.getExternalCompactionId(), fromThriftExtent);
+              TCompactionStatusUpdate update = new TCompactionStatusUpdate(TCompactionState.FAILED,
+                  "Compaction failed due to: " + err.get().getMessage(), -1, -1, -1,
+                  fcr.getCompactionAge().toNanos());
+              updateCompactionState(job, update);
+              updateCompactionFailed(job, err.get().getClass().getName());
+              failed.incrementAndGet();
+              errorHistory.addError(fromThriftExtent.tableId(), err.get());
+            } catch (RetriesExceededException e) {
+              LOG.error("Error updating coordinator with compaction failure: id: {}, extent: {}",
+                  job.getExternalCompactionId(), fromThriftExtent, e);
+            } finally {
+              currentCompactionId.set(null);
+            }
+          } else {
+            try {
+              LOG.trace("Updating coordinator with compaction completion.");
+              updateCompactionCompleted(job, JOB_HOLDER.getStats());
+              completed.incrementAndGet();
+              // job completed successfully, clear the error history
+              errorHistory.clear();
+            } catch (RetriesExceededException e) {
+              LOG.error(
+                  "Error updating coordinator with compaction completion, cancelling compaction.",
+                  e);
+              try {
+                cancel(job.getExternalCompactionId());
+              } catch (TException e1) {
+                LOG.error("Error cancelling compaction.", e1);
+              }
+            } finally {
+              currentCompactionId.set(null);
+            }
+          }
+        } catch (RuntimeException e1) {
+          LOG.error(
+              "Compactor thread was interrupted waiting for compaction to start, cancelling job",
+              e1);
+          try {
+            cancel(job.getExternalCompactionId());
+          } catch (TException e2) {
+            LOG.error("Error cancelling compaction.", e2);
+          }
+        } finally {
+          currentCompactionId.set(null);
 
-            // mark compactor as idle after compaction completes
-            updateIdleStatus(true);
+          // mark compactor as idle after compaction completes
+          updateIdleStatus(true);
 
-            // In the case where there is an error in the foreground code the background compaction
-            // may still be running. Must cancel it before starting another iteration of the loop to
-            // avoid multiple threads updating shared state.
-            while (compactionThread.isAlive()) {
-              compactionThread.interrupt();
-              compactionThread.join(1000);
-            }
+          // In the case where there is an error in the foreground code the background compaction
+          // may still be running. Must cancel it before starting another iteration of the loop to
+          // avoid multiple threads updating shared state.
+          while (compactionThread.isAlive()) {
+            compactionThread.interrupt();
+            compactionThread.join(1000);
           }
-        } catch (InterruptedException e) {
-          LOG.info("Interrupt Exception received, shutting down");
-          gracefulShutdown(getContext().rpcCreds());
         }
-      } // end while
-    } catch (Exception e) {
-      LOG.error("Unhandled error occurred in Compactor", e);
-    } finally {
-      // Shutdown local thrift server
-      LOG.debug("Stopping Thrift Servers");
-      if (getThriftServer() != null) {
-        getThriftServer().stop();
+      } catch (InterruptedException e) {
+        LOG.info("Interrupt Exception received, shutting down");
+        gracefulShutdown(getContext().rpcCreds());
       }
+    } // end while, shutdown requested
 
-      try {
-        LOG.debug("Closing filesystems");
-        VolumeManager mgr = getContext().getVolumeManager();
-        if (null != mgr) {
-          mgr.close();
-        }
-      } catch (IOException e) {
-        LOG.warn("Failed to close filesystem : {}", e.getMessage(), e);
-      }
+    // Shutdown local thrift server
+    LOG.debug("Stopping Thrift Servers");
+    if (getThriftServer() != null) {
+      getThriftServer().stop();
+    }
 
-      getContext().getLowMemoryDetector().logGCInfo(getConfiguration());
-      super.close();
-      getShutdownComplete().set(true);
-      LOG.info("stop requested. exiting ... ");
-      try {
-        if (null != compactorLock) {
-          compactorLock.unlock();
-        }
-      } catch (Exception e) {
-        LOG.warn("Failed to release compactor lock", e);
+    try {
+      LOG.debug("Closing filesystems");
+      VolumeManager mgr = getContext().getVolumeManager();
+      if (null != mgr) {
+        mgr.close();
       }
+    } catch (IOException e) {
+      LOG.warn("Failed to close filesystem : {}", e.getMessage(), e);
     }
 
+    super.close();

Review Comment:
   Implemented in ec5cd1d



##########
server/compactor/src/main/java/org/apache/accumulo/compactor/Compactor.java:
##########
@@ -829,237 +829,241 @@ public void run() {
         getConfiguration().getTimeInMillis(Property.COMPACTOR_CANCEL_CHECK_INTERVAL));
 
     LOG.info("Compactor started, waiting for work");
-    try {
-
-      final AtomicReference<Throwable> err = new AtomicReference<>();
-      final LogSorter logSorter = new LogSorter(this);
-      long nextSortLogsCheckTime = System.currentTimeMillis();
 
-      while (!isShutdownRequested()) {
-        if (Thread.currentThread().isInterrupted()) {
-          LOG.info("Server process thread has been interrupted, shutting down");
-          break;
-        }
-        try {
-          // mark compactor as idle while not in the compaction loop
-          updateIdleStatus(true);
+    final AtomicReference<Throwable> err = new AtomicReference<>();
+    final LogSorter logSorter = new LogSorter(this);
+    long nextSortLogsCheckTime = System.currentTimeMillis();
 
-          currentCompactionId.set(null);
-          err.set(null);
-          JOB_HOLDER.reset();
-
-          if (System.currentTimeMillis() > nextSortLogsCheckTime) {
-            // Attempt to process all existing log sorting work serially in this thread.
-            // When no work remains, this call will return so that we can look for compaction
-            // work.
-            LOG.debug("Checking to see if any recovery logs need sorting");
+    while (!isShutdownRequested()) {
+      if (Thread.currentThread().isInterrupted()) {
+        LOG.info("Server process thread has been interrupted, shutting down");
+        break;
+      }
+      try {
+        // mark compactor as idle while not in the compaction loop
+        updateIdleStatus(true);
+
+        currentCompactionId.set(null);
+        err.set(null);
+        JOB_HOLDER.reset();
+
+        if (System.currentTimeMillis() > nextSortLogsCheckTime) {
+          // Attempt to process all existing log sorting work serially in this thread.
+          // When no work remains, this call will return so that we can look for compaction
+          // work.
+          LOG.debug("Checking to see if any recovery logs need sorting");
+          try {
             nextSortLogsCheckTime = logSorter.sortLogsIfNeeded();
+          } catch (KeeperException e) {
+            LOG.error("Error sorting logs", e);
           }
+        }
 
-          performFailureProcessing(errorHistory);
+        performFailureProcessing(errorHistory);
 
-          TExternalCompactionJob job;
-          try {
-            TNextCompactionJob next = getNextJob(getNextId());
-            job = next.getJob();
-            if (!job.isSetExternalCompactionId()) {
-              LOG.trace("No external compactions in queue {}", this.getResourceGroup());
-              UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
-              continue;
-            }
-            if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
-              throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
-                  + " does not match supplied eci " + currentCompactionId.get());
-            }
-          } catch (RetriesExceededException e2) {
-            LOG.warn("Retries exceeded getting next job. Retrying...");
+        TExternalCompactionJob job;
+        try {
+          TNextCompactionJob next = getNextJob(getNextId());
+          job = next.getJob();
+          if (!job.isSetExternalCompactionId()) {
+            LOG.trace("No external compactions in queue {}", this.getResourceGroup());
+            UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
             continue;
           }
-          LOG.debug("Received next compaction job: {}", job);
+          if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
+            throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
+                + " does not match supplied eci " + currentCompactionId.get());
+          }
+        } catch (RetriesExceededException e2) {
+          LOG.warn("Retries exceeded getting next job. Retrying...");
+          continue;
+        }
+        LOG.debug("Received next compaction job: {}", job);
 
-          final LongAdder totalInputEntries = new LongAdder();
-          final LongAdder totalInputBytes = new LongAdder();
-          final CountDownLatch started = new CountDownLatch(1);
-          final CountDownLatch stopped = new CountDownLatch(1);
+        final LongAdder totalInputEntries = new LongAdder();
+        final LongAdder totalInputBytes = new LongAdder();
+        final CountDownLatch started = new CountDownLatch(1);
+        final CountDownLatch stopped = new CountDownLatch(1);
 
-          final FileCompactorRunnable fcr =
-              createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
+        final FileCompactorRunnable fcr =
+            createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
 
-          final Thread compactionThread = Threads.createNonCriticalThread(
-              "Compaction job for tablet " + job.getExtent().toString(), fcr);
+        final Thread compactionThread = Threads.createNonCriticalThread(
+            "Compaction job for tablet " + job.getExtent().toString(), fcr);
 
-          JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
+        JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
 
-          try {
-            // mark compactor as busy while compacting
-            updateIdleStatus(false);
+        try {
+          // mark compactor as busy while compacting
+          updateIdleStatus(false);
 
+          try {
             // Need to call FileCompactorRunnable.initialize after calling JOB_HOLDER.set
             fcr.initialize();
-
-            compactionThread.start(); // start the compactionThread
-            started.await(); // wait until the compactor is started
-            final long inputEntries = totalInputEntries.sum();
-            final long waitTime = calculateProgressCheckTime(totalInputBytes.sum());
-            LOG.debug("Progress checks will occur every {} seconds", waitTime);
-            String percentComplete = "unknown";
-
-            while (!stopped.await(waitTime, TimeUnit.SECONDS)) {
-              List<CompactionInfo> running =
-                  org.apache.accumulo.server.compaction.FileCompactor.getRunningCompactions();
-              if (!running.isEmpty()) {
-                // Compaction has started. There should only be one in the list
-                CompactionInfo info = running.get(0);
-                if (info != null) {
-                  final long entriesRead = info.getEntriesRead();
-                  final long entriesWritten = info.getEntriesWritten();
-                  if (inputEntries > 0) {
-                    percentComplete = Float.toString((entriesRead / (float) inputEntries) * 100);
-                  }
-                  String message = String.format(
-                      "Compaction in progress, read %d of %d input entries ( %s %s ), written %d entries",
-                      entriesRead, inputEntries, percentComplete, "%", entriesWritten);
-                  watcher.run();
-                  try {
-                    LOG.debug("Updating coordinator with compaction progress: {}.", message);
-                    TCompactionStatusUpdate update = new TCompactionStatusUpdate(
-                        TCompactionState.IN_PROGRESS, message, inputEntries, entriesRead,
-                        entriesWritten, fcr.getCompactionAge().toNanos());
-                    updateCompactionState(job, update);
-                  } catch (RetriesExceededException e) {
-                    LOG.warn("Error updating coordinator with compaction progress, error: {}",
-                        e.getMessage());
-                  }
-                }
-              } else {
-                LOG.debug("Waiting on compaction thread to finish, but no RUNNING compaction");
-              }
-            }
-            compactionThread.join();
-            LOG.trace("Compaction thread finished.");
-            // Run the watcher again to clear out the finished compaction and set the
-            // stuck count to zero.
-            watcher.run();
-
-            if (err.get() != null) {
-              // maybe the error occured because the table was deleted or something like that, so
-              // force a cancel check to possibly reduce noise in the logs
-              checkIfCanceled();
+          } catch (RetriesExceededException e) {
+            LOG.error(
+                "Error starting FileCompactableRunnable, cancelling compaction and moving to next job.",
+                e);
+            try {
+              cancel(job.getExternalCompactionId());
+            } catch (TException e1) {
+              LOG.error("Error cancelling compaction.", e1);
             }
+            continue;
+          } finally {
+            currentCompactionId.set(null);

Review Comment:
   Removed finally block in ec5cd1d



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304022781


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";

Review Comment:
   > What happens w/ the test if this method does not exists? Does the test fail?
   Seems like maybe it would fail because the SHUTDOWN case would expect an exit code of zero but would see some other exit code. But not sure.
   
   I can make it fail explicity by adding the following to ProcessProxy.main:
   
   ```
   diff --git a/test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT.java b/test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT.java
   index 4f8f948d26..c17a30ab6e 100644
   --- a/test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT.java
   +++ b/test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT.java
   @@ -155,6 +155,15 @@ public class ExitCodesIT extends SharedMiniClusterBase {
              throw new UnsupportedOperationException(st + " is not currently supported");
          }
    
   +      // Check that methodName exists on serverClass
   +      try {
   +        @SuppressWarnings("unused")
   +        var ignored = serverClass.getDeclaredMethod(methodName);
   +      } catch (NoSuchMethodException nsme) {
   +        nsme.printStackTrace();
   +        System.exit(42);
   +      }
   +
   ```
   > Wondering if instead of this run time overriding if it would be possible to do it at compile time instead w/ something like the following. Then if someone changes a method name they will get a compile time error.
   
   I think I could make something that is functionally equivalent without using ByteBuddy, but it would be more code. I started with ByteBuddy initially because I wasn't sure of the design when I started, but I knew that I basically needed a proxy for each server class.
   



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2290889850


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########


Review Comment:
   Renamed class



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2289335278


##########
core/src/main/java/org/apache/accumulo/core/clientImpl/ClientContext.java:
##########
@@ -918,21 +918,26 @@ public AuthenticationToken token() {
   @Override
   public synchronized void close() {
     if (closed.compareAndSet(false, true)) {
-      if (zooCacheCreated.get()) {
-        zooCache.get().close();
-      }
-      if (zooKeeperOpened.get()) {
-        zooSession.get().close();

Review Comment:
   This needed to be moved to the end because it closes ZooKeeper, which deletes all ephemeral nodes and fires any watchers.



##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT_SimpleSuite.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT_SimpleSuite extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), compactorArgs.toArray(new String[] {})};
+          break;
+        case GARBAGE_COLLECTOR:
+          serverClass = SimpleGarbageCollector.class;
+          methodName = "logStats";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new String[] {}};
+          break;
+        case MANAGER:
+          serverClass = Manager.class;
+          methodName = "mainWait";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(), new String[] {}};
+          break;
+        case SCAN_SERVER:
+          List<String> scanServerArgs = new ArrayList<>();
+          scanServerArgs.add("-o");
+          scanServerArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = ScanServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), scanServerArgs.toArray(new String[] {})};
+          break;
+        case TABLET_SERVER:
+          List<String> tabletServerArgs = new ArrayList<>();
+          tabletServerArgs.add("-o");
+          tabletServerArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = TabletServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(),
+              tabletServerArgs.toArray(new String[] {})};
+          break;
+        case MONITOR:
+        case ZOOKEEPER:
+        default:
+          throw new UnsupportedOperationException(st + " is not currently supported");
+      }
+
+      final Implementation implementation;
+      switch (behavior) {
+        case ERROR:
+          implementation =
+              ExceptionMethod.throwing(StackOverflowError.class, "throwing unknown error");
+          break;
+        case EXCEPTION:
+          implementation =
+              ExceptionMethod.throwing(RuntimeException.class, "throwing runtime exception");
+          break;
+        case SHUTDOWN:
+          implementation =
+              MethodCall.invoke(AbstractServer.class.getMethod("requestShutdownForTests"));
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+
+      // Dynamically create the subclass with the specified behavior, load it
+      // into the JVM, and return it's Class.
+      // creates a subclass of server class defining a public constructor that
+      // takes an Integer, but calls the server class constructor with the
+      // appropriate args. Calls to the intercepted method name are intercepted
+      // by the supplied implementation
+      final Class<? extends AbstractServer> dynamicServerType =
+          new ByteBuddy().subclass(serverClass, ConstructorStrategy.Default.NO_CONSTRUCTORS)
+              .name("org.apache.accumulo.test.functional.exit_codes." + serverClass.getSimpleName()
+                  + "_" + behavior.name())
+              .defineConstructor(Visibility.PUBLIC).withParameters(Integer.class)
+              .intercept(MethodCall.invoke(serverClass.getDeclaredConstructor(ctorParams)).onSuper()
+                  .with(ctorArgs))
+              .method(ElementMatchers.named(methodName)).intercept(implementation).make()
+              .load(serverClass.getClassLoader()).getLoaded();
+
+      // Find and invoke the constructor of the dynamically created class
+      final Constructor<? extends AbstractServer> ctor =
+          dynamicServerType.getDeclaredConstructor(Integer.class);
+      final AbstractServer dynamicServerInstance = ctor.newInstance(1);
+
+      // Start the server process
+      AbstractServer.startServer(dynamicServerInstance, LoggerFactory.getLogger(serverClass));
+    }
+
+  }
+
+  @BeforeAll
+  public static void beforeTests() throws Exception {
+    // Start MiniCluster so that getCluster() does not
+    // return null,
+    SharedMiniClusterBase.startMiniCluster();
+    getCluster().getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);
+  }
+
+  @AfterAll
+  public static void afterTests() {
+    SharedMiniClusterBase.stopMiniCluster();
+  }
+
+  // Junit doesn't support more than one parameterized
+  // argument to a test method. We need to generate
+  // the arguments here.
+  static Stream<Arguments> generateWorkerProcessArguments() {
+    List<Arguments> args = new ArrayList<>();
+    for (ServerType st : ServerType.values()) {
+      if (st == ServerType.COMPACTOR || st == ServerType.SCAN_SERVER
+          || st == ServerType.TABLET_SERVER) {
+        for (TerminalBehavior tb : TerminalBehavior.values()) {
+          args.add(Arguments.of(st, tb));
+        }
+      }
+    }
+    return args.stream();
+  }
+
+  @ParameterizedTest
+  @MethodSource("generateWorkerProcessArguments")
+  public void testWorkerProcesses(ServerType server, TerminalBehavior behavior) throws Exception {
+    Map<String,String> properties = new HashMap<>();
+    properties.put(ProcessProxy.PROXY_CLASS, server.name());
+    properties.put(ProcessProxy.PROXY_METHOD_BEHAVIOR, behavior.name());
+    getCluster().getConfig().setSystemProperties(properties);
+    ProcessInfo pi = getCluster()._exec(ProcessProxy.class, server, Map.of(), new String[] {});
+    Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000);
+    int exitValue = pi.getProcess().exitValue();
+    if (server != ServerType.SCAN_SERVER) {
+      if (behavior == TerminalBehavior.SHUTDOWN) {
+        assertEquals(0, exitValue);
+      } else {
+        assertEquals(1, exitValue);
+      }
+    } else {
+      // TODO:

Review Comment:
   This should be resolved, wasn't quite sure how to fix it.



##########
server/compactor/src/main/java/org/apache/accumulo/compactor/Compactor.java:
##########
@@ -829,237 +829,247 @@ public void run() {
         getConfiguration().getTimeInMillis(Property.COMPACTOR_CANCEL_CHECK_INTERVAL));
 
     LOG.info("Compactor started, waiting for work");
-    try {
-
-      final AtomicReference<Throwable> err = new AtomicReference<>();
-      final LogSorter logSorter = new LogSorter(this);
-      long nextSortLogsCheckTime = System.currentTimeMillis();
 
-      while (!isShutdownRequested()) {
-        if (Thread.currentThread().isInterrupted()) {
-          LOG.info("Server process thread has been interrupted, shutting down");
-          break;
-        }
-        try {
-          // mark compactor as idle while not in the compaction loop
-          updateIdleStatus(true);
+    final AtomicReference<Throwable> err = new AtomicReference<>();
+    final LogSorter logSorter = new LogSorter(this);
+    long nextSortLogsCheckTime = System.currentTimeMillis();
 
-          currentCompactionId.set(null);
-          err.set(null);
-          JOB_HOLDER.reset();
-
-          if (System.currentTimeMillis() > nextSortLogsCheckTime) {
-            // Attempt to process all existing log sorting work serially in this thread.
-            // When no work remains, this call will return so that we can look for compaction
-            // work.
-            LOG.debug("Checking to see if any recovery logs need sorting");
+    while (!isShutdownRequested()) {
+      if (Thread.currentThread().isInterrupted()) {
+        LOG.info("Server process thread has been interrupted, shutting down");
+        break;
+      }
+      try {
+        // mark compactor as idle while not in the compaction loop
+        updateIdleStatus(true);
+
+        currentCompactionId.set(null);
+        err.set(null);
+        JOB_HOLDER.reset();
+
+        if (System.currentTimeMillis() > nextSortLogsCheckTime) {
+          // Attempt to process all existing log sorting work serially in this thread.
+          // When no work remains, this call will return so that we can look for compaction
+          // work.
+          LOG.debug("Checking to see if any recovery logs need sorting");
+          try {
             nextSortLogsCheckTime = logSorter.sortLogsIfNeeded();
+          } catch (KeeperException e) {
+            LOG.error("Error sorting logs", e);
           }
+        }
 
-          performFailureProcessing(errorHistory);
+        performFailureProcessing(errorHistory);
 
-          TExternalCompactionJob job;
-          try {
-            TNextCompactionJob next = getNextJob(getNextId());
-            job = next.getJob();
-            if (!job.isSetExternalCompactionId()) {
-              LOG.trace("No external compactions in queue {}", this.getResourceGroup());
-              UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
-              continue;
-            }
-            if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
-              throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
-                  + " does not match supplied eci " + currentCompactionId.get());
-            }
-          } catch (RetriesExceededException e2) {
-            LOG.warn("Retries exceeded getting next job. Retrying...");
+        TExternalCompactionJob job;
+        try {
+          TNextCompactionJob next = getNextJob(getNextId());
+          job = next.getJob();
+          if (!job.isSetExternalCompactionId()) {
+            LOG.trace("No external compactions in queue {}", this.getResourceGroup());
+            UtilWaitThread.sleep(getWaitTimeBetweenCompactionChecks(next.getCompactorCount()));
             continue;
           }
-          LOG.debug("Received next compaction job: {}", job);
+          if (!job.getExternalCompactionId().equals(currentCompactionId.get().toString())) {
+            throw new IllegalStateException("Returned eci " + job.getExternalCompactionId()
+                + " does not match supplied eci " + currentCompactionId.get());
+          }
+        } catch (RetriesExceededException e2) {
+          LOG.warn("Retries exceeded getting next job. Retrying...");
+          continue;
+        }
+        LOG.debug("Received next compaction job: {}", job);
 
-          final LongAdder totalInputEntries = new LongAdder();
-          final LongAdder totalInputBytes = new LongAdder();
-          final CountDownLatch started = new CountDownLatch(1);
-          final CountDownLatch stopped = new CountDownLatch(1);
+        final LongAdder totalInputEntries = new LongAdder();
+        final LongAdder totalInputBytes = new LongAdder();
+        final CountDownLatch started = new CountDownLatch(1);
+        final CountDownLatch stopped = new CountDownLatch(1);
 
-          final FileCompactorRunnable fcr =
-              createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
+        final FileCompactorRunnable fcr =
+            createCompactionJob(job, totalInputEntries, totalInputBytes, started, stopped, err);
 
-          final Thread compactionThread = Threads.createNonCriticalThread(
-              "Compaction job for tablet " + job.getExtent().toString(), fcr);
+        final Thread compactionThread = Threads.createNonCriticalThread(
+            "Compaction job for tablet " + job.getExtent().toString(), fcr);
 
-          JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
+        JOB_HOLDER.set(job, compactionThread, fcr.getFileCompactor());
 
-          try {
-            // mark compactor as busy while compacting
-            updateIdleStatus(false);
+        try {
+          // mark compactor as busy while compacting
+          updateIdleStatus(false);
 
+          try {
             // Need to call FileCompactorRunnable.initialize after calling JOB_HOLDER.set
             fcr.initialize();
-
-            compactionThread.start(); // start the compactionThread
-            started.await(); // wait until the compactor is started
-            final long inputEntries = totalInputEntries.sum();
-            final long waitTime = calculateProgressCheckTime(totalInputBytes.sum());
-            LOG.debug("Progress checks will occur every {} seconds", waitTime);
-            String percentComplete = "unknown";
-
-            while (!stopped.await(waitTime, TimeUnit.SECONDS)) {
-              List<CompactionInfo> running =
-                  org.apache.accumulo.server.compaction.FileCompactor.getRunningCompactions();
-              if (!running.isEmpty()) {
-                // Compaction has started. There should only be one in the list
-                CompactionInfo info = running.get(0);
-                if (info != null) {
-                  final long entriesRead = info.getEntriesRead();
-                  final long entriesWritten = info.getEntriesWritten();
-                  if (inputEntries > 0) {
-                    percentComplete = Float.toString((entriesRead / (float) inputEntries) * 100);
-                  }
-                  String message = String.format(
-                      "Compaction in progress, read %d of %d input entries ( %s %s ), written %d entries",
-                      entriesRead, inputEntries, percentComplete, "%", entriesWritten);
-                  watcher.run();
-                  try {
-                    LOG.debug("Updating coordinator with compaction progress: {}.", message);
-                    TCompactionStatusUpdate update = new TCompactionStatusUpdate(
-                        TCompactionState.IN_PROGRESS, message, inputEntries, entriesRead,
-                        entriesWritten, fcr.getCompactionAge().toNanos());
-                    updateCompactionState(job, update);
-                  } catch (RetriesExceededException e) {
-                    LOG.warn("Error updating coordinator with compaction progress, error: {}",
-                        e.getMessage());
-                  }
-                }
-              } else {
-                LOG.debug("Waiting on compaction thread to finish, but no RUNNING compaction");
-              }
-            }
-            compactionThread.join();
-            LOG.trace("Compaction thread finished.");
-            // Run the watcher again to clear out the finished compaction and set the
-            // stuck count to zero.
-            watcher.run();
-
-            if (err.get() != null) {
-              // maybe the error occured because the table was deleted or something like that, so
-              // force a cancel check to possibly reduce noise in the logs
-              checkIfCanceled();
+          } catch (RetriesExceededException e) {
+            LOG.error(
+                "Error starting FileCompactableRunnable, cancelling compaction and moving to next job.",
+                e);
+            try {
+              cancel(job.getExternalCompactionId());
+            } catch (TException e1) {
+              LOG.error("Error cancelling compaction.", e1);
             }
+            continue;
+          } finally {
+            currentCompactionId.set(null);
+          }
 
-            if (compactionThread.isInterrupted() || JOB_HOLDER.isCancelled()
-                || (err.get() != null && err.get().getClass().equals(InterruptedException.class))) {
-              LOG.warn("Compaction thread was interrupted, sending CANCELLED state");
-              try {
-                TCompactionStatusUpdate update =
-                    new TCompactionStatusUpdate(TCompactionState.CANCELLED, "Compaction cancelled",
-                        -1, -1, -1, fcr.getCompactionAge().toNanos());
-                updateCompactionState(job, update);
-                updateCompactionFailed(job, InterruptedException.class.getName());
-                cancelled.incrementAndGet();
-              } catch (RetriesExceededException e) {
-                LOG.error("Error updating coordinator with compaction cancellation.", e);
-              } finally {
-                currentCompactionId.set(null);
-              }
-            } else if (err.get() != null) {
-              final KeyExtent fromThriftExtent = KeyExtent.fromThrift(job.getExtent());
-              try {
-                LOG.info("Updating coordinator with compaction failure: id: {}, extent: {}",
-                    job.getExternalCompactionId(), fromThriftExtent);
-                TCompactionStatusUpdate update = new TCompactionStatusUpdate(
-                    TCompactionState.FAILED, "Compaction failed due to: " + err.get().getMessage(),
-                    -1, -1, -1, fcr.getCompactionAge().toNanos());
-                updateCompactionState(job, update);
-                updateCompactionFailed(job, err.get().getClass().getName());
-                failed.incrementAndGet();
-                errorHistory.addError(fromThriftExtent.tableId(), err.get());
-              } catch (RetriesExceededException e) {
-                LOG.error("Error updating coordinator with compaction failure: id: {}, extent: {}",
-                    job.getExternalCompactionId(), fromThriftExtent, e);
-              } finally {
-                currentCompactionId.set(null);
-              }
-            } else {
-              try {
-                LOG.trace("Updating coordinator with compaction completion.");
-                updateCompactionCompleted(job, JOB_HOLDER.getStats());
-                completed.incrementAndGet();
-                // job completed successfully, clear the error history
-                errorHistory.clear();
-              } catch (RetriesExceededException e) {
-                LOG.error(
-                    "Error updating coordinator with compaction completion, cancelling compaction.",
-                    e);
+          compactionThread.start(); // start the compactionThread
+          started.await(); // wait until the compactor is started
+          final long inputEntries = totalInputEntries.sum();
+          final long waitTime = calculateProgressCheckTime(totalInputBytes.sum());
+          LOG.debug("Progress checks will occur every {} seconds", waitTime);
+          String percentComplete = "unknown";
+
+          while (!stopped.await(waitTime, TimeUnit.SECONDS)) {
+            List<CompactionInfo> running =
+                org.apache.accumulo.server.compaction.FileCompactor.getRunningCompactions();
+            if (!running.isEmpty()) {
+              // Compaction has started. There should only be one in the list
+              CompactionInfo info = running.get(0);
+              if (info != null) {
+                final long entriesRead = info.getEntriesRead();
+                final long entriesWritten = info.getEntriesWritten();
+                if (inputEntries > 0) {
+                  percentComplete = Float.toString((entriesRead / (float) inputEntries) * 100);
+                }
+                String message = String.format(
+                    "Compaction in progress, read %d of %d input entries ( %s %s ), written %d entries",
+                    entriesRead, inputEntries, percentComplete, "%", entriesWritten);
+                watcher.run();
                 try {
-                  cancel(job.getExternalCompactionId());
-                } catch (TException e1) {
-                  LOG.error("Error cancelling compaction.", e1);
+                  LOG.debug("Updating coordinator with compaction progress: {}.", message);
+                  TCompactionStatusUpdate update = new TCompactionStatusUpdate(
+                      TCompactionState.IN_PROGRESS, message, inputEntries, entriesRead,
+                      entriesWritten, fcr.getCompactionAge().toNanos());
+                  updateCompactionState(job, update);
+                } catch (RetriesExceededException e) {
+                  LOG.warn("Error updating coordinator with compaction progress, error: {}",
+                      e.getMessage());
                 }
-              } finally {
-                currentCompactionId.set(null);
               }
+            } else {
+              LOG.debug("Waiting on compaction thread to finish, but no RUNNING compaction");
             }
-          } catch (RuntimeException e1) {
-            LOG.error(
-                "Compactor thread was interrupted waiting for compaction to start, cancelling job",
-                e1);
+          }
+          compactionThread.join();
+          LOG.trace("Compaction thread finished.");
+          // Run the watcher again to clear out the finished compaction and set the
+          // stuck count to zero.
+          watcher.run();
+
+          if (err.get() != null) {
+            // maybe the error occured because the table was deleted or something like that, so
+            // force a cancel check to possibly reduce noise in the logs
+            checkIfCanceled();
+          }
+
+          if (compactionThread.isInterrupted() || JOB_HOLDER.isCancelled()
+              || (err.get() != null && err.get().getClass().equals(InterruptedException.class))) {
+            LOG.warn("Compaction thread was interrupted, sending CANCELLED state");
             try {
-              cancel(job.getExternalCompactionId());
-            } catch (TException e2) {
-              LOG.error("Error cancelling compaction.", e2);
+              TCompactionStatusUpdate update =
+                  new TCompactionStatusUpdate(TCompactionState.CANCELLED, "Compaction cancelled",
+                      -1, -1, -1, fcr.getCompactionAge().toNanos());
+              updateCompactionState(job, update);
+              updateCompactionFailed(job, InterruptedException.class.getName());
+              cancelled.incrementAndGet();
+            } catch (RetriesExceededException e) {
+              LOG.error("Error updating coordinator with compaction cancellation.", e);
+            } finally {
+              currentCompactionId.set(null);
             }
-          } finally {
-            currentCompactionId.set(null);
+          } else if (err.get() != null) {
+            final KeyExtent fromThriftExtent = KeyExtent.fromThrift(job.getExtent());
+            try {
+              LOG.info("Updating coordinator with compaction failure: id: {}, extent: {}",
+                  job.getExternalCompactionId(), fromThriftExtent);
+              TCompactionStatusUpdate update = new TCompactionStatusUpdate(TCompactionState.FAILED,
+                  "Compaction failed due to: " + err.get().getMessage(), -1, -1, -1,
+                  fcr.getCompactionAge().toNanos());
+              updateCompactionState(job, update);
+              updateCompactionFailed(job, err.get().getClass().getName());
+              failed.incrementAndGet();
+              errorHistory.addError(fromThriftExtent.tableId(), err.get());
+            } catch (RetriesExceededException e) {
+              LOG.error("Error updating coordinator with compaction failure: id: {}, extent: {}",
+                  job.getExternalCompactionId(), fromThriftExtent, e);
+            } finally {
+              currentCompactionId.set(null);
+            }
+          } else {
+            try {
+              LOG.trace("Updating coordinator with compaction completion.");
+              updateCompactionCompleted(job, JOB_HOLDER.getStats());
+              completed.incrementAndGet();
+              // job completed successfully, clear the error history
+              errorHistory.clear();
+            } catch (RetriesExceededException e) {
+              LOG.error(
+                  "Error updating coordinator with compaction completion, cancelling compaction.",
+                  e);
+              try {
+                cancel(job.getExternalCompactionId());
+              } catch (TException e1) {
+                LOG.error("Error cancelling compaction.", e1);
+              }
+            } finally {
+              currentCompactionId.set(null);
+            }
+          }
+        } catch (RuntimeException e1) {
+          LOG.error(
+              "Compactor thread was interrupted waiting for compaction to start, cancelling job",
+              e1);
+          try {
+            cancel(job.getExternalCompactionId());
+          } catch (TException e2) {
+            LOG.error("Error cancelling compaction.", e2);
+          }
+        } finally {
+          currentCompactionId.set(null);
 
-            // mark compactor as idle after compaction completes
-            updateIdleStatus(true);
+          // mark compactor as idle after compaction completes
+          updateIdleStatus(true);
 
-            // In the case where there is an error in the foreground code the background compaction
-            // may still be running. Must cancel it before starting another iteration of the loop to
-            // avoid multiple threads updating shared state.
-            while (compactionThread.isAlive()) {
-              compactionThread.interrupt();
-              compactionThread.join(1000);
-            }
+          // In the case where there is an error in the foreground code the background compaction
+          // may still be running. Must cancel it before starting another iteration of the loop to
+          // avoid multiple threads updating shared state.
+          while (compactionThread.isAlive()) {
+            compactionThread.interrupt();
+            compactionThread.join(1000);
           }
-        } catch (InterruptedException e) {
-          LOG.info("Interrupt Exception received, shutting down");
-          gracefulShutdown(getContext().rpcCreds());
         }
-      } // end while
-    } catch (Exception e) {
-      LOG.error("Unhandled error occurred in Compactor", e);
-    } finally {

Review Comment:
   The change here was to remove the finally block. It causes the normal close code to occur even in Exception or Error case.



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#issuecomment-3210663241

   I'm seeing an inconsistency in how we handle Exceptions and Errors in the server threads (AbstractServer.run).
   
   In all other threads the AccumuloUncaughtExceptionHandler will:
   
   1. Log an error that the thread is dead on an uncaught Exception
   2. Print the stack trace and a message to stderr then halt the VM on an uncaught Error
   
   For critical tasks put into a ThreadPool, we have a method that watches them and throws an ExecutionError if the task has failed. This Error is uncaught and would bubble up to the AccumuloUncaugthExceptionHandler, terminating the VM.
   
   We made some changes recently to AbstractServer in #5796 and #5808 such that a new method `AbstractServer.startServer` exists because exceptions and errors being throws from `AbstractServer.runServer` were not being logged. This method looks like:
   
   https://github.com/apache/accumulo/blob/3a0d8e5c72915fb4c7ce26d6156d15b0a444fb71/server/base/src/main/java/org/apache/accumulo/server/AbstractServer.java#L78-L97
   
   WIth this new method if `AbstractServer.runServer` completes successfully, then the server process does a normal shutdown finishing with a call to `AbstractServer.close`. Due to the `finally` block in `AbstractServer.startServer` the server's close method will be called again. If `AbstractServer.runServer` throws an Exception or Error, then the server's close method will be called by the `finally` block in `AbstractServer.startServer`, but the other normal shutdown stuff won't occur.
   
   Looking at one of the logs from ExitCodesIT we see the following:
   ```
   2025-08-21T12:59:37,729 12 [exit_codes.TabletServer_ERROR] INFO : TabletServer_ERROR process shut down.
   2025-08-21T12:59:37,729 12 [tserver.TabletServer] ERROR: TabletServer_ERROR died, exception thrown from runServer.
   java.lang.StackOverflowError: throwing unknown error
   	at org.apache.accumulo.test.functional.exit_codes.TabletServer_ERROR.updateIdleStatus(Unknown Source) ~[?:?]
   	at org.apache.accumulo.tserver.TabletServer.run(TabletServer.java:607) ~[classes/:?]
   	at org.apache.accumulo.core.trace.TraceWrappedRunnable.run(TraceWrappedRunnable.java:52) ~[classes/:?]
   	at java.base/java.lang.Thread.run(Thread.java:829) [?:?]
   2025-08-21T12:59:37,733 12 [metrics.MetricsInfoImpl] INFO : Closing metrics registry
   2025-08-21T12:59:37,750 12 [server.ServerContext] DEBUG: Shutting down shared executor pool
   2025-08-21T12:59:37,750 12 [clientImpl.ClientContext] DEBUG: Closing ZooCache
   2025-08-21T12:59:37,750 12 [clientImpl.ClientContext] DEBUG: Closing ZooSession
   2025-08-21T12:59:37,752 21 [lock.ServiceLock] DEBUG: [zlock#5c6acefc-a1c0-4fdc-8c81-a7acd162c56e#] zlock#5c6acefc-a1c0-4fdc-8c81-a7acd162c56e#0000000000 was deleted; WatchedEvent state:SyncConnected type:NodeDeleted path:/tservers/TEST/ip-10-113-15-120.evoforge.org:33045/zlock#5c6acefc-a1c0-4fdc-8c81-a7acd162c56e#0000000000 zxid: 827
   2025-08-21T12:59:37,754 21 [util.Halt] ERROR: FATAL TABLET_SERVER lost lock (reason = LOCK_DELETED), exiting.
   ```
   
   In any other thread, the VM would be halted without closing. I'm thinking that the `finally` block from `AbstractServer.startServer` should be removed. Thoughts?


-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304604086


##########
server/base/src/main/java/org/apache/accumulo/server/AbstractServer.java:
##########
@@ -476,8 +470,22 @@ public void startServiceLockVerificationThread() {
 
   @Override
   public void close() {
-    if (context != null) {
-      context.close();
+
+    context.getLowMemoryDetector().logGCInfo(getConfiguration());
+
+    // Must set shutdown as completed before calling super.close().

Review Comment:
   Updated comment in ec5cd1d



##########
server/base/src/main/java/org/apache/accumulo/server/AbstractServer.java:
##########
@@ -84,15 +84,6 @@ public static void startServer(AbstractServer server, Logger LOG) throws Excepti
       e.printStackTrace();
       LOG.error("{} died, exception thrown from runServer.", server.getClass().getSimpleName(), e);
       throw e;
-    } finally {

Review Comment:
   Fixed in ec5cd1d



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#issuecomment-3211770714

   Yeah, I don't think `server.close` is needed. If `runServer` exits normally without Exception/Error, then it's already been called.


-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2290891456


##########
server/base/src/main/java/org/apache/accumulo/server/ServerContext.java:
##########
@@ -522,9 +522,11 @@ public void close() {
       getMetricsInfo().close();
     }
     if (sharedSchedExecutorCreated.get()) {
+      log.info("Shutting down shared executor pool");

Review Comment:
   Changed to debug in d41dbcc



##########
core/src/main/java/org/apache/accumulo/core/clientImpl/ClientContext.java:
##########
@@ -918,21 +918,26 @@ public AuthenticationToken token() {
   @Override
   public synchronized void close() {
     if (closed.compareAndSet(false, true)) {
-      if (zooCacheCreated.get()) {
-        zooCache.get().close();
-      }
-      if (zooKeeperOpened.get()) {
-        zooSession.get().close();
-      }
       if (thriftTransportPool != null) {
+        log.info("Closing Thrift Transport Pool");
         thriftTransportPool.shutdown();
       }
       if (scannerReadaheadPool != null) {
+        log.info("Closing Scanner ReadAhead Pool");
         scannerReadaheadPool.shutdownNow(); // abort all tasks, client is shutting down
       }
       if (cleanupThreadPool != null) {
+        log.info("Closing Cleanup ThreadPool");
         cleanupThreadPool.shutdown(); // wait for shutdown tasks to execute
       }
+      if (zooCacheCreated.get()) {
+        log.info("Closing ZooCache");

Review Comment:
   Changed to debug in d41dbcc



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304683719


##########
server/base/src/main/java/org/apache/accumulo/server/AbstractServer.java:
##########
@@ -84,15 +84,6 @@ public static void startServer(AbstractServer server, Logger LOG) throws Excepti
       e.printStackTrace();
       LOG.error("{} died, exception thrown from runServer.", server.getClass().getSimpleName(), e);
       throw e;
-    } finally {

Review Comment:
   I don't think we need to. I checked the logs and the Exception and Error are logged correctly. The issue in #5796 was an exception in the try-with-resources was being suppressed when an exception happened in the close. try-with-resources is no longer being used.



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "keith-turner (via GitHub)" <gi...@apache.org>.
keith-turner commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304319407


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";

Review Comment:
   > I think I could make something that is functionally equivalent without using ByteBuddy, but it would be more code. 
   
   If its not much more code then there are benefits. Can fully navigate and manipulate the code in an IDE and easily see what the test references. Also if a method is renamed will get a quick compile time failure instead of this test failing and then trying to figure out why.



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "keith-turner (via GitHub)" <gi...@apache.org>.
keith-turner commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304793444


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT.java:
##########
@@ -0,0 +1,334 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT extends SharedMiniClusterBase {
+
+  public static enum TerminalBehavior {
+    SHUTDOWN, EXCEPTION, ERROR
+  };
+
+  public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+  public static TerminalBehavior getTerminalBehavior() {
+    final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+    Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+    return TerminalBehavior.valueOf(methodBehavior);
+  }
+
+  public static class ExitCompactor extends Compactor {
+
+    public static void main(String[] args) throws Exception {
+      List<String> compactorArgs = new ArrayList<>();
+      compactorArgs.add("-o");
+      compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+      AbstractServer.startServer(new ExitCompactor(getTerminalBehavior(), compactorArgs),
+          LoggerFactory.getLogger(ExitCompactor.class));
+    }
+
+    private final TerminalBehavior behavior;
+
+    public ExitCompactor(TerminalBehavior behavior, List<String> compactorArgs) {
+      super(new ConfigOpts(), compactorArgs.toArray(new String[] {}));
+      this.behavior = behavior;
+    }
+
+    @Override
+    public void updateIdleStatus(boolean isIdle) {
+      switch (behavior) {
+        case ERROR:
+          throw new StackOverflowError("throwing stack overflow error");
+        case EXCEPTION:
+          throw new RuntimeException("throwing runtime exception");
+        case SHUTDOWN:
+          requestShutdownForTests();
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+    }
+  }
+
+  public static class ExitScanServer extends ScanServer {
+
+    public static void main(String[] args) throws Exception {
+      List<String> sserverArgs = new ArrayList<>();
+      sserverArgs.add("-o");
+      sserverArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+      AbstractServer.startServer(new ExitScanServer(getTerminalBehavior(), sserverArgs),
+          LoggerFactory.getLogger(ExitScanServer.class));
+    }
+
+    private final TerminalBehavior behavior;
+
+    public ExitScanServer(TerminalBehavior behavior, List<String> sserverArgs) {
+      super(new ConfigOpts(), sserverArgs.toArray(new String[] {}));
+      this.behavior = behavior;
+    }
+
+    @Override
+    public void updateIdleStatus(boolean isIdle) {
+      switch (behavior) {
+        case ERROR:
+          throw new StackOverflowError("throwing stack overflow error");
+        case EXCEPTION:
+          throw new RuntimeException("throwing runtime exception");
+        case SHUTDOWN:
+          requestShutdownForTests();
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+    }
+  }
+
+  public static class ExitTabletServer extends TabletServer {
+
+    public static void main(String[] args) throws Exception {
+      List<String> tserverArgs = new ArrayList<>();
+      tserverArgs.add("-o");
+      tserverArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+      AbstractServer.startServer(new ExitTabletServer(getTerminalBehavior(), tserverArgs),
+          LoggerFactory.getLogger(ExitTabletServer.class));
+    }
+
+    private final TerminalBehavior behavior;
+
+    public ExitTabletServer(TerminalBehavior behavior, List<String> tserverArgs) {
+      super(new ConfigOpts(), ServerContext::new, tserverArgs.toArray(new String[] {}));
+      this.behavior = behavior;
+    }
+
+    @Override
+    public void updateIdleStatus(boolean isIdle) {
+      switch (behavior) {
+        case ERROR:
+          throw new StackOverflowError("throwing stack overflow error");
+        case EXCEPTION:
+          throw new RuntimeException("throwing runtime exception");
+        case SHUTDOWN:
+          requestShutdownForTests();
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+    }
+  }
+
+  public static class ExitGC extends SimpleGarbageCollector {
+
+    public static void main(String[] args) throws Exception {
+      AbstractServer.startServer(new ExitGC(getTerminalBehavior()),
+          LoggerFactory.getLogger(ExitGC.class));
+    }
+
+    private final TerminalBehavior behavior;
+
+    public ExitGC(TerminalBehavior behavior) {
+      super(new ConfigOpts(), new String[] {});
+      this.behavior = behavior;
+    }
+
+    @Override
+    public void logStats() {
+      switch (behavior) {
+        case ERROR:
+          throw new StackOverflowError("throwing stack overflow error");
+        case EXCEPTION:
+          throw new RuntimeException("throwing runtime exception");
+        case SHUTDOWN:
+          requestShutdownForTests();
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+    }
+  }
+
+  public static class ExitManager extends Manager {
+
+    public static void main(String[] args) throws Exception {
+      AbstractServer.startServer(new ExitManager(getTerminalBehavior()),
+          LoggerFactory.getLogger(ExitManager.class));
+    }
+
+    private final TerminalBehavior behavior;
+
+    public ExitManager(TerminalBehavior behavior) throws IOException {
+      super(new ConfigOpts(), ServerContext::new, new String[] {});
+      this.behavior = behavior;
+    }
+
+    @Override
+    public void mainWait() throws InterruptedException {
+      switch (behavior) {
+        case ERROR:
+          throw new StackOverflowError("throwing stack overflow error");
+        case EXCEPTION:
+          throw new RuntimeException("throwing runtime exception");
+        case SHUTDOWN:
+          requestShutdownForTests();
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+    }
+  }
+
+  @BeforeAll
+  public static void beforeTests() throws Exception {
+    // Start MiniCluster so that getCluster() does not
+    // return null,
+    SharedMiniClusterBase.startMiniCluster();
+    getCluster().getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);
+  }
+
+  @AfterAll
+  public static void afterTests() {
+    SharedMiniClusterBase.stopMiniCluster();
+  }
+
+  // Junit doesn't support more than one parameterized
+  // argument to a test method. We need to generate
+  // the arguments here.
+  static Stream<Arguments> generateWorkerProcessArguments() {
+    List<Arguments> args = new ArrayList<>();
+    for (ServerType st : ServerType.values()) {
+      if (st == ServerType.COMPACTOR || st == ServerType.SCAN_SERVER
+          || st == ServerType.TABLET_SERVER) {
+        for (TerminalBehavior tb : TerminalBehavior.values()) {
+          args.add(Arguments.of(st, tb));
+        }
+      }
+    }
+    return args.stream();
+  }
+
+  @ParameterizedTest
+  @MethodSource("generateWorkerProcessArguments")
+  public void testWorkerProcesses(ServerType server, TerminalBehavior behavior) throws Exception {
+    Map<String,String> properties = new HashMap<>();
+    properties.put(PROXY_METHOD_BEHAVIOR, behavior.name());
+    getCluster().getConfig().setSystemProperties(properties);
+    Class<?> serverClass = null;
+    switch (server) {
+      case COMPACTOR:
+        serverClass = ExitCompactor.class;
+        break;
+      case SCAN_SERVER:
+        serverClass = ExitScanServer.class;
+        break;
+      case TABLET_SERVER:
+        serverClass = ExitTabletServer.class;
+        break;
+      case GARBAGE_COLLECTOR:
+      case MANAGER:
+      case MONITOR:
+      case ZOOKEEPER:
+      default:
+        throw new IllegalArgumentException("Unhandled type");
+    }
+    ProcessInfo pi = getCluster()._exec(serverClass, server, Map.of(), new String[] {});
+    Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000);
+    int exitValue = pi.getProcess().exitValue();
+    assertEquals(behavior == TerminalBehavior.SHUTDOWN ? 0 : 1, exitValue);
+  }
+
+  @ParameterizedTest
+  @EnumSource
+  public void testGarbageCollector(TerminalBehavior behavior) throws Exception {
+    Map<String,String> properties = new HashMap<>();
+    properties.put(PROXY_METHOD_BEHAVIOR, behavior.name());
+    getCluster().getConfig().setSystemProperties(properties);
+    ProcessInfo pi =
+        getCluster()._exec(ExitGC.class, ServerType.GARBAGE_COLLECTOR, Map.of(), new String[] {});
+    if (behavior == TerminalBehavior.SHUTDOWN) {
+      Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000);
+      int exitValue = pi.getProcess().exitValue();
+      assertEquals(0, exitValue);
+    } else if (behavior == TerminalBehavior.EXCEPTION) {
+      // GarbageCollector logs exceptions and keeps going.
+      // We need to let this time out and then
+      // terminate the process.
+      IllegalStateException ise = assertThrows(IllegalStateException.class,
+          () -> Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000));

Review Comment:
   Does this always wait for 2 mins?  If so, could we lower time to wait to 30s or 60s?



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304601969


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";

Review Comment:
   Removed ByteBuddy and subclassed server processes in ec5cd1d



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2290888187


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT_SimpleSuite.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT_SimpleSuite extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), compactorArgs.toArray(new String[] {})};
+          break;
+        case GARBAGE_COLLECTOR:
+          serverClass = SimpleGarbageCollector.class;
+          methodName = "logStats";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new String[] {}};
+          break;
+        case MANAGER:
+          serverClass = Manager.class;
+          methodName = "mainWait";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(), new String[] {}};
+          break;
+        case SCAN_SERVER:
+          List<String> scanServerArgs = new ArrayList<>();
+          scanServerArgs.add("-o");
+          scanServerArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = ScanServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), scanServerArgs.toArray(new String[] {})};
+          break;
+        case TABLET_SERVER:
+          List<String> tabletServerArgs = new ArrayList<>();
+          tabletServerArgs.add("-o");
+          tabletServerArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = TabletServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(),
+              tabletServerArgs.toArray(new String[] {})};
+          break;
+        case MONITOR:
+        case ZOOKEEPER:
+        default:
+          throw new UnsupportedOperationException(st + " is not currently supported");
+      }
+
+      final Implementation implementation;
+      switch (behavior) {
+        case ERROR:
+          implementation =
+              ExceptionMethod.throwing(StackOverflowError.class, "throwing unknown error");
+          break;
+        case EXCEPTION:
+          implementation =
+              ExceptionMethod.throwing(RuntimeException.class, "throwing runtime exception");
+          break;
+        case SHUTDOWN:
+          implementation =
+              MethodCall.invoke(AbstractServer.class.getMethod("requestShutdownForTests"));
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+
+      // Dynamically create the subclass with the specified behavior, load it
+      // into the JVM, and return it's Class.
+      // creates a subclass of server class defining a public constructor that
+      // takes an Integer, but calls the server class constructor with the
+      // appropriate args. Calls to the intercepted method name are intercepted
+      // by the supplied implementation
+      final Class<? extends AbstractServer> dynamicServerType =
+          new ByteBuddy().subclass(serverClass, ConstructorStrategy.Default.NO_CONSTRUCTORS)
+              .name("org.apache.accumulo.test.functional.exit_codes." + serverClass.getSimpleName()
+                  + "_" + behavior.name())
+              .defineConstructor(Visibility.PUBLIC).withParameters(Integer.class)
+              .intercept(MethodCall.invoke(serverClass.getDeclaredConstructor(ctorParams)).onSuper()
+                  .with(ctorArgs))
+              .method(ElementMatchers.named(methodName)).intercept(implementation).make()
+              .load(serverClass.getClassLoader()).getLoaded();
+
+      // Find and invoke the constructor of the dynamically created class
+      final Constructor<? extends AbstractServer> ctor =
+          dynamicServerType.getDeclaredConstructor(Integer.class);
+      final AbstractServer dynamicServerInstance = ctor.newInstance(1);
+
+      // Start the server process
+      AbstractServer.startServer(dynamicServerInstance, LoggerFactory.getLogger(serverClass));
+    }
+
+  }
+
+  @BeforeAll
+  public static void beforeTests() throws Exception {
+    // Start MiniCluster so that getCluster() does not
+    // return null,
+    SharedMiniClusterBase.startMiniCluster();
+    getCluster().getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);

Review Comment:
   Renamed class so it's not part of the suite in d41dbcc



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#issuecomment-3208148795

   Best viewed using the "Hide Whitespace" option.


-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "ctubbsii (via GitHub)" <gi...@apache.org>.
ctubbsii commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2289446786


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########


Review Comment:
   Is this really a SimpleSuite test case? The SimpleSuite tests use a shared mini cluster for all tests in the suite, because they don't do anything that would mess up the cluster state that would prevent a different test from running. I haven't finished looking at this entire test, but the nature of it seems like it is intentionally changing the state (killing processes).



##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT_SimpleSuite.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT_SimpleSuite extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.

Review Comment:
   Good comment... but this is wild :sweat_smile: 



##########
server/base/src/main/java/org/apache/accumulo/server/ServerContext.java:
##########
@@ -522,9 +522,11 @@ public void close() {
       getMetricsInfo().close();
     }
     if (sharedSchedExecutorCreated.get()) {
+      log.info("Shutting down shared executor pool");

Review Comment:
   Also debug here



##########
server/compactor/src/main/java/org/apache/accumulo/compactor/Compactor.java:
##########
@@ -829,237 +829,247 @@ public void run() {
         getConfiguration().getTimeInMillis(Property.COMPACTOR_CANCEL_CHECK_INTERVAL));
 
     LOG.info("Compactor started, waiting for work");
-    try {
-
-      final AtomicReference<Throwable> err = new AtomicReference<>();
-      final LogSorter logSorter = new LogSorter(this);
-      long nextSortLogsCheckTime = System.currentTimeMillis();
 
-      while (!isShutdownRequested()) {
-        if (Thread.currentThread().isInterrupted()) {
-          LOG.info("Server process thread has been interrupted, shutting down");
-          break;
-        }
-        try {
-          // mark compactor as idle while not in the compaction loop
-          updateIdleStatus(true);
+    final AtomicReference<Throwable> err = new AtomicReference<>();
+    final LogSorter logSorter = new LogSorter(this);
+    long nextSortLogsCheckTime = System.currentTimeMillis();

Review Comment:
   Not for this PR, but I wonder if this needs to use the system clock or can be made to use relative time (nanoTime).



##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT_SimpleSuite.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT_SimpleSuite extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), compactorArgs.toArray(new String[] {})};
+          break;
+        case GARBAGE_COLLECTOR:
+          serverClass = SimpleGarbageCollector.class;
+          methodName = "logStats";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new String[] {}};
+          break;
+        case MANAGER:
+          serverClass = Manager.class;
+          methodName = "mainWait";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(), new String[] {}};
+          break;
+        case SCAN_SERVER:
+          List<String> scanServerArgs = new ArrayList<>();
+          scanServerArgs.add("-o");
+          scanServerArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = ScanServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), scanServerArgs.toArray(new String[] {})};
+          break;
+        case TABLET_SERVER:
+          List<String> tabletServerArgs = new ArrayList<>();
+          tabletServerArgs.add("-o");
+          tabletServerArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = TabletServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(),
+              tabletServerArgs.toArray(new String[] {})};
+          break;
+        case MONITOR:
+        case ZOOKEEPER:
+        default:
+          throw new UnsupportedOperationException(st + " is not currently supported");
+      }
+
+      final Implementation implementation;
+      switch (behavior) {
+        case ERROR:
+          implementation =
+              ExceptionMethod.throwing(StackOverflowError.class, "throwing unknown error");
+          break;
+        case EXCEPTION:
+          implementation =
+              ExceptionMethod.throwing(RuntimeException.class, "throwing runtime exception");
+          break;
+        case SHUTDOWN:
+          implementation =
+              MethodCall.invoke(AbstractServer.class.getMethod("requestShutdownForTests"));
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+
+      // Dynamically create the subclass with the specified behavior, load it
+      // into the JVM, and return it's Class.
+      // creates a subclass of server class defining a public constructor that
+      // takes an Integer, but calls the server class constructor with the
+      // appropriate args. Calls to the intercepted method name are intercepted
+      // by the supplied implementation
+      final Class<? extends AbstractServer> dynamicServerType =
+          new ByteBuddy().subclass(serverClass, ConstructorStrategy.Default.NO_CONSTRUCTORS)
+              .name("org.apache.accumulo.test.functional.exit_codes." + serverClass.getSimpleName()
+                  + "_" + behavior.name())
+              .defineConstructor(Visibility.PUBLIC).withParameters(Integer.class)
+              .intercept(MethodCall.invoke(serverClass.getDeclaredConstructor(ctorParams)).onSuper()
+                  .with(ctorArgs))
+              .method(ElementMatchers.named(methodName)).intercept(implementation).make()
+              .load(serverClass.getClassLoader()).getLoaded();
+
+      // Find and invoke the constructor of the dynamically created class
+      final Constructor<? extends AbstractServer> ctor =
+          dynamicServerType.getDeclaredConstructor(Integer.class);
+      final AbstractServer dynamicServerInstance = ctor.newInstance(1);
+
+      // Start the server process
+      AbstractServer.startServer(dynamicServerInstance, LoggerFactory.getLogger(serverClass));
+    }
+
+  }
+
+  @BeforeAll
+  public static void beforeTests() throws Exception {
+    // Start MiniCluster so that getCluster() does not
+    // return null,
+    SharedMiniClusterBase.startMiniCluster();
+    getCluster().getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);

Review Comment:
   I don't think you can do this as part of the SimpleSuite tests. This method would only get run when running it as a standalone test. I don't think it would be called, and thus the GC wouldn't be stopped, when run as part of the suite.



##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT_SimpleSuite.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT_SimpleSuite extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), compactorArgs.toArray(new String[] {})};
+          break;
+        case GARBAGE_COLLECTOR:
+          serverClass = SimpleGarbageCollector.class;
+          methodName = "logStats";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new String[] {}};
+          break;
+        case MANAGER:
+          serverClass = Manager.class;
+          methodName = "mainWait";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(), new String[] {}};
+          break;
+        case SCAN_SERVER:
+          List<String> scanServerArgs = new ArrayList<>();
+          scanServerArgs.add("-o");
+          scanServerArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = ScanServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), scanServerArgs.toArray(new String[] {})};
+          break;
+        case TABLET_SERVER:
+          List<String> tabletServerArgs = new ArrayList<>();
+          tabletServerArgs.add("-o");
+          tabletServerArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = TabletServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(),
+              tabletServerArgs.toArray(new String[] {})};
+          break;
+        case MONITOR:
+        case ZOOKEEPER:
+        default:
+          throw new UnsupportedOperationException(st + " is not currently supported");
+      }
+
+      final Implementation implementation;
+      switch (behavior) {
+        case ERROR:
+          implementation =
+              ExceptionMethod.throwing(StackOverflowError.class, "throwing unknown error");
+          break;
+        case EXCEPTION:
+          implementation =
+              ExceptionMethod.throwing(RuntimeException.class, "throwing runtime exception");
+          break;
+        case SHUTDOWN:
+          implementation =
+              MethodCall.invoke(AbstractServer.class.getMethod("requestShutdownForTests"));
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+
+      // Dynamically create the subclass with the specified behavior, load it
+      // into the JVM, and return it's Class.
+      // creates a subclass of server class defining a public constructor that
+      // takes an Integer, but calls the server class constructor with the
+      // appropriate args. Calls to the intercepted method name are intercepted
+      // by the supplied implementation
+      final Class<? extends AbstractServer> dynamicServerType =
+          new ByteBuddy().subclass(serverClass, ConstructorStrategy.Default.NO_CONSTRUCTORS)
+              .name("org.apache.accumulo.test.functional.exit_codes." + serverClass.getSimpleName()
+                  + "_" + behavior.name())
+              .defineConstructor(Visibility.PUBLIC).withParameters(Integer.class)
+              .intercept(MethodCall.invoke(serverClass.getDeclaredConstructor(ctorParams)).onSuper()
+                  .with(ctorArgs))
+              .method(ElementMatchers.named(methodName)).intercept(implementation).make()
+              .load(serverClass.getClassLoader()).getLoaded();
+
+      // Find and invoke the constructor of the dynamically created class
+      final Constructor<? extends AbstractServer> ctor =
+          dynamicServerType.getDeclaredConstructor(Integer.class);
+      final AbstractServer dynamicServerInstance = ctor.newInstance(1);
+
+      // Start the server process
+      AbstractServer.startServer(dynamicServerInstance, LoggerFactory.getLogger(serverClass));
+    }
+
+  }
+
+  @BeforeAll
+  public static void beforeTests() throws Exception {
+    // Start MiniCluster so that getCluster() does not
+    // return null,
+    SharedMiniClusterBase.startMiniCluster();
+    getCluster().getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);
+  }
+
+  @AfterAll
+  public static void afterTests() {
+    SharedMiniClusterBase.stopMiniCluster();
+  }
+
+  // Junit doesn't support more than one parameterized
+  // argument to a test method. We need to generate
+  // the arguments here.
+  static Stream<Arguments> generateWorkerProcessArguments() {
+    List<Arguments> args = new ArrayList<>();
+    for (ServerType st : ServerType.values()) {
+      if (st == ServerType.COMPACTOR || st == ServerType.SCAN_SERVER
+          || st == ServerType.TABLET_SERVER) {
+        for (TerminalBehavior tb : TerminalBehavior.values()) {
+          args.add(Arguments.of(st, tb));
+        }
+      }
+    }
+    return args.stream();
+  }
+
+  @ParameterizedTest
+  @MethodSource("generateWorkerProcessArguments")
+  public void testWorkerProcesses(ServerType server, TerminalBehavior behavior) throws Exception {
+    Map<String,String> properties = new HashMap<>();
+    properties.put(ProcessProxy.PROXY_CLASS, server.name());
+    properties.put(ProcessProxy.PROXY_METHOD_BEHAVIOR, behavior.name());
+    getCluster().getConfig().setSystemProperties(properties);
+    ProcessInfo pi = getCluster()._exec(ProcessProxy.class, server, Map.of(), new String[] {});
+    Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000);
+    int exitValue = pi.getProcess().exitValue();
+    if (server != ServerType.SCAN_SERVER) {
+      if (behavior == TerminalBehavior.SHUTDOWN) {
+        assertEquals(0, exitValue);
+      } else {
+        assertEquals(1, exitValue);
+      }

Review Comment:
   I find this easier to read, because it's less code, but others may feel differently.
   ```suggestion
         assertEquals(behavior == TerminalBehavior.SHUTDOWN ? 0 : 1, exitValue);
   ```



##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT_SimpleSuite.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT_SimpleSuite extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), compactorArgs.toArray(new String[] {})};
+          break;
+        case GARBAGE_COLLECTOR:
+          serverClass = SimpleGarbageCollector.class;
+          methodName = "logStats";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new String[] {}};
+          break;
+        case MANAGER:
+          serverClass = Manager.class;
+          methodName = "mainWait";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(), new String[] {}};
+          break;
+        case SCAN_SERVER:
+          List<String> scanServerArgs = new ArrayList<>();
+          scanServerArgs.add("-o");
+          scanServerArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = ScanServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), scanServerArgs.toArray(new String[] {})};
+          break;
+        case TABLET_SERVER:
+          List<String> tabletServerArgs = new ArrayList<>();
+          tabletServerArgs.add("-o");
+          tabletServerArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = TabletServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(),
+              tabletServerArgs.toArray(new String[] {})};
+          break;
+        case MONITOR:
+        case ZOOKEEPER:
+        default:
+          throw new UnsupportedOperationException(st + " is not currently supported");
+      }
+
+      final Implementation implementation;
+      switch (behavior) {
+        case ERROR:
+          implementation =
+              ExceptionMethod.throwing(StackOverflowError.class, "throwing unknown error");
+          break;
+        case EXCEPTION:
+          implementation =
+              ExceptionMethod.throwing(RuntimeException.class, "throwing runtime exception");
+          break;
+        case SHUTDOWN:
+          implementation =
+              MethodCall.invoke(AbstractServer.class.getMethod("requestShutdownForTests"));
+          break;
+        default:
+          throw new UnsupportedOperationException(behavior + " is not currently supported");
+      }
+
+      // Dynamically create the subclass with the specified behavior, load it
+      // into the JVM, and return it's Class.
+      // creates a subclass of server class defining a public constructor that
+      // takes an Integer, but calls the server class constructor with the
+      // appropriate args. Calls to the intercepted method name are intercepted
+      // by the supplied implementation
+      final Class<? extends AbstractServer> dynamicServerType =
+          new ByteBuddy().subclass(serverClass, ConstructorStrategy.Default.NO_CONSTRUCTORS)
+              .name("org.apache.accumulo.test.functional.exit_codes." + serverClass.getSimpleName()
+                  + "_" + behavior.name())
+              .defineConstructor(Visibility.PUBLIC).withParameters(Integer.class)
+              .intercept(MethodCall.invoke(serverClass.getDeclaredConstructor(ctorParams)).onSuper()
+                  .with(ctorArgs))
+              .method(ElementMatchers.named(methodName)).intercept(implementation).make()
+              .load(serverClass.getClassLoader()).getLoaded();
+
+      // Find and invoke the constructor of the dynamically created class
+      final Constructor<? extends AbstractServer> ctor =
+          dynamicServerType.getDeclaredConstructor(Integer.class);
+      final AbstractServer dynamicServerInstance = ctor.newInstance(1);
+
+      // Start the server process
+      AbstractServer.startServer(dynamicServerInstance, LoggerFactory.getLogger(serverClass));
+    }
+
+  }
+
+  @BeforeAll
+  public static void beforeTests() throws Exception {
+    // Start MiniCluster so that getCluster() does not
+    // return null,
+    SharedMiniClusterBase.startMiniCluster();
+    getCluster().getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);
+  }
+
+  @AfterAll
+  public static void afterTests() {
+    SharedMiniClusterBase.stopMiniCluster();
+  }
+
+  // Junit doesn't support more than one parameterized
+  // argument to a test method. We need to generate
+  // the arguments here.
+  static Stream<Arguments> generateWorkerProcessArguments() {
+    List<Arguments> args = new ArrayList<>();
+    for (ServerType st : ServerType.values()) {
+      if (st == ServerType.COMPACTOR || st == ServerType.SCAN_SERVER
+          || st == ServerType.TABLET_SERVER) {
+        for (TerminalBehavior tb : TerminalBehavior.values()) {
+          args.add(Arguments.of(st, tb));
+        }
+      }
+    }
+    return args.stream();
+  }
+
+  @ParameterizedTest
+  @MethodSource("generateWorkerProcessArguments")
+  public void testWorkerProcesses(ServerType server, TerminalBehavior behavior) throws Exception {
+    Map<String,String> properties = new HashMap<>();
+    properties.put(ProcessProxy.PROXY_CLASS, server.name());
+    properties.put(ProcessProxy.PROXY_METHOD_BEHAVIOR, behavior.name());
+    getCluster().getConfig().setSystemProperties(properties);
+    ProcessInfo pi = getCluster()._exec(ProcessProxy.class, server, Map.of(), new String[] {});
+    Wait.waitFor(() -> !pi.getProcess().isAlive(), 120_000);
+    int exitValue = pi.getProcess().exitValue();
+    if (server != ServerType.SCAN_SERVER) {

Review Comment:
   Please swap around this if/else, so we're not checking a negative. It makes it easier to read when checking `if ==, then X, else Y` rather than `if !=, then Y, else X`.



##########
core/src/main/java/org/apache/accumulo/core/lock/ServiceLockSupport.java:
##########
@@ -111,11 +111,11 @@ public synchronized void failedToAcquireLock(Exception e) {
         String msg =
             "Failed to acquire " + server + " lock due to incorrect ZooKeeper authentication.";
         LOG.error("{} Ensure instance.secret is consistent across Accumulo configuration", msg, e);
-        Halt.halt(-1, msg);
+        Halt.halt(1, msg);
       }
 
       if (acquiredLock) {
-        Halt.halt(-1,
+        Halt.halt(1,

Review Comment:
   :+1:  to using positive numbers.



##########
core/src/main/java/org/apache/accumulo/core/clientImpl/ClientContext.java:
##########
@@ -918,21 +918,26 @@ public AuthenticationToken token() {
   @Override
   public synchronized void close() {
     if (closed.compareAndSet(false, true)) {
-      if (zooCacheCreated.get()) {
-        zooCache.get().close();
-      }
-      if (zooKeeperOpened.get()) {
-        zooSession.get().close();
-      }
       if (thriftTransportPool != null) {
+        log.info("Closing Thrift Transport Pool");
         thriftTransportPool.shutdown();
       }
       if (scannerReadaheadPool != null) {
+        log.info("Closing Scanner ReadAhead Pool");
         scannerReadaheadPool.shutdownNow(); // abort all tasks, client is shutting down
       }
       if (cleanupThreadPool != null) {
+        log.info("Closing Cleanup ThreadPool");
         cleanupThreadPool.shutdown(); // wait for shutdown tasks to execute
       }
+      if (zooCacheCreated.get()) {
+        log.info("Closing ZooCache");

Review Comment:
   I think these log messages could be at debug. They're pretty noisy, and it's not like we log at INFO when we create them. They are all internal resources. The user doesn't necessarily care to see all this internal thread cleanup for the normal case.



##########
server/manager/src/main/java/org/apache/accumulo/manager/Manager.java:
##########
@@ -1206,7 +1206,7 @@ boolean canSuspendTablets() {
         break;
       }
       try {
-        Thread.sleep(500);
+        mainWait();
       } catch (InterruptedException e) {
         log.info("Interrupt Exception received, shutting down");
         gracefulShutdown(context.rpcCreds());

Review Comment:
   Does this mean we get a graceful shutdown if we do Ctrl-C on the process while it's sleeping here? That doesn't seem quite right, but maybe that's the best option? I'm curious why it was done this way.



##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT_SimpleSuite.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT_SimpleSuite extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), compactorArgs.toArray(new String[] {})};
+          break;
+        case GARBAGE_COLLECTOR:
+          serverClass = SimpleGarbageCollector.class;
+          methodName = "logStats";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new String[] {}};
+          break;
+        case MANAGER:
+          serverClass = Manager.class;
+          methodName = "mainWait";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(), new String[] {}};
+          break;
+        case SCAN_SERVER:
+          List<String> scanServerArgs = new ArrayList<>();
+          scanServerArgs.add("-o");
+          scanServerArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = ScanServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), scanServerArgs.toArray(new String[] {})};
+          break;
+        case TABLET_SERVER:
+          List<String> tabletServerArgs = new ArrayList<>();
+          tabletServerArgs.add("-o");
+          tabletServerArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = TabletServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(),

Review Comment:
   Can't you inline the ServerContextFunction like the server processes normally do, as in:
   
   ```suggestion
             ctorArgs = new Object[] {new ConfigOpts(), ServerContext::new,
   ```



##########
server/gc/src/main/java/org/apache/accumulo/gc/SimpleGarbageCollector.java:
##########
@@ -352,15 +352,12 @@ public void run() {
         gracefulShutdown(getContext().rpcCreds());
       }
     }
-    super.close();
+    // Must set shutdown as completed before calling super.close().
+    // super.close() calls ServerContext.close() ->
+    // ClientContext.close() -> ZooSession.close() which removes
+    // all of the ephemeral nodes and forces the watches to fire.
     getShutdownComplete().set(true);
-    log.info("stop requested. exiting ... ");
-    try {
-      gcLock.unlock();
-    } catch (Exception e) {
-      log.warn("Failed to release GarbageCollector lock", e);
-    }
-
+    super.close();

Review Comment:
   Is that something that we always do together? If so, I wonder if it can be done inside the close, or if the getShutdownComplete() stuff is needed at all.



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2290859723


##########
test/src/main/java/org/apache/accumulo/test/functional/ExitCodesIT_SimpleSuite.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.test.functional;
+
+import static org.apache.accumulo.harness.AccumuloITBase.MINI_CLUSTER_ONLY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.accumulo.compactor.Compactor;
+import org.apache.accumulo.core.cli.ConfigOpts;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.conf.SiteConfiguration;
+import org.apache.accumulo.gc.SimpleGarbageCollector;
+import org.apache.accumulo.harness.SharedMiniClusterBase;
+import org.apache.accumulo.manager.Manager;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.ProcessInfo;
+import org.apache.accumulo.server.AbstractServer;
+import org.apache.accumulo.server.ServerContext;
+import org.apache.accumulo.test.functional.ExitCodesIT_SimpleSuite.ProcessProxy.TerminalBehavior;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.accumulo.tserver.ScanServer;
+import org.apache.accumulo.tserver.TabletServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.modifier.Visibility;
+import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.ExceptionMethod;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodCall;
+import net.bytebuddy.matcher.ElementMatchers;
+
+@Tag(MINI_CLUSTER_ONLY)
+public class ExitCodesIT_SimpleSuite extends SharedMiniClusterBase {
+
+  public static class ServerContextFunction implements Function<SiteConfiguration,ServerContext> {
+
+    @Override
+    public ServerContext apply(SiteConfiguration site) {
+      return new ServerContext(site);
+    }
+
+  }
+
+  // Dynamic Proxy class for a server instance that will be invoked via
+  // Accumulo's Main class using MiniAccumuloClusterImpl._exec(). This
+  // ProcessProxy class will determine which class to instantiate
+  // and what the terminal behavior should be using two system
+  // properties. A subclass of the desired class is dynamically created
+  // and started.
+  public static class ProcessProxy {
+
+    public static enum TerminalBehavior {
+      SHUTDOWN, EXCEPTION, ERROR
+    };
+
+    public static final String PROXY_CLASS = "proxy.server";
+    public static final String PROXY_METHOD_BEHAVIOR = "proxy.method.behavior";
+
+    public static void main(String[] args) throws Exception {
+
+      final String proxyServer = System.getProperty(PROXY_CLASS);
+      Objects.requireNonNull(proxyServer, PROXY_CLASS + " must exist as an env var");
+      final String methodBehavior = System.getProperty(PROXY_METHOD_BEHAVIOR);
+      Objects.requireNonNull(methodBehavior, methodBehavior + " must exist as an env var");
+
+      final ServerType st = ServerType.valueOf(proxyServer);
+      final TerminalBehavior behavior = TerminalBehavior.valueOf(methodBehavior);
+
+      // Determine the constructor arguments and parameters for each server class.
+      // Find a method with no-args that does not return anything that is
+      // called during the servers run method that we can intercept to signal
+      // shutdown, exception, or error.
+      final Class<? extends AbstractServer> serverClass;
+      final String methodName;
+      final Class<?>[] ctorParams;
+      final Object[] ctorArgs;
+      switch (st) {
+        case COMPACTOR:
+          List<String> compactorArgs = new ArrayList<>();
+          compactorArgs.add("-o");
+          compactorArgs.add(Property.COMPACTOR_GROUP_NAME.getKey() + "=TEST");
+          serverClass = Compactor.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), compactorArgs.toArray(new String[] {})};
+          break;
+        case GARBAGE_COLLECTOR:
+          serverClass = SimpleGarbageCollector.class;
+          methodName = "logStats";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new String[] {}};
+          break;
+        case MANAGER:
+          serverClass = Manager.class;
+          methodName = "mainWait";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(), new String[] {}};
+          break;
+        case SCAN_SERVER:
+          List<String> scanServerArgs = new ArrayList<>();
+          scanServerArgs.add("-o");
+          scanServerArgs.add(Property.SSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = ScanServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), scanServerArgs.toArray(new String[] {})};
+          break;
+        case TABLET_SERVER:
+          List<String> tabletServerArgs = new ArrayList<>();
+          tabletServerArgs.add("-o");
+          tabletServerArgs.add(Property.TSERV_GROUP_NAME.getKey() + "=TEST");
+          serverClass = TabletServer.class;
+          methodName = "updateIdleStatus";
+          ctorParams = new Class<?>[] {ConfigOpts.class, Function.class, String[].class};
+          ctorArgs = new Object[] {new ConfigOpts(), new ServerContextFunction(),

Review Comment:
   I tried this initially, and I get a compilation error that says "The target type of this expression must be a functional interface"



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "dlmarion (via GitHub)" <gi...@apache.org>.
dlmarion commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304212029


##########
server/base/src/main/java/org/apache/accumulo/server/AbstractServer.java:
##########
@@ -84,15 +84,6 @@ public static void startServer(AbstractServer server, Logger LOG) throws Excepti
       e.printStackTrace();
       LOG.error("{} died, exception thrown from runServer.", server.getClass().getSimpleName(), e);
       throw e;
-    } finally {

Review Comment:
   I thought it was for the logging of Error, not just Exception. 



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "keith-turner (via GitHub)" <gi...@apache.org>.
keith-turner commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304327579


##########
server/base/src/main/java/org/apache/accumulo/server/AbstractServer.java:
##########
@@ -84,15 +84,6 @@ public static void startServer(AbstractServer server, Logger LOG) throws Excepti
       e.printStackTrace();
       LOG.error("{} died, exception thrown from runServer.", server.getClass().getSimpleName(), e);
       throw e;
-    } finally {

Review Comment:
   It was for logging an error in the case where finally threw an exception in which case the error would be lost and would not propagate.  W/o the finally the error will propagate now.  So it depends on what the outer code does with it.  



-- 
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: notifications-unsubscribe@accumulo.apache.org

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


Re: [PR] Added ExitCodesIT to test process exit codes under various conditions [accumulo]

Posted by "keith-turner (via GitHub)" <gi...@apache.org>.
keith-turner commented on code in PR #5811:
URL: https://github.com/apache/accumulo/pull/5811#discussion_r2304660712


##########
server/base/src/main/java/org/apache/accumulo/server/AbstractServer.java:
##########
@@ -84,15 +84,6 @@ public static void startServer(AbstractServer server, Logger LOG) throws Excepti
       e.printStackTrace();
       LOG.error("{} died, exception thrown from runServer.", server.getClass().getSimpleName(), e);
       throw e;
-    } finally {

Review Comment:
   Do we still want to catch an exception and log here to achieve the goals of #5796?  I was commenting about catching Throwable because it was only added in #5808 because of the finally. So not sure we need to catch Throwable, but may still want to catch exception.



-- 
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: notifications-unsubscribe@accumulo.apache.org

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