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

9 files modified
681 ■■■■■ changed files
.github/scripts/replication/disturb-scale.sh 181 ●●●●● patch | view | raw | blame | history
.github/scripts/replication/scale-monitor.py 56 ●●●●● patch | view | raw | blame | history
.github/scripts/replication/selftest-disturb-scale.sh 133 ●●●●● patch | view | raw | blame | history
.github/scripts/replication/selftest-scale-monitor.py 29 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/ReplSessionSecurity.java 29 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/replication/server/changelog/file/FileChangelogDB.java 45 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java 101 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/protocol/ReplSessionSecurityTest.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
.github/scripts/replication/disturb-scale.sh
@@ -40,12 +40,13 @@
# The administration port is published on loopback for scale rows. A native client
# avoids starting another JVM for every checkpoint and binds only to that loopback port.
scale_monitor_search() { # <node>
scale_monitor_search() { # <node> [connected-to <monitor DN>]
  local mapping port
  mapping=$(docker port "$1" 4444/tcp) || return 1
  case $mapping in 127.0.0.1:*) port=${mapping#127.0.0.1:} ;; *) echo 'admin port is not loopback-only' >&2; return 1 ;; esac
  case $port in ''|*[!0-9]*) echo 'invalid admin port' >&2; return 1 ;; esac
  printf '%s' "$ROOT_PASSWORD" | python3 -I "$HERE/scale-monitor.py" "$port" "$ROLLING_END_MS"
  shift
  printf '%s' "$ROOT_PASSWORD" | python3 -I "$HERE/scale-monitor.py" "$port" "$ROLLING_END_MS" "$@"
}
scale_checkpoint_query() { # <node> <output> <error> <role>
@@ -270,24 +271,24 @@
# During a combined-node checkpoint, request every pause before waiting for
# the departing node and the other writers to finish their segments. Keep the
# observer's clients running while the others' high-water marks become finite.
# selected writer's clients running while the others' high-water marks become finite.
# The other writers resume after the stop, and the departing writer after its join.
scale_hold_writers() { # <observer DS> <departing DS> <down|up>
  local observer=$1 departing=$2 direction=$3 node
scale_hold_writers() { # <writer DS> <departing DS> <down|up>
  local writer=$1 departing=$2 direction=$3 node
  # On a handoff, keep the old writer running until the new one has active
  # clients. Other parked workers can stay parked throughout.
  if [ -n "$SCALE_WRITER" ]; then
    rolling_resume "$writer" || return 1
    scale_wait "$writer resumes before the handoff" rolling_clients_running "$writer" || return 1
  fi
  SCALE_HELD_WRITERS=
  rolling_request_pause "$departing" || return 1
  for node in $DS_NODES; do
    [ "$node" != "$observer" ] && [ "$node" != "$departing" ] || continue
    # The removed node is absent during scale-in, but is a writer again during scale-out.
    [ "$node" != "$writer" ] && [ "$node" != "$departing" ] || continue
    [ "$direction" != down ] || [ "$node" != "$REMOVED" ] || continue
    rolling_request_pause "$node" || return 1
    SCALE_HELD_WRITERS="$SCALE_HELD_WRITERS $node"
  done
  rolling_pause "$departing" || return 1
  for node in $SCALE_HELD_WRITERS; do rolling_pause "$node" || return 1; done
  scale_wait "$observer has active load clients" rolling_clients_running "$observer" || return 1
  mkdir -p "$OUT/scale-progress" || return 1
  scale_wait "$observer accepts a checkpoint write" scale_probe "$observer" "$departing" "checkpoint-$direction" || return 1
  for node in "$departing" $SCALE_HELD_WRITERS; do rolling_request_pause "$node" || return 1; done
  for node in "$departing" $SCALE_HELD_WRITERS; do rolling_pause "$node" || return 1; done
}
scale_release_writers() {
@@ -297,6 +298,98 @@
  [ -z "$failed" ]
}
scale_writer_connected() { # <writer> <expected endpoint>
  local endpoint
  endpoint=$(scale_monitor_search "$1" connected-to "$MONITOR_DOMAIN") && [ "$endpoint" = "$2" ]
}
# End this wait when the checkpoint is ready or the writer changes route.
# Clearing SCALE_OBSERVER tells the caller to prepare a new checkpoint before stopping.
scale_routed_checkpoint() { # <departing> <down|up> <writer> <endpoint>
  local departing=$1 key= node
  if ! scale_writer_connected "$3" "$4"; then
    SCALE_OBSERVER=
    return 0
  fi
  scale_caught_up "$SCALE_OBSERVER" "$departing" || return 1
  # Docker reads a log position from each node. Recheck the route after these
  # reads finish, just before the stop.
  if [ "$departing" = "$REMOVED" ]; then
    dns_window_open "$departing" || return 200
    window_open "dns:$departing" 180 || return 200
  else
    key="-$2-$departing"
    window_open_key "${key#-}" "dns:$REMOVED" "dns:$departing" || return 200
  fi
  scale_writer_connected "$3" "$4" && return 0
  SCALE_OBSERVER=
  # The stop did not happen. Discard these pending starts so the next attempt
  # captures a new window without excusing errors from the intervening catch-up.
  for node in $ALL_NODES; do
    rm -f "$OUT/logs/$node.window$key" || return 200
    if [ "$departing" = "$REMOVED" ]; then rm -f "$OUT/logs/$node.dns-window" || return 200; fi
  done
  return 0
}
# A combined DS may send changes through a remote RS. Keep a writer whose serving
# RS survives this stop and compare that RS against the departing changelog.
scale_prepare_routed_writer() { # <departing> <down|up> <surviving node=endpoint>...
  local departing=$1 direction=$2 writer observer= pair endpoint probe="checkpoint-$2"
  local -a candidates=("$SCALE_WRITER")
  shift 2
  for pair in "$@"; do
    [ "${pair%%=*}" = "$SCALE_WRITER" ] || candidates+=("${pair%%=*}")
  done
  for writer in "${candidates[@]}"; do
    [ -n "$writer" ] || continue
    endpoint=$(scale_monitor_search "$writer" connected-to "$MONITOR_DOMAIN") || continue
    for pair in "$@"; do
      if [ "${pair#*=}" = "$endpoint" ]; then observer=${pair%%=*}; break 2; fi
    done
  done
  if [ -z "$observer" ]; then
    SCALE_OBSERVER=
    printf 'no workload DS connects to a surviving RS before stopping %s (eligible: %s)\n' \
      "$departing" "$*" >"$OUT/scale-checkpoint/check.txt"
    return 1
  fi
  scale_checkpoint_init "$observer" "$departing" || return 200
  printf 'writer=%s observer=%s endpoint=%s departing=%s\n' "$writer" "$observer" "$endpoint" "$departing" \
    >>"$SCALE_CHECKPOINT_DIR/history.txt" || return 200
  if [ -n "$SCALE_WRITER" ]; then probe="$probe-$SCALE_CHECKPOINT_NUMBER"; fi
  if [ "$writer" != "$SCALE_WRITER" ]; then
    scale_hold_writers "$writer" "$departing" "$direction" || return 200
  fi
  scale_wait "$writer has active load clients" rolling_clients_running "$writer" || return 200
  scale_wait "$writer accepts a checkpoint write" scale_probe "$writer" "$departing" "$probe" || return 200
  SCALE_WRITER=$writer
  scale_writer_connected "$writer" "$endpoint" || return 1
  SCALE_OBSERVER=$observer
  SCALE_ENDPOINT=$endpoint
}
scale_combined_checkpoint() { # <departing> <down|up>
  local departing=$1 direction=$2 node address SCALE_OBSERVER= SCALE_ENDPOINT=
  local -a survivors=()
  SCALE_WRITER=
  mkdir -p "$OUT/scale-checkpoint" "$OUT/scale-progress" || return 1
  for node in $RS_NODES; do
    [ "$node" != "$departing" ] || continue
    [ "$direction" = up ] || [ "$node" != "$REMOVED" ] || continue
    address=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$node") || return 1
    case $address in ''|*[!0-9.]*) return 1 ;; esac
    survivors+=("$node=$address:8989")
  done
  while :; do
    scale_wait "a writer confirms a write through a surviving RS" \
      scale_prepare_routed_writer "$departing" "$direction" "${survivors[@]}" || return 1
    scale_wait "$SCALE_OBSERVER reaches the checkpoint of $departing" \
      scale_routed_checkpoint "$departing" "$direction" "$SCALE_WRITER" "$SCALE_ENDPOINT" || return 1
    [ -z "$SCALE_OBSERVER" ] || return 0
  done
}
# A restart removes the old container and with it its bootstrap timings. Keep the
# Docker timestamp on each line so events from different processes can be correlated.
scale_capture_bootstrap() { # <node> <generation>
@@ -347,33 +440,33 @@
}
scale_roll() { # <node> <peer list>
  local node=$1 peers=$2 role=directory from observer= writer= candidate direction=up
  local node=$1 peers=$2 role=directory from observer= writer= candidate direction=up SCALE_WRITER=
  [ "$peers" != "$SHORT_PEERS" ] || direction=down
  for candidate in $RS_NODES; do
    [ "$candidate" != "$REMOVED" ] && [ "$candidate" != "$node" ] || continue
    observer=$candidate; break
  done
  [ -n "$observer" ] || { fail "no replication server remains while rolling $node"; return 1; }
  for candidate in $DS_NODES; do
    [ "$candidate" != "$REMOVED" ] && [ "$candidate" != "$node" ] || continue
    writer=$candidate; break
  done
  [ -n "$writer" ] || { fail "no directory server remains while rolling $node"; return 1; }
  [ "$TOPOLOGY" != combined ] || role=combined
  case " $RS_ONLY " in *" $node "*) role=replication ;; esac
  SCALE_HELD_WRITERS=
  if [ "$TOPOLOGY" = combined ]; then
    scale_hold_writers "$observer" "$node" "$direction" || { scale_release_writers || :; return 1; }
  elif is_directory_node "$node"; then
    rolling_pause "$node" || return 1
    role=combined
    scale_combined_checkpoint "$node" "$direction" || { scale_release_writers || :; return 1; }
    writer=$SCALE_WRITER
  else
    for candidate in $RS_NODES; do
      [ "$candidate" != "$REMOVED" ] && [ "$candidate" != "$node" ] || continue
      observer=$candidate; break
    done
    [ -n "$observer" ] || { fail "no replication server remains while rolling $node"; return 1; }
    for candidate in $DS_NODES; do
      [ "$candidate" != "$REMOVED" ] && [ "$candidate" != "$node" ] || continue
      writer=$candidate; break
    done
    [ -n "$writer" ] || { fail "no directory server remains while rolling $node"; return 1; }
    case " $RS_ONLY " in *" $node "*) role=replication ;; esac
    if is_directory_node "$node"; then rolling_pause "$node" || return 1; fi
    case " $RS_NODES " in
      *" $node "*)
        scale_checkpoint_wait "$observer reaches a checkpoint of $node" "$observer" "$node" || return 1
        window_open_key "$direction-$node" "dns:$REMOVED" "dns:$node" || return 1 ;;
      *) window_open_key "$direction-$node" "dns:$REMOVED" || return 1 ;;
    esac
  fi
  case " $RS_NODES " in
    *" $node "*) scale_checkpoint_wait "$observer reaches a checkpoint of $node" "$observer" "$node" || { scale_release_writers || :; return 1; } ;;
  esac
  case " $RS_NODES " in
    *" $node "*) window_open_key "$direction-$node" "dns:$REMOVED" "dns:$node" || { scale_release_writers || :; return 1; } ;;
    *) window_open_key "$direction-$node" "dns:$REMOVED" || { scale_release_writers || :; return 1; } ;;
  esac
  from=$(date +%s) || { scale_release_writers || :; return 1; }
  docker stop -t 120 "$node" >/dev/null || { scale_release_writers || :; return 1; }
  scale_release_writers || return 1
