mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Valery Kharseko
60 mins ago d10be9455ccee71072843da100f9102d410a4406
Prevent duplicate changelog cursors during replica publication (#1352)

A domain cursor could discover a new replica database in its initial
scan and then receive a second notification when the writer finished
publishing that same database. If the reader had already consumed a
change, it could replay it. If both cursors reached the same change
together, one could remain open at shutdown.

`FileChangelogDB` now uses the same per-domain lock for publishing a
replica and for scanning and registering a new reader. A reader that
starts before publication receives the notification. A reader that
starts afterwards discovers the replica in its initial scan and uses its
requested starting CSN.

The regression test opens a reader during publication and verifies that
it reads the change exactly once. It fails on the parent commit and
passes with this change. A separate local reproduction produced
`msgID=269` with one cursor still open on the parent commit and zero
open cursors with the fix.

The [combined scale-empty run on
#1341](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/46504297800/job/142249558104)
reported the same shutdown error. Its artifact records the log path and
cursor count. The identity of the reader in that run remains unknown.

Maven verification passed with 141 changelog tests across six test
classes. The original Docker convergence scenario is covered by CI.
2 files modified
107 ■■■■■ changed files
opendj-server-legacy/src/main/java/org/opends/server/replication/server/changelog/file/FileChangelogDB.java 37 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/server/changelog/file/FileChangelogDBTest.java 70 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/replication/server/changelog/file/FileChangelogDB.java
@@ -199,19 +199,6 @@
      final Pair<FileReplicaDB, Boolean> result = getExistingOrNewReplicaDB(domainMap, serverId, baseDN, server);
      if (result != null)
      {
        final Boolean dbWasCreated = result.getSecond();
        if (dbWasCreated)
        { // new replicaDB => update all cursors with it
          final List<DomainDBCursor> cursors = registeredDomainCursors.get(baseDN);
          if (cursors != null && !cursors.isEmpty())
          {
            for (DomainDBCursor cursor : cursors)
            {
              cursor.addReplicaDB(serverId, null);
            }
          }
        }
        return result;
      }
    }
@@ -305,7 +292,17 @@
        }
        final FileReplicaDB newDB = newReplicaDB(serverId, baseDN, server, cryptoSuite, replicationEnv);
        final List<DomainDBCursor> cursors = domainCursors(baseDN);
        synchronized (cursors)
        {
          // A reader must either discover this replica in its initial scan or receive the
          // creation announcement. Doing both can open two cursors over the same log.
        domainMap.put(serverId, newDB);
          for (DomainDBCursor cursor : cursors)
          {
            cursor.addReplicaDB(serverId, null);
          }
        }
        return Pair.of(newDB, true);
      }
      finally
@@ -823,21 +820,23 @@
  public DBCursor<UpdateMsg> getCursorFrom(final DN baseDN, final ServerState startState, CursorOptions options)
      throws ChangelogException
  {
    final DomainDBCursor cursor = newDomainDBCursor(baseDN, options);
    final DomainDBCursor cursor = new DomainDBCursor(baseDN, this, options);
    final List<DomainDBCursor> cursors = domainCursors(baseDN);
    synchronized (cursors)
    {
    for (int serverId : getDomainMap(baseDN).keySet())
    {
      // get the last already sent CSN from that server to get a cursor
      final CSN lastCSN = startState != null ? startState.getCSN(serverId) : null;
      cursor.addReplicaDB(serverId, lastCSN);
    }
      cursors.add(cursor);
    }
    return cursor;
  }
  private DomainDBCursor newDomainDBCursor(final DN baseDN, final CursorOptions options)
  private List<DomainDBCursor> domainCursors(final DN baseDN)
  {
    final DomainDBCursor cursor = new DomainDBCursor(baseDN, this, options);
    putCursor(registeredDomainCursors, baseDN, cursor);
    return cursor;
    return registeredDomainCursors.computeIfAbsent(baseDN, dn -> new CopyOnWriteArrayList<>());
  }
  private CSN getOfflineCSN(DN baseDN, int serverId, CSN startAfterCSN)
opendj-server-legacy/src/test/java/org/opends/server/replication/server/changelog/file/FileChangelogDBTest.java
@@ -25,6 +25,7 @@
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
@@ -553,6 +554,75 @@
    }
  }
  @Test
  public void cursorOpenedDuringReplicaPublicationReadsEachChangeOnce() throws Exception
  {
    TestCaseUtils.startServer();
    final ReplicationServer server = configureReplicationServer(100, 5000);
    final FileChangelogDB db = (FileChangelogDB) server.getChangelogDB();
    final DN dn = DN.valueOf("dc=cursor-publication");
    final CSN csn = new CSN(5000, 1, SERVER_ID);
    final AtomicReference<DBCursor<UpdateMsg>> opened = new AtomicReference<>();
    final FutureTask<Void> firstRead = new FutureTask<>(() ->
    {
      final DBCursor<UpdateMsg> cursor = db.getCursorFrom(dn, new ServerState(),
          new CursorOptions(GREATER_THAN_OR_EQUAL_TO_KEY, AFTER_MATCHING_KEY));
      opened.set(cursor);
      assertTrue(cursor.next());
      assertEquals(cursor.getRecord().getCSN(), csn);
      return null;
    });
    final Thread reader = new Thread(firstRead, "cursor opened during replica publication");
    try
    {
      db.getDomainToReplicaDBs().put(dn, new ConcurrentHashMap<Integer, FileReplicaDB>()
      {
        @Override
        public FileReplicaDB put(Integer serverId, FileReplicaDB replica)
        {
          final FileReplicaDB previous = super.put(serverId, replica);
          try
          {
            replica.add(new DeleteMsg(dn, csn, "uid"));
            reader.start();
            // Let the reader consume the change before the creator can announce it, or let
            // the creator continue once the reader is waiting for its publication lock.
            final ThreadMXBean threads = ManagementFactory.getThreadMXBean();
            final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(TIMEOUT_MS);
            while (!firstRead.isDone())
            {
              final ThreadInfo info = threads.getThreadInfo(reader.getId());
              if (info != null && info.getThreadState() == Thread.State.BLOCKED
                  && info.getLockOwnerId() == Thread.currentThread().getId())
              {
                break;
              }
              assertTrue(System.nanoTime() < deadline, "Reader did not reach replica publication");
              Thread.sleep(1);
            }
          }
          catch (Exception e)
          {
            throw new AssertionError(e);
          }
          return previous;
        }
      });
      db.getOrCreateReplicaDB(dn, SERVER_ID, server);
      firstRead.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
      assertFalse(opened.get().next(), "The creation announcement replayed the change already read");
    }
    finally
    {
      join(reader);
      if (opened.get() != null)
      {
        opened.get().close();
      }
      remove(server);
    }
  }
  /**
   * A creation which bails out on the identity check must not drop the domain map another creation
   * has freshly inserted: the drop is equality based and two empty maps are equal, so an identity