DemonicTutor opened a new issue, #13870:
URL: https://github.com/apache/ignite/issues/13870

   ## Summary
   
   On a server node that was segmented with `SegmentationPolicy.NOOP`, calls 
that wait for a discovery custom message
   never return, for example `QueryCursor.close()` of a continuous query and 
`getOrCreateCache()`. Only stopping the
   node releases them. On a client node the same calls fail at once.
   
   ## Cause
   
   With `NOOP`, `GridDiscoveryManager.onSegmentation()` only disconnects the 
discovery SPI
   ([GridDiscoveryManager 
L3184-L3189](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManager.java#L3184-L3189)).
   `ServerImpl.disconnect()` calls `spiStop0(true)`
   
([L1065-L1067](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java#L1065-L1067)),
   which sets the state to `DISCONNECTING`
   
([L567](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java#L567)),
   cancels the ring message worker
   
([L625](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java#L625))
   and finally sets `DISCONNECTED`
   
([L693](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java#L693)).
   `ServerImpl.sendCustomEvent()` does not check the state: it adds the message 
to the stopped worker's queue, where it
   is never sent, and nothing fails
   
([L1069-L1081](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java#L1069-L1081)).
   
   So `GridContinuousProcessor.stopRoutine()` returns a future that only the 
stop acknowledgement completes
   
([L1058-L1066](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousProcessor.java#L1058-L1066),
   
[L1276-L1281](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousProcessor.java#L1276-L1281)),
   and the cursor's `close()` waits for it without a timeout
   ([IgniteCacheProxyImpl 
L712-L722](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxyImpl.java#L712-L722)).
   The processor's segmentation listener only cancels the futures that exist 
when `EVT_NODE_SEGMENTED` is recorded
   
([L203-L207](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousProcessor.java#L203-L207)).
   `ClientImpl.sendCustomEvent()` throws in the equivalent states
   
([L484-L491](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ClientImpl.java#L484-L491)).
   
   ## Reproducer
   
   Three server nodes on localhost, each in its own JVM, with Ignite's defaults 
except `SegmentationPolicy.NOOP` and a
   static IP finder, and a continuous query on each. The third node is frozen 
with `SIGSTOP` for 20 s, longer than the
   default `failureDetectionTimeout`: the others remove it, and when it resumes 
it is segmented. Its `EVT_NODE_SEGMENTED`
   listener closes its continuous query on a new thread. Linux or macOS. The 
classpath is the `libs/` directory of the
   binary release or `org.apache.ignite:ignite-core` with its dependencies.
   
   ```
   javac -cp "$IGNITE_HOME/libs/*" CqCloseAfterSegmentation.java
   java -cp "$IGNITE_HOME/libs/*:." CqCloseAfterSegmentation
   ```
   
   <details>
   <summary>CqCloseAfterSegmentation.java</summary>
   
   ```java
   import java.io.File;
   import java.nio.charset.StandardCharsets;
   import java.nio.file.Files;
   import java.nio.file.Path;
   import java.util.ArrayList;
   import java.util.List;
   import java.util.concurrent.TimeUnit;
   
   import javax.cache.Cache;
   
   import org.apache.ignite.Ignite;
   import org.apache.ignite.Ignition;
   import org.apache.ignite.cache.query.ContinuousQuery;
   import org.apache.ignite.cache.query.QueryCursor;
   import org.apache.ignite.configuration.IgniteConfiguration;
   import org.apache.ignite.events.EventType;
   import org.apache.ignite.plugin.segmentation.SegmentationPolicy;
   import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
   import 
org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
   
   /**
    * Reproducer: on a server node that was segmented with 
SegmentationPolicy.NOOP, QueryCursor.close() of a continuous
    * query never returns.
    *
    * Starts three server nodes on localhost, each in its own JVM, with 
Ignite's defaults except SegmentationPolicy.NOOP
    * and a static IP finder. Each node runs a continuous query. The third node 
is frozen with SIGSTOP for 20 s (longer
    * than the default failureDetectionTimeout of 10 s): the other two remove 
it, and when it resumes it is segmented.
    * On EVT_NODE_SEGMENTED it closes its continuous query on a new thread. 
Needs Linux or macOS (kill -STOP/-CONT).
    *
    * <pre>
    * javac -cp "$IGNITE_HOME/libs/*" CqCloseAfterSegmentation.java
    * java -cp "$IGNITE_HOME/libs/*:." CqCloseAfterSegmentation
    * </pre>
    * The node JVMs get the classpath of this one and the --add-opens flags 
Ignite needs. Logs: node0.log, node1.log,
    * node2.log.
    */
   public class CqCloseAfterSegmentation {
       public static void main(String[] args) throws Exception {
           if (args.length == 1) {
               node(Integer.parseInt(args[0]));
               return;
           }
           List<Process> nodes = new ArrayList<>();
           try {
               for (int i = 0; i < 3; i++) {
                   List<String> cmd = new ArrayList<>();
                   cmd.add(Path.of(System.getProperty("java.home"), "bin", 
"java").toString());
                   cmd.addAll(igniteJvmFlags());
                   cmd.addAll(List.of("-cp", 
System.getProperty("java.class.path"),
                       CqCloseAfterSegmentation.class.getName(), 
Integer.toString(i)));
                   nodes.add(new ProcessBuilder(cmd).redirectErrorStream(true)
                       .redirectOutput(new File("node" + i + ".log")).start());
                   if (!awaitLine("node" + i + ".log", "[node" + i + "] 
servers=" + (i + 1), "start failed", 60)) {
                       System.out.println("node" + i + " did not start, see 
node" + i + ".log");
                       return;
                   }
               }
               Thread.sleep(5_000);
               System.out.println("cluster of 3 started; freezing node2 for 20 
s");
               signal(nodes.get(2), "-STOP");
               Thread.sleep(20_000);
               signal(nodes.get(2), "-CONT");
               System.out.println("node2 resumed");
               awaitLine("node2.log", "close() ", "still blocked", 45);
               List<String> log = Files.readAllLines(Path.of("node2.log"), 
StandardCharsets.ISO_8859_1);
               for (String line : log)
                   if ((line.startsWith("[node2]") && 
!line.contains("servers=")) || line.contains("Local node SEGMENTED"))
                       System.out.println(line);
               if (log.stream().noneMatch(l -> 
l.contains("EVT_NODE_SEGMENTED")))
                   System.out.println("node2 was not segmented, see node2.log");
               else if (log.stream().anyMatch(l -> l.contains("still blocked")))
                   System.out.println("BUG: close() did not return");
               else
                   System.out.println("close() completed");
           }
           finally {
               nodes.forEach(Process::destroyForcibly);
           }
       }
   
       private static void node(int idx) throws Exception {
           IgniteConfiguration cfg = new IgniteConfiguration()
               .setIgniteInstanceName("node" + idx)
               .setLocalHost("127.0.0.1")
               .setSegmentationPolicy(SegmentationPolicy.NOOP)
               .setIncludeEventTypes(EventType.EVT_NODE_SEGMENTED)
               .setDiscoverySpi(new TcpDiscoverySpi()
                   .setIpFinder(new 
TcpDiscoveryVmIpFinder().setAddresses(List.of("127.0.0.1:47500..47502"))));
   
           Ignite ignite;
           try {
               ignite = Ignition.start(cfg);
           }
           catch (RuntimeException e) {
               log(idx, "start failed: " + e);
               throw e;
           }
   
           QueryCursor<Cache.Entry<Integer, Integer>> cursor = ignite.<Integer, 
Integer>getOrCreateCache("test")
               .query(new ContinuousQuery<Integer, 
Integer>().setLocalListener(evts -> { }));
   
           ignite.events().localListen(evt -> {
               log(idx, "EVT_NODE_SEGMENTED");
               Thread closer = new Thread(() -> {
                   long start = System.nanoTime();
                   log(idx, "closing the continuous query");
                   try {
                       cursor.close();
                       log(idx, "close() returned after " + ms(start) + " ms");
                   }
                   catch (RuntimeException e) {
                       log(idx, "close() threw after " + ms(start) + " ms: " + 
e);
                   }
               }, "cq-close");
               closer.start();
               Thread watchdog = new Thread(() -> {
                   try {
                       closer.join(30_000);
                   }
                   catch (InterruptedException ignored) {
                       return;
                   }
                   if (closer.isAlive()) {
                       log(idx, "close() still blocked after 30 s:");
                       for (StackTraceElement e : closer.getStackTrace())
                           log(idx, "    at " + e);
                   }
               });
               watchdog.setDaemon(true);
               watchdog.start();
               return true;
           }, EventType.EVT_NODE_SEGMENTED);
   
           while (true) {
               log(idx, "servers=" + 
ignite.cluster().forServers().nodes().size());
               Thread.sleep(1000);
           }
       }
   
       private static void log(int idx, String msg) {
           System.out.println("[node" + idx + "] " + msg);
       }
   
       private static long ms(long startNanos) {
           return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
       }
   
       /** The JVM flags Ignite 2.x needs on Java 11 and later. */
       private static List<String> igniteJvmFlags() {
           List<String> flags = new ArrayList<>(List.of("-Xmx512m", 
"-Djava.net.preferIPv4Stack=true",
               "--add-opens=java.base/java.nio=ALL-UNNAMED", 
"--add-opens=java.base/java.util=ALL-UNNAMED",
               "--add-opens=java.base/java.lang=ALL-UNNAMED", 
"--add-opens=java.base/java.lang.invoke=ALL-UNNAMED",
               "--add-opens=java.base/sun.nio.ch=ALL-UNNAMED", 
"--add-opens=java.base/jdk.internal.misc=ALL-UNNAMED",
               "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", 
"--add-exports=java.base/sun.nio.ch=ALL-UNNAMED"));
           int java = Runtime.version().feature();
           if (java >= 23)
               flags.add("--sun-misc-unsafe-memory-access=warn");
           if (java >= 26)
               flags.add("--enable-final-field-mutation=ALL-UNNAMED");
           return flags;
       }
   
       private static void signal(Process p, String sig) throws Exception {
           new ProcessBuilder("kill", sig, 
Long.toString(p.pid())).inheritIO().start().waitFor();
       }
   
       /** @return true if a line contains {@code text}; false if one contains 
{@code alt}, or after the timeout. */
       private static boolean awaitLine(String file, String text, String alt, 
int seconds) throws Exception {
           Path p = Path.of(file);
           for (int i = 0; i < seconds * 10; i++) {
               List<String> lines = Files.exists(p) ? Files.readAllLines(p, 
StandardCharsets.ISO_8859_1) : List.of();
               if (lines.stream().anyMatch(l -> l.contains(text)))
                   return true;
               if (lines.stream().anyMatch(l -> l.contains(alt)))
                   return false;
               Thread.sleep(100);
           }
           return false;
       }
   }
   ```
   </details>
   
   Output with Ignite 2.18.0 on JDK 17.0.21 (the node logs are in `node0.log` 
to `node2.log`):
   
   ```
   cluster of 3 started; freezing node2 for 20 s
   node2 resumed
   [node2] EVT_NODE_SEGMENTED
   [node2] closing the continuous query
   [node2] close() still blocked after 30 s:
   [node2]     at [email protected]/jdk.internal.misc.Unsafe.park(Native 
Method)
   [node2]     at 
[email protected]/java.util.concurrent.locks.LockSupport.park(LockSupport.java:341)
   [node2]     at 
app//org.apache.ignite.internal.util.future.GridFutureAdapter.get0(GridFutureAdapter.java:181)
   [node2]     at 
app//org.apache.ignite.internal.util.future.GridFutureAdapter.get(GridFutureAdapter.java:144)
   [node2]     at 
app//org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl$6.close(IgniteCacheProxyImpl.java:713)
   [node2]     at 
app//CqCloseAfterSegmentation.lambda$node$3(CqCloseAfterSegmentation.java:108)
   [node2]     ...
   BUG: close() did not return
   ```
   
   Also reproduced with Ignite 2.16.0 and 2.17.0; JDK 21, 26 and 27; REPLICATED 
and PARTITIONED caches; SSL;
   `failureDetectionTimeout` from 5 to 30 s; and when the node segments itself 
because it cannot reach its next nodes
   (`Unable to connect to next nodes in a ring`). `getOrCreateCache()` blocks 
the same way, in
   `IgniteKernal.getOrCreateCache(IgniteKernal.java:2477)`. On a healthy node 
the close returns in a few milliseconds.
   
   ## Expected
   
   The calls fail fast on a segmented server node, as on a client node, or, for 
`stopRoutine()`, complete locally: the
   routine is already unregistered on the node, and the remaining nodes drop 
the routines of a failed node.
   
   ## Suggested fix
   
   1. `ServerImpl.sendCustomEvent()` throws `IgniteSpiException` while the SPI 
is disconnecting or disconnected.
      `GridDiscoveryManager.sendCustomEvent()` wraps it
      
([L2312-L2324](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManager.java#L2312-L2324)),
      and `stopRoutine()` already completes its future with it. With this 
change on 2.18.0 the reproducer prints
      `close() threw after 0 ms: class 
org.apache.ignite.spi.IgniteSpiException: Failed to send custom message: 
discovery
      SPI is disconnecting.` (6 runs out of 6); `getOrCreateCache()` fails the 
same way, and a close on a healthy node is
      unchanged.
   2. Change 1 does not help a close that runs inside the `EVT_NODE_SEGMENTED` 
listener: the SPI is disconnected only
      after the listeners return, so the close still never returns (tested). 
`GridContinuousProcessor` could remember the
      segmentation in its listener and complete `stopRoutine()` at once from 
then on; that would also cover a message
      queued just before the disconnect.
   
   <details>
   <summary>Patch for 1 (master)</summary>
   
   ```diff
   --- 
a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java
   +++ 
b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java
   @@ -1068,6 +1068,14 @@
    
        /** {@inheritDoc} */
        @Override public void sendCustomEvent(DiscoverySpiCustomMessage evt) {
   +        TcpDiscoverySpiState state = spiStateCopy();
   +
   +        // After disconnect() (segmentation with SegmentationPolicy.NOOP) 
the ring message worker is stopped:
   +        // a message added to its queue would never be sent, and its sender 
would wait forever.
   +        if (state == DISCONNECTING || state == DISCONNECTED)
   +            throw new IgniteSpiException("Failed to send custom message: 
discovery SPI is " +
   +                state.name().toLowerCase() + '.');
   +
            TcpDiscoveryCustomEventMessage msg;
    
            DiscoverySpiCustomMessage customMsg = U.unwrapCustomMessage(evt);
   ```
   </details>
   
   Minor: `GridContinuousProcessor.onKernalStop()` cancels pending stop futures 
with "Failed to **start**
   continuous query (node is stopping)"
   
([L375](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousProcessor.java#L375)).
   
   ## Workaround
   
   Stop the node from a new thread after `EVT_NODE_SEGMENTED`, as 
`StopNodeFailureHandler` does
   
([L32](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/failure/StopNodeFailureHandler.java#L32));
   the blocked calls then fail (`node is stopping`). Stopping it inside the 
listener deadlocks: the listener
   runs under `GridEventStorageManager`'s busy read lock
   
([L227-L234](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java#L227-L234)),
   and `onKernalStop0()` waits for the write lock
   
([L248-L249](https://github.com/apache/ignite/blob/c017a9230d931e8fdf3c6a8ea60264eaeb9163e6/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java#L248-L249)).
   
   ## Related
   
   - [IGNITE-11222](https://issues.apache.org/jira/browse/IGNITE-11222): with 
`NOOP`, a segmented node's discovery SPI
     also stops listening (the same `disconnect()`).
   - vertx-ignite (5.0.11 and later) closes its continuous query when it shuts 
Vert.x down after a segmentation, and
     that shutdown hangs because of this (vert-x3/vertx-ignite issue: link 
follows).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to