@@ -743,18 +836,18 @@
}
disturb() {
  local node from end address surviving_rs= REJOINED_WITH_NEW_ID=0
  local node from end address surviving_rs= REJOINED_WITH_NEW_ID=0 SCALE_WRITER=
  local -a return_window=("dns:$REMOVED" 180) recovery=() certificate_peers=()
  from=$(date +%s) || return 1
  SCALE_HELD_WRITERS=
  if [ "$TOPOLOGY" = combined ]; then
    scale_hold_writers "$SURVIVING_RS" "$REMOVED" down || { scale_release_writers || :; return 1; }
  elif is_directory_node "$REMOVED"; then
    rolling_pause "$REMOVED" || return 1
    scale_combined_checkpoint "$REMOVED" down || { scale_release_writers || :; return 1; }
  else
    if is_directory_node "$REMOVED"; then rolling_pause "$REMOVED" || return 1; fi
    scale_checkpoint_wait "$SURVIVING_RS reaches the departing RS checkpoint" "$SURVIVING_RS" "$REMOVED" || return 1
    dns_window_open "$REMOVED" || return 1
    window_open "dns:$REMOVED" 180 || return 1
  fi
  scale_checkpoint_wait "$SURVIVING_RS reaches the departing RS checkpoint" "$SURVIVING_RS" "$REMOVED" || { scale_release_writers || :; return 1; }
  dns_window_open "$REMOVED" || { scale_release_writers || :; return 1; }
  window_open "dns:$REMOVED" 180 || { scale_release_writers || :; return 1; }
  docker stop -t 120 "$REMOVED" >/dev/null || { scale_release_writers || :; return 1; }
  scale_release_writers || return 1
  ABSENCE_START=$(date +%s) || return 1
.github/scripts/replication/scale-monitor.py
@@ -148,14 +148,18 @@
    return '\n'.join(lines) + '\n\n'
def search(sock, password, deadline, present=b'replicationServer-database',
           attributes=(b'replicationServer-database', b'domain-name', b'last-change')):
    bind = tlv(0x02, b'\x03') + tlv(0x04, b'cn=Directory Manager') + tlv(0x80, password)
    transmit(sock, tlv(0x30, tlv(0x02, b'\x01') + tlv(0x60, bind)), deadline)
def bind(sock, password, deadline):
    request = tlv(0x02, b'\x03') + tlv(0x04, b'cn=Directory Manager') + tlv(0x80, password)
    transmit(sock, tlv(0x30, tlv(0x02, b'\x01') + tlv(0x60, request)), deadline)
    tag, result = message(sock, 1, deadline)
    if tag != 0x61:
        raise LdapError('expected LDAP bind response')
    require_success(result)
def search(sock, password, deadline, present=b'replicationServer-database',
           attributes=(b'replicationServer-database', b'domain-name', b'last-change')):
    bind(sock, password, deadline)
    query = (tlv(0x04, b'cn=monitor') + tlv(0x0a, b'\x02') + tlv(0x0a, b'\x00') +
             tlv(0x02, b'\x00') + tlv(0x02, b'\x00') + tlv(0x01, b'\x00') +
             tlv(0x87, present) + tlv(0x30, b''.join(tlv(0x04, attr) for attr in attributes)))
@@ -201,7 +205,7 @@
    return attributes
def membership_search(sock, deadline, message_id, base, scope, ldap_filter, attribute):
def attribute_search(sock, deadline, message_id, base, scope, ldap_filter, attribute):
    query = (tlv(0x04, base) + tlv(0x0a, bytes([scope])) + tlv(0x0a, b'\x00') +
             tlv(0x02, b'\x00') + tlv(0x02, b'\x00') + tlv(0x01, b'\x00') +
             ldap_filter + tlv(0x30, tlv(0x04, attribute)))
@@ -223,6 +227,16 @@
            raise LdapError('unexpected LDAP search response')
def connected_to(sock, password, deadline, domain):
    bind(sock, password, deadline)
    attribute = b'connected-to'
    entries = attribute_search(sock, deadline, 2, domain.encode('utf-8'), 1, tlv(0x87, attribute), attribute)
    values = entries[0].get('connected-to', []) if len(entries) == 1 else []
    if len(values) != 1 or not values[0]:
        raise LdapError('expected one connected-to endpoint for ' + domain)
    return values[0]
def membership_matches(registry, config, peer, wanted):
    if wanted not in ('present', 'absent') or not registry or not config:
        return False
@@ -240,24 +254,23 @@
def membership(sock, password, deadline, peer, wanted):
    bind = tlv(0x02, b'\x03') + tlv(0x04, b'cn=Directory Manager') + tlv(0x80, password)
    transmit(sock, tlv(0x30, tlv(0x02, b'\x01') + tlv(0x60, bind)), deadline)
    tag, result = message(sock, 1, deadline)
    if tag != 0x61:
        raise LdapError('expected LDAP bind response')
    require_success(result)
    registry = membership_search(sock, deadline, 2, b'cn=Servers,cn=admin data', 1,
                                 tlv(0x87, b'objectClass'), b'hostname')
    bind(sock, password, deadline)
    registry = attribute_search(sock, deadline, 2, b'cn=Servers,cn=admin data', 1,
                                tlv(0x87, b'objectClass'), b'hostname')
    equal = lambda value: tlv(0xa3, tlv(0x04, b'objectClass') + tlv(0x04, value))
    ldap_filter = tlv(0xa1, equal(b'ds-cfg-replication-server') + equal(b'ds-cfg-replication-domain'))
    config = membership_search(sock, deadline, 3, b'cn=config', 2, ldap_filter,
                               b'ds-cfg-replication-server')
    config = attribute_search(sock, deadline, 3, b'cn=config', 2, ldap_filter,
                              b'ds-cfg-replication-server')
    return membership_matches(registry, config, peer, wanted)
def main(argv):
    if len(argv) not in (3, 6) or (len(argv) == 6 and (argv[3] != 'membership' or argv[5] not in ('present', 'absent'))):
        print('usage: scale-monitor.py <loopback port> <load deadline in milliseconds> [membership <peer> <present|absent>]', file=sys.stderr)
    args = argv[3:]
    route = len(args) == 2 and args[0] == 'connected-to'
    member = len(args) == 3 and args[0] == 'membership' and args[2] in ('present', 'absent')
    if len(argv) < 3 or (args and not (route or member)):
        print('usage: scale-monitor.py <loopback port> <load deadline in milliseconds> '
              '[connected-to <monitor DN> | membership <peer> <present|absent>]', file=sys.stderr)
        return 2
    try:
        port, load_deadline = int(argv[1]), int(argv[2]) / 1000
@@ -275,8 +288,13 @@
        context.verify_mode = ssl.CERT_NONE  # Same trust policy as the existing --trustAll search.
        with socket.create_connection(('127.0.0.1', port), timeout=remaining) as raw:
            with context.wrap_socket(raw, server_hostname='localhost') as connection:
                output = search(connection, password, deadline) if len(argv) == 3 else None
                matched = membership(connection, password, deadline, argv[4], argv[5]) if len(argv) == 6 else True
                output, matched = None, True
                if route:
                    output = connected_to(connection, password, deadline, args[1]) + '\n'
                elif member:
                    matched = membership(connection, password, deadline, args[1], args[2])
                else:
                    output = search(connection, password, deadline)
        if time.monotonic() >= deadline or time.time() >= load_deadline:
            raise TimeoutError('LDAP response completed after the deadline')
        if output is not None:
.github/scripts/replication/selftest-disturb-scale.sh
@@ -35,6 +35,7 @@
  ALL_NODES="$DS_NODES${RS_ONLY:+ $RS_ONLY}"
  PEERS=$(echo "$ALL_NODES" | tr ' ' ',')
  TOPOLOGY=$topology SCALE_VOLUME=$mode DISTURB_TIMEOUT=900 ROLLING_END=$((SECONDS + 900))
  NETWORK=fixture MONITOR_DOMAIN='cn=dc_example_dc_com,cn=Replication,cn=monitor'
  BASE_DN=dc=example,dc=com ROOT_PASSWORD=password
  . "$HERE/disturb-scale.sh"
  record() { printf '%s\n' "$*" >>"$OUT/calls"; }
@@ -72,7 +73,14 @@
  }
  start_server() { record "start $1 $2 $PEERS"; [ "$#" -le 2 ] || record "start-options $1 ${*:3}"; }
  admin_search() { echo 'scale checkpoint must not start an admin-search JVM' >&2; return 1; }
  scale_monitor_search() { record "search $1"; echo 'baseline'; }
  scale_monitor_search() {
    if [ "$2" = connected-to ]; then
      printf '%s:8989\n' "$(docker inspect "$1")"
    else
      record "search $1"; echo 'baseline'
    fi
  }
  scale_caught_up() { record "wait scale_caught_up $*"; [ "${FAIL_CHECKPOINT:-0}" != 1 ]; }
  window_open() { record "window $*"; }; window_close() { :; }
  window_open_key() { record "key-open $1"; shift; record "window $*"; }
  window_close_key() { record "window-close $1"; }
@@ -85,6 +93,7 @@
  record_rejoined_id() { REJOINED_WITH_NEW_ID=$new_id; record "identity $1"; }
  scale_backlog() { record "fill $REMOVED"; }
  wait_until() {
    case $3 in scale_prepare_routed_writer|scale_routed_checkpoint) "${@:3}"; return $? ;; esac
    record "wait ${*:3}"
    [ "${FAIL_CHECKPOINT:-0}" != 1 ] || [ "${3:-}" != scale_caught_up ] || return 1
    [ "${FAIL_RETURN_HISTORY:-0}" != 1 ] || [ "${3:-} ${4:-} ${5:-}" != 'scale_caught_up r2 r0' ] || return 1
@@ -102,6 +111,84 @@
  date() { echo 400; }
  sleep() { record "sleep $*"; }
  fail() { echo "$*" >&2; return 1; }
  # d0 writes through the departing RS. d1 starts on d0, switches to d3
  # while log windows open, then switches to the departing RS during catch-up.
  if [ "$topology-$mode-$new_id" = combined-kept-0 ]; then (
    scale_monitor_search() {
      [ "$2" = connected-to ] && [ "$3" = "$MONITOR_DOMAIN" ] || return 1
      case $1 in
        d0) echo 172.18.0.11:8989 ;;
        d1)
          if [ -e "$OUT/blip" ]; then
            rm "$OUT/blip"; touch "$OUT/blipped"; echo 172.18.0.12:8989
          elif [ -e "$OUT/switched" ]; then echo 172.18.0.11:8989
          elif [ -e "$OUT/opened" ]; then echo 172.18.0.12:8989
          else echo 172.18.0.9:8989; fi ;;
        d3) echo 172.18.0.10:8989 ;;
        *) return 1 ;;
      esac
    }
    rolling_clients_running() { record "active $1"; }
    scale_probe() {
      record "write $*"
      [ "${FAIL_MOVED_WRITE:-0}" = 0 ] || [ ! -e "$OUT/opened" ]
    }
    scale_caught_up() {
      record "checkpoint $*"
      if [ "$1" = d3 ]; then touch "$OUT/switched"; fi
    }
    window_open_key() {
      local node
      for node in $ALL_NODES; do
        [ ! -e "$OUT/logs/$node.window-$1" ] || return 1
        touch "$OUT/logs/$node.window-$1"
      done
      if [ "${ROUTE_BLIP:-0}" = 1 ] && [ ! -e "$OUT/blipped" ]; then
        touch "$OUT/blip"
      else
        touch "$OUT/opened"
      fi
    }
    wait_until() {
      shift 2
      local try rc
      for try in 1 2 3 4; do
        "$@" && return 0; rc=$?
        [ "$rc" != 200 ] || return 1
      done
      return 1
    }
    started_since() { :; }; bootstrap_ended() { :; }
    if (FAIL_MOVED_WRITE=1; scale_roll d2 "$FULL_PEERS"); then
      echo 'accepted an unconfirmed write after the same DS changed serving RS' >&2; exit 1
    fi
    if grep -q '^docker stop ' "$OUT/calls"; then echo 'stopped after a failed route probe' >&2; exit 1; fi
    rm -f "$OUT/opened" "$OUT/switched"
    : >"$OUT/calls"
    ROUTE_BLIP=1 scale_roll d2 "$FULL_PEERS" || { echo 'could not roll d2 with a surviving route' >&2; exit 1; }
    awk '
      /^active d1$/ && !first { first=NR }
      /^checkpoint d0 d2$/ { observed=NR }
      /^write d1 d2 checkpoint-up/ { probes++; confirmed=NR }
      /^checkpoint d3 d2$/ { moved=NR }
      /^active d3$/ && !replacement { replacement=NR }
      /^resume d0$/ && !stopped { exit 1 }
      /^request-pause d1$/ { held=NR }
      /^checkpoint d1 d2$/ { checked=NR }
      /^docker stop -t 120 d2$/ { stopped=NR }
      /^write d3 d2 up$/ { written=NR }
      END { if (!(probes == 3 && first && first < observed && observed < confirmed && confirmed < moved &&
                  moved < replacement && replacement < held && held < checked && checked < stopped &&
                  stopped < written)) exit 1 }
    ' "$OUT/calls" || { echo 'checkpoint did not follow the active writer to a surviving RS' >&2; exit 1; }
    : >"$OUT/calls"
    # d3 is absent on scale-in. d0 and d1 both use d2, leaving no safe route.
    if scale_roll d2 "$SHORT_PEERS"; then echo 'accepted only departing routes' >&2; exit 1; fi
    if grep -Eq '^(request-pause|docker stop|checkpoint) ' "$OUT/calls"; then
      echo 'changed the topology before finding a surviving route' >&2; exit 1
    fi
  ); fi
  : >"$OUT/calls"
  # No server is stopped if the surviving RS has not reached the departing RS's checkpoint.
  if (FAIL_CHECKPOINT=1; disturb) >/dev/null 2>&1; then
    echo 'failed checkpoint was accepted' >&2; exit 1
@@ -446,6 +533,7 @@
  [ ! -e "$OUT/logs/$target.offline" ]
  # A failed observer query identifies the node and status in the checkpoint diagnostic.
  (
    . "$HERE/disturb-scale.sh"
    scale_monitor_search() { [ "$1" != observer ] || return 124; echo baseline; }
    scale_checkpoint_init observer departing
    if scale_caught_up observer departing; then echo 'failed checkpoint query accepted' >&2; exit 1; fi
@@ -465,6 +553,49 @@
    if (FAIL_PROBE=1; scale_probe_batch d2 up d0 d1 r0); then echo 'failed batch accepted' >&2; exit 1; fi
  fi
)
check_checkpoint_budget() ( # <load end> <caught up at> <expected result> <expected time> [route change at]
  local caught_up_at=$2 switch_at=${5:-} result=0
  OUT="$OUT/budget-$1-$2-$switch_at"
  mkdir -p "$OUT"
  TOPOLOGY=combined SCALE_VOLUME=kept
  . "$HERE/lib.sh"
  . "$HERE/disturb-scale.sh"
  # Use the real wait loop with a deterministic clock. Writer preparation takes 80 s.
  unset SECONDS
  SECONDS=0 ROLLING_END=$1 DISTURB_TIMEOUT=900
  sleep() { SECONDS=$((SECONDS + $1)); }
  rolling_request_pause() { :; }
  rolling_pause() { [ "$1" != "$REMOVED" ] || sleep 80; }
  rolling_clients_running() { :; }
  scale_probe() { :; }
  docker() {
    local node=${*: -1}
    [ "$1" = inspect ] && echo "172.18.0.1${node##*-c}"
  }
  scale_monitor_search() {
    if [ -n "$switch_at" ] && [ "$SECONDS" -ge "$switch_at" ]; then
      echo '172.18.0.11:8989'
    else
      echo '172.18.0.10:8989'
    fi
  }
  scale_caught_up() { [ "$SECONDS" -ge "$caught_up_at" ]; }
  dns_window_open() { :; }
  window_open() { :; }
  scale_combined_checkpoint "$REMOVED" down >"$OUT/result" 2>&1 || result=$?
  if [ "$result" != "$3" ] || [ "$SECONDS" != "$4" ]; then
    cat "$OUT/result" >&2
    echo "checkpoint with load end $1 and catch-up at $2 returned $result at $SECONDS, expected $3 at $4" >&2
    exit 1
  fi
)
check_checkpoint_budget 2580 940 0 940
check_checkpoint_budget 880 940 1 880
check_checkpoint_budget 2580 1000 1 980
# Switching RS at 900 starts a fresh checkpoint, still bounded by the same load end.
check_checkpoint_budget 2580 1700 0 1700 900
check_checkpoint_budget 1500 1700 1 1500 900
for topology in rs534 combined; do
  for mode in kept empty; do run_case "$topology" "$mode"; done
done
.github/scripts/replication/selftest-scale-monitor.py
@@ -57,15 +57,16 @@
class MonitorTest(unittest.TestCase):
    def exchange(self, responses, timeout=3):
    def exchange(self, responses, timeout=3, search=monitor.search, args=()):
        client, server = socket.socketpair()
        errors = []
        self.requests = []
        def respond():
            try:
                monitor.read_frame(server, time.monotonic() + 3)
                self.requests.append(monitor.read_frame(server, time.monotonic() + 3))
                server.sendall(responses[0])
                if len(responses) > 1:
                    monitor.read_frame(server, time.monotonic() + 3)
                    self.requests.append(monitor.read_frame(server, time.monotonic() + 3))
                    for data in responses[1:]:
                        for i in range(0, len(data), 3):
                            server.sendall(data[i:i + 3])
@@ -78,7 +79,7 @@
        thread = threading.Thread(target=respond)
        thread.start()
        try:
            return monitor.search(client, b'password', time.monotonic() + timeout)
            return search(client, b'password', time.monotonic() + timeout, *args)
        finally:
            client.close()
            thread.join(4)
@@ -92,6 +93,26 @@
        self.assertIn('dn:: ', text)
        self.assertTrue(text.endswith('\n\n'))
    def test_connected_to_reads_only_the_workload_domain(self):
        domain = 'cn=dc_example_dc_com,cn=Replication,cn=monitor'
        def route(entries, code=0):
            responses = [msg(1, 0x61, ldap_result(0))]
            responses.extend(msg(2, 0x64, member_entry(b'cn=DS,' + domain.encode(),
                             {b'connected-to': values})) for values in entries)
            responses.append(msg(2, 0x65, ldap_result(code)))
            return self.exchange(responses, search=monitor.connected_to, args=(domain,))
        endpoint = b'172.18.0.10:8989'
        self.assertEqual(route([[endpoint]]), endpoint.decode())
        query = list(monitor.fields(self.requests[1]))[1][1]
        fields = list(monitor.fields(query))
        self.assertEqual(fields[:2], [(0x04, domain.encode()), (0x0a, bytes([1]))])
        self.assertEqual(fields[-2:], [(0x87, b'connected-to'), (0x30, wrap(0x04, b'connected-to'))])
        for entries, code in [([], 0), ([[endpoint], [endpoint]], 0), ([[endpoint, endpoint]], 0),
                              ([[b'']], 0), ([[endpoint]], 3)]:
            with self.subTest(entries=entries, code=code), self.assertRaises(monitor.LdapError):
                route(entries, code)
    def test_rejects_bind_failure(self):
        with self.assertRaises(monitor.LdapError):
            self.exchange([msg(1, 0x61, ldap_result(49))])
opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/ReplSessionSecurity.java
@@ -267,7 +267,7 @@
   *          The connected socket.
   * @param soTimeout
   *          The socket timeout option to use for the protocol session.
   * @return The new protocol session.
   * @return The new protocol session, or {@code null} if TLS negotiation raised an {@link SSLException}.
   * @throws ConfigException
   *           If the protocol session could not be established due to a
   *           configuration problem.
@@ -278,6 +278,28 @@
  public Session createServerSession(final Socket socket,
      final int soTimeout) throws ConfigException, IOException
  {
    try
    {
      return createServerSessionOrThrow(socket, soTimeout);
    }
    catch (SSLException e)
    {
      // The TLS failure was logged before the socket was closed.
      return null;
    }
  }
  /**
   * Creates a server session and propagates TLS failures to the caller.
   *
   * @param socket the connected socket
   * @param soTimeout the socket read timeout in milliseconds
   * @return the new protocol session
   * @throws ConfigException if the session configuration is invalid
   * @throws IOException if the session cannot be established, including an {@link SSLException} from TLS negotiation
   */
  public Session createServerSessionOrThrow(final Socket socket, final int soTimeout) throws ConfigException, IOException
  {
    boolean hasCompleted = false;
    SSLSocket secureSocket = null;
@@ -307,8 +329,9 @@
      // Force TLS negotiation now.
      secureSocket.startHandshake();
      final Session session = new Session(socket, secureSocket);
      hasCompleted = true;
      return new Session(socket, secureSocket);
      return session;
    }
    catch (final SSLException e)
    {
@@ -316,7 +339,7 @@
      // also how a certificate misconfiguration shows up, so warn the
      // administrator instead of failing silently.
      logHandshakeFailure(socket, e);
      return null;
      throw e;
    }
    finally
    {
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);
        domainMap.put(serverId, newDB);
        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);
    for (int serverId : getDomainMap(baseDN).keySet())
    final DomainDBCursor cursor = new DomainDBCursor(baseDN, this, options);
    final List<DomainDBCursor> cursors = domainCursors(baseDN);
    synchronized (cursors)
    {
      // 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);
      for (int serverId : getDomainMap(baseDN).keySet())
      {
        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/plugin/ReplicationBrokerStopTest.java
@@ -18,6 +18,7 @@
import static java.util.concurrent.TimeUnit.*;
import static org.forgerock.opendj.ldap.ModificationType.*;
import static org.opends.messages.ReplicationMessages.WARN_HEARTBEAT_FAILURE;
import static org.opends.messages.ReplicationMessages.WARN_REPLICATION_SERVER_BADLY_DISCONNECTED;
import static org.opends.messages.ReplicationMessages.WARN_TIMEOUT_CONNECTING_TO_RS;
import static org.opends.server.TestCaseUtils.*;
@@ -51,6 +52,7 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.ResultCode;
@@ -141,10 +143,7 @@
  private static final int LARGE_MESSAGE_SIZE = 256 * 1024;
  /** How many of those messages a case writes at most before it reports that no write blocks. */
  private static final int MAX_LARGE_MESSAGES = 400;
  /**
   * The heartbeat interval of the case of a replication server which is gone: long enough for its
   * writes to fill the socket buffers before the heartbeat monitor gives up on the session.
   */
  /** Heartbeat interval negotiated by the domain in the lost-server test. */
  private static final long HEARTBEAT_INTERVAL_MS = 4000;
  /** A value which makes a change of the description one of those messages. */
  private static final String LARGE_VALUE = "x".repeat(LARGE_MESSAGE_SIZE);
@@ -724,7 +723,7 @@
      final LDAPReplicationDomain domain = startDomain(rs);
      TestCaseUtils.ERROR_TEXT_WRITER.clear();
      rs.stopReading();
      writer = startLargeChanges(keepWriting, changes, failed);
      writer = startLargeChanges(keepWriting::get, changes, failed);
      waitForAWriteToBlock(writer, changes);
      keepWriting.set(false);
@@ -1059,34 +1058,43 @@
  {
    TestCaseUtils.initializeTestBackend(true);
    final WithholdingReplicationServer rs = new WithholdingReplicationServer(LARGE_WINDOW);
    final AtomicBoolean keepWriting = new AtomicBoolean(true);
    final AtomicInteger changes = new AtomicInteger();
    final AtomicReference<ResultCode> failed = new AtomicReference<>();
    Thread writer = null;
    try
    {
      final LDAPReplicationDomain domain = startDomain(rs, HEARTBEAT_INTERVAL_MS);
      final ReplicationBroker broker = brokerOf(domain);
      final Session original = broker.getSession();
      // Give the replication server a CSN from which it can request recovery on reconnect.
      assertEquals(replaceDescription("before the heartbeat timeout"), ResultCode.SUCCESS);
      rs.waitForUpdates(1);
      TestCaseUtils.ERROR_TEXT_WRITER.clear();
      rs.goAway();
      final long away = System.nanoTime();
      writer = startLargeChanges(keepWriting, changes, failed);
      rs.stopReading();
      // A stalled write may still fit in the TCP buffers later. Keep writing until this session closes.
      writer = startLargeChanges(() -> !original.closeInitiated(), changes, failed);
      waitForAWriteToBlock(writer, changes);
      keepWriting.set(false);
      final long blocked = System.nanoTime();
      // The monitor gives up two or three intervals after the last heartbeat.
      rs.giveCredit(LARGE_WINDOW);
      newTimer().repeatUntilSuccess(() -> assertTrue(broker.getCurrentSendWindow() > LARGE_WINDOW,
          "the directory server did not receive the credit on the original session"));
      rs.goAway();
      writer.join(4 * HEARTBEAT_INTERVAL_MS + 10000);
      final long released = System.nanoTime();
      assertFalse(writer.isAlive(), "the write still blocks once the heartbeats of the replication server stopped");
      assertTrue(NANOSECONDS.toMillis(released - away) >= 2 * HEARTBEAT_INTERVAL_MS, "the write of change "
          + changes.get() + ", blocked " + NANOSECONDS.toMillis(blocked - away) + " ms after the replication server went away, ended "
          + NANOSECONDS.toMillis(released - away) + " ms after it: before the heartbeat monitor could give the session up");
      assertTrue(original.closeInitiated(), "the writer exhausted its changes while the original session was open");
      assertNull(failed.get(), "a local change failed");
      final String timeout = WARN_HEARTBEAT_FAILURE.get(DS_ID, rs.serverId,
          original.getReadableRemoteAddress(), baseDN.toString()).toString();
      newTimer().repeatUntilSuccess(() -> assertTrue(TestCaseUtils.ERROR_TEXT_WRITER.getMessages().stream()
          .anyMatch(record -> record.contains(timeout)), "missing heartbeat timeout: " + timeout));
      rs.resumeReading();
      waitForConnection(domain);
      // Discard any bytes queued on the old socket. Only the reconnected session can deliver the change.
      final CSN last = domain.getServerState().getCSN(DS_ID);
      assertNotNull(last, "the domain has no change of its own in its state");
      assertFalse(rs.receivedUpdateCSNs().contains(last), "the old session already delivered the blocked change");
      rs.dropTheSession();
      rs.resumeReading();
      waitForConnection(domain);
      newTimer().repeatUntilSuccess(() -> assertTrue(rs.receivedUpdateCSNs().contains(last),
          "the change cut short, " + last + ", did not reach the replication server: it has "
          + rs.receivedUpdateCSNs()));
@@ -1437,11 +1445,7 @@
      final CSN beforeFailover = former.receivedUpdateCSNs().get(1);
      survivor.differentGroup = false;
      former.beforeStartReply = () -> {
        // The accepted socket can answer discovery after the listener stops accepting connections.
        former.listenSocket.close();
        return null;
      };
      former.closeListenerAfterNextAccept = true;
      survivor.delayedFailoverHandshake = handshake;
      former.closeTheSession();
@@ -1493,10 +1497,7 @@
      former.waitForUpdates(1);
      responder.differentGroup = false;
      former.beforeStartReply = () -> {
        former.listenSocket.close();
        return null;
      };
      former.closeListenerAfterNextAccept = true;
      responder.delayedFailoverHandshake = handshake;
      handshake.sendNextReply.countDown();
      former.closeTheSession();
@@ -1546,10 +1547,7 @@
      responder.differentGroup = false;
      responder.delayedFailoverHandshake = handshake;
      former.beforeStartReply = () -> {
        former.listenSocket.close();
        return null;
      };
      former.closeListenerAfterNextAccept = true;
      former.dropTheSession();
      await(handshake.nextStartReceived);
@@ -2198,6 +2196,8 @@
      final LDAPReplicationDomain domain = startDomain(oldRS, 100000, nextRS.getAddress());
      assertEquals(domain.getRsServerId(), oldRS.serverId);
      nextRS.differentGroup = false;
      // Allow TLS to finish before exercising the broker's shorter start-reply timeout.
      nextRS.tlsHandshakeTimeoutMS = 8_000;
      nextRS.delayedFailoverHandshake = handshake;
      if (formerRs == FormerRsDuringFailover.OFFLINE)
      {
@@ -2267,6 +2267,15 @@
        nextRS.waitForUpdates(1);
      }
    }
    catch (AssertionError e)
    {
      final IOException tlsFailure = nextRS.firstTlsHandshakeFailure.get();
      if (tlsFailure != null)
      {
        e.addSuppressed(tlsFailure);
      }
      throw e;
    }
    finally
    {
      handshake.sendNextReply.countDown();
@@ -2445,11 +2454,11 @@
   * Starts a thread which makes changes of {@link #LARGE_MESSAGE_SIZE} until it is told to stop,
   * counting them, and keeping the first result which is no success.
   */
  private Thread startLargeChanges(final AtomicBoolean keepWriting, final AtomicInteger changes,
  private Thread startLargeChanges(final BooleanSupplier keepWriting, final AtomicInteger changes,
      final AtomicReference<ResultCode> failed)
  {
    return startThread("writer", () -> {
      while (keepWriting.get() && changes.get() < MAX_LARGE_MESSAGES)
      while (keepWriting.getAsBoolean() && changes.get() < MAX_LARGE_MESSAGES)
      {
        final ResultCode result = replaceDescription(changes.get() + LARGE_VALUE);
        if (result != ResultCode.SUCCESS)
@@ -2675,12 +2684,17 @@
    private boolean reading = true;
    /** Whether this server is away: it then sends no heartbeat, and answers no connection either. */
    private volatile boolean away;
    /** Accept the discovery socket, then refuse the session connection. */
    private volatile boolean closeListenerAfterNextAccept;
    private volatile Callable<Void> beforeStartReply;
    private volatile Callable<Void> onFirstWindowProbe;
    /** If set, read from the next session after StartSessionMsg instead of sending its topology. */
    private final AtomicReference<CompletableFuture<ReplicationMsg>> readInsteadOfSendingTopology =
        new AtomicReference<>();
    private volatile DelayedFailoverHandshake delayedFailoverHandshake;
    /** A positive timeout applies only to TLS negotiation on this server. */
    private volatile int tlsHandshakeTimeoutMS;
    private final AtomicReference<IOException> firstTlsHandshakeFailure = new AtomicReference<>();
    WithholdingReplicationServer() throws IOException
    {
@@ -2743,6 +2757,10 @@
        try
        {
          socket = listenSocket.accept();
          if (closeListenerAfterNextAccept)
          {
            listenSocket.close();
          }
        }
        catch (IOException e)
        {
@@ -2763,12 +2781,20 @@
    private void serve(Socket socket)
    {
      Session s = null;
      int tlsTimeoutMS = 0;
      try
      {
        // A server which is away answers no connection: the connection waits for it to come back.
        waitToBeBack();
        s = new ReplSessionSecurity().createServerSession(socket, MultimasterReplication.getConnectionTimeoutMS());
        final int readTimeoutMS = MultimasterReplication.getConnectionTimeoutMS();
        tlsTimeoutMS = tlsHandshakeTimeoutMS;
        s = new ReplSessionSecurity().createServerSessionOrThrow(socket,
            tlsTimeoutMS > 0 ? tlsTimeoutMS : readTimeoutMS);
        sessions.add(s);
        if (tlsTimeoutMS > 0)
        {
          s.setSoTimeout(readTimeoutMS);
        }
        final ServerStartMsg start = (ServerStartMsg) s.receive();
        final Callable<Void> hook = beforeStartReply;
        if (hook != null)
@@ -2849,7 +2875,12 @@
      }
      catch (Exception e)
      {
        // The domain closed the session, or the test closed this server.
        if (s == null && tlsTimeoutMS > 0)
        {
          firstTlsHandshakeFailure.compareAndSet(null, new IOException("TLS handshake on replication server "
              + getAddress() + " with peer " + socket.getRemoteSocketAddress(), e));
        }
        // An established session may end when the domain or the test closes it.
      }
      finally
      {
opendj-server-legacy/src/test/java/org/opends/server/replication/protocol/ReplSessionSecurityTest.java
@@ -16,15 +16,52 @@
package org.opends.server.replication.protocol;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.opends.server.replication.protocol.ReplSessionSecurity.HANDSHAKE_FAILURE_WARN_INTERVAL_NANOS;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.SSLException;
import org.opends.server.DirectoryServerTestCase;
import org.opends.server.TestCaseUtils;
import org.testng.annotations.Test;
/** Tests for {@link ReplSessionSecurity}. */
@SuppressWarnings("javadoc")
public class ReplSessionSecurityTest extends DirectoryServerTestCase
{
  @Test
  public void serverSessionCanPropagateTheTlsFailureToItsCaller() throws Exception
  {
    TestCaseUtils.startServer();
    final ReplSessionSecurity security = new ReplSessionSecurity();
    try (ServerSocket listener = TestCaseUtils.bindFreePort())
    {
      for (boolean propagate : new boolean[] { false, true })
      {
        try (Socket peer = new Socket(InetAddress.getLoopbackAddress(), listener.getLocalPort());
             Socket accepted = listener.accept())
        {
          peer.getOutputStream().write("plain text".getBytes(StandardCharsets.US_ASCII));
          if (propagate)
          {
            assertThatThrownBy(() -> security.createServerSessionOrThrow(accepted, 5000))
                .isInstanceOf(SSLException.class);
          }
          else
          {
            assertThat(security.createServerSession(accepted, 5000)).isNull();
          }
          assertThat(accepted.isClosed()).isTrue();
        }
      }
    }
  }
  /**
   * Any connection which is not a replication peer fails the handshake on the replication
   * port, and a data server which cannot present its certificate reconnects every 500 ms,
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