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

Valery Kharseko
yesterday 52694d4c03f9b09b2e52f389701255f3c78dfd9b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
#
# The contents of this file are subject to the terms of the Common Development and
# Distribution License (the License). You may not use this file except in compliance with the
# License.
#
# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
# specific language governing permission and limitations under the License.
#
# When distributing Covered Software, include this CDDL Header Notice in each file and include
# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
# Header, with the fields enclosed by brackets [] replaced by your own identifying
# information: "Portions copyright [year] [name of copyright owner]".
#
# Copyright 2026 3A Systems, LLC.
 
# Scale down one RS (or one combined node), roll the survivors with the shorter peer list,
# and scale up on its retained or a new volume. A DS's load clients finish before it stops.
case $TOPOLOGY in
  rs534) REMOVED=${RS_ONLY##* }; REMOVED_ROLE=replication ;;
  combined) REMOVED=${DS_NODES##* }; REMOVED_ROLE=combined ;;
  *) echo "scale requires rs534 or combined" >&2; exit 2 ;;
esac
case $SCALE_VOLUME in kept|empty) ;; *) echo "unknown scale volume $SCALE_VOLUME" >&2; exit 2 ;; esac
DISTURBED=$REMOVED
DISTURB_STEPS=1
SURVIVORS=
for node in $ALL_NODES; do [ "$node" = "$REMOVED" ] || SURVIVORS="$SURVIVORS $node"; done
SHORT_PEERS=$(echo "$SURVIVORS" | xargs | tr ' ' ',')
FULL_PEERS=$PEERS
SURVIVING_RS=${RS_NODES%% *}
 
# Freeze the departing RS's positions while waiting for catch-up. Once reached, take a
# fresh sample and verify it before stopping the RS; a stale snapshot must not authorize it.
scale_checkpoint_init() { # <survivor> <departing>
  SCALE_CHECKPOINT_NUMBER=$(( ${SCALE_CHECKPOINT_NUMBER:-0} + 1 ))
  SCALE_CHECKPOINT_DIR="$OUT/scale-checkpoint/$(printf '%03d' "$SCALE_CHECKPOINT_NUMBER")-$1-$2"
  SCALE_CHECKPOINT_ATTEMPT=0
  mkdir -p "$SCALE_CHECKPOINT_DIR"
}
 
# 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>
  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"
}
 
scale_checkpoint_query() { # <node> <output> <error> <role>
  local node=$1 output=$2 errors=$3 role=$4 rc=0 start=$SECONDS remaining=$((ROLLING_END - SECONDS)) now timeout=none
  now=$(date +%s) || return 1
  scale_monitor_search "$node" >"$output" 2>"$errors" || rc=$?
  if [ "$rc" -eq 124 ]; then
    if grep -F 'timeout=query' "$errors" >/dev/null; then timeout=query
    elif grep -F 'timeout=load' "$errors" >/dev/null || [ "$SECONDS" -ge "$ROLLING_END" ]; then timeout=load
    else timeout=unknown
    fi
  fi
  printf 'attempt=%s role=%s node=%s started=%s elapsed=%s remaining-start=%s remaining-end=%s exit=%s timeout=%s\n' \
    "$SCALE_CHECKPOINT_ATTEMPT" "$role" "$node" "$now" "$((SECONDS - start))" "$remaining" "$((ROLLING_END - SECONDS))" "$rc" "$timeout" \
    >>"$SCALE_CHECKPOINT_DIR/history.txt" || return 1
  return "$rc"
}
 
scale_caught_up() { # <survivor RS> <departing RS>
  local survivor=$1 departing=$2 dir="$SCALE_CHECKPOINT_DIR" prefix rc reference reference_new=0
  SCALE_CHECKPOINT_ATTEMPT=$((SCALE_CHECKPOINT_ATTEMPT + 1))
  prefix="$dir/attempt-$(printf '%04d' "$SCALE_CHECKPOINT_ATTEMPT")"
  reference="$dir/reference.ldif"
  if [ ! -f "$reference" ]; then
    reference="$prefix.reference.ldif"
    if scale_checkpoint_query "$departing" "$reference" "$prefix.reference.err" reference; then
      reference_new=1
    else
      rc=$?; printf 'checkpoint query of %s failed (exit %s)\n' "$departing" "$rc" >"$OUT/scale-checkpoint/check.txt"; return 1
    fi
  fi
  if scale_checkpoint_query "$survivor" "$prefix.observer.ldif" "$prefix.observer.err" observer; then :
  else
    rc=$?; printf 'checkpoint query of %s failed (exit %s)\n' "$survivor" "$rc" >"$OUT/scale-checkpoint/check.txt"; return 1
  fi
  rc=0
  python3 -I "$HERE/changelog-checkpoint.py" "$BASE_DN" "$OUT/server-ids.txt" \
    "$reference" "$prefix.observer.ldif" >"$prefix.compare" 2>&1 || rc=$?
  printf 'attempt=%s comparison-exit=%s\n' "$SCALE_CHECKPOINT_ATTEMPT" "$rc" >>"$dir/history.txt" || return 1
  cp "$prefix.compare" "$OUT/scale-checkpoint/check.txt" || return 1
  # Freeze only a usable reference. A newly added origin may not have a position yet.
  if [ "$reference_new" -eq 1 ] && [ "$rc" -le 1 ]; then
    cp "$reference" "$dir/reference.ldif" || return 1
  fi
  [ "$rc" -eq 0 ] || return "$rc"
  # The first successful comparison already sampled the departing node immediately
  # before the observer. Only a reference retained across retries needs refreshing.
  [ "$reference_new" -eq 0 ] || return 0
  # A writer may have advanced while the frozen reference was catching up. Re-sample
  # the departing node, then the survivor, before accepting this checkpoint.
  if scale_checkpoint_query "$departing" "$prefix.fresh-reference.ldif" "$prefix.fresh-reference.err" fresh-reference; then :
  else
    rc=$?; printf 'checkpoint query of %s failed (exit %s)\n' "$departing" "$rc" >"$OUT/scale-checkpoint/check.txt"; return 1
  fi
  if scale_checkpoint_query "$survivor" "$prefix.fresh-observer.ldif" "$prefix.fresh-observer.err" fresh-observer; then :
  else
    rc=$?; printf 'checkpoint query of %s failed (exit %s)\n' "$survivor" "$rc" >"$OUT/scale-checkpoint/check.txt"; return 1
  fi
  rc=0
  python3 -I "$HERE/changelog-checkpoint.py" "$BASE_DN" "$OUT/server-ids.txt" \
    "$prefix.fresh-reference.ldif" "$prefix.fresh-observer.ldif" >"$prefix.fresh-compare" 2>&1 || rc=$?
  printf 'attempt=%s fresh-comparison-exit=%s\n' "$SCALE_CHECKPOINT_ATTEMPT" "$rc" >>"$dir/history.txt" || return 1
  cp "$prefix.fresh-compare" "$OUT/scale-checkpoint/check.txt" || return 1
  [ "$rc" -gt 1 ] || cp "$prefix.fresh-reference.ldif" "$dir/reference.ldif" || return 1
  return "$rc"
}
 
scale_checkpoint_wait() { # <description> <survivor> <departing>
  local what=$1 survivor=$2 departing=$3
  scale_checkpoint_init "$survivor" "$departing" || return 1
  scale_wait "$what" scale_caught_up "$survivor" "$departing"
}
 
# A dedicated LDAP client applies 50,001 distinct modifications after the stop. The tool
# exits at the first failed operation, so a zero exit proves the whole generated stream was
# acknowledged. A fresh RS may adopt the generation ID immediately: the backlog alone does
# not establish the mismatched-generation condition of #1080.
backlog_ldif() { # <uid> <base DN> <first> <last>
  awk -v uid="$1" -v base="$2" -v first="$3" -v last="$4" 'BEGIN {
    for (i = first; i <= last; i++) {
      printf "dn: uid=%s,ou=People,%s\nchangetype: modify\nreplace: description\ndescription: scale-%d\n-\n\n", uid, base, i
    }
  }'
}
 
scale_fence() { # <surviving RS>
  local node=$1 dir="$OUT/scale-checkpoint" history prefix started start=$SECONDS query_rc=0 compare_rc=not-run line file
  SCALE_FENCE_ATTEMPT=$(( ${SCALE_FENCE_ATTEMPT:-0} + 1 ))
  history="$dir/fence-$node/history.txt"
  mkdir -p "$dir/fence-$node" || return 1
  prefix="$dir/fence-$node/attempt-$(printf '%04d' "$SCALE_FENCE_ATTEMPT")"
  started=$(date +%s) || return 1
  printf 'attempt=%s phase=start started=%s remaining=%s\n' "$SCALE_FENCE_ATTEMPT" "$started" "$((ROLLING_END - SECONDS))" >>"$history" || return 1
  scale_monitor_search "$node" >"$prefix.ldif" 2>"$prefix.query.txt" || query_rc=$?
  if [ "$query_rc" -eq 0 ]; then
    compare_rc=0
    python3 -I "$HERE/scale-fence.py" "$BASE_DN" "$dir/writer.ldif" "$prefix.ldif" >"$prefix.compare.txt" 2>&1 || compare_rc=$?
    cp "$prefix.ldif" "$dir/fence-$node.ldif" || return 1
    cp "$prefix.compare.txt" "$dir/fence-$node.txt" || return 1
  else
    cp "$prefix.query.txt" "$dir/fence-$node.txt" || return 1
  fi
  printf 'attempt=%s phase=end elapsed=%s remaining=%s query_exit=%s compare_exit=%s\n' \
    "$SCALE_FENCE_ATTEMPT" "$((SECONDS - start))" "$((ROLLING_END - SECONDS))" "$query_rc" "$compare_rc" >>"$history" || return 1
  for file in "$prefix.query.txt" "$prefix.compare.txt"; do
    [ -f "$file" ] || continue
    while IFS= read -r line || [ -n "$line" ]; do
      printf 'attempt=%s detail=%s\n' "$SCALE_FENCE_ATTEMPT" "$line" >>"$history" || return 1
    done <"$file"
  done
  [ "$query_rc" -eq 0 ] && [ "$compare_rc" = 0 ]
}
 
# Copying an online changelog can catch a partially written block: a failed parse or an
# incomplete interval is retried until the load deadline, never accepted as a complete fill.
scale_coverage() { # <surviving RS>
  local node=$1 dir="$OUT/scale-checkpoint"
  docker cp "$node:/opt/opendj/data/changelogDb" - \
    | python3 -I "$HERE/scale-deadline.py" "$ROLLING_END_MS" python3 -I "$HERE/scale-coverage.py" \
      "$BASE_DN" "$dir/first.ldif" "$dir/writer.ldif" >"$dir/coverage-$node.txt" 2>&1
}
 
run_fill() { # <writer> <uid> <first> <last> <log>
  local writer=$1 uid=$2 first=$3 last=$4 log=$5 remaining=$((ROLLING_END - SECONDS))
  [ "$remaining" -gt 0 ] || return 1
  printf 'load-scale-fill\n' >"$OUT/load/fill.active" || return 1
  [ ! -e "$OUT/load/deadline" ] || return 1
  # The container checks the absolute deadline after Docker has created it; a late
  # launch exits before writing. GNU timeout reaches the Java child as well.
  if ! backlog_ldif "$uid" "$BASE_DN" "$first" "$last" \
    | docker run --rm -i --name load-scale-fill --network "$NETWORK" \
        -e OPENDJ_JAVA_ARGS="$CLIENT_JAVA_ARGS" --entrypoint /bin/sh "$IMAGE" -c '
          deadline=$1; writer=$2; password=$3
          left=$((deadline - $(date +%s)))
          [ "$left" -gt 0 ] || exit 1
          exec /usr/bin/timeout "$left" /opt/opendj/bin/ldapmodify --noPropertiesFile \
            --hostname "$writer" --port 1636 --bindDN "cn=Directory Manager" \
            --bindPassword "$password" --useSsl --trustAll
        ' sh "$((ROLLING_END_MS / 1000))" "$writer" "$ROOT_PASSWORD" \
        >"$log" 2>&1; then
    rolling_kill_active fill || true
    return 1
  fi
  [ ! -e "$OUT/load/deadline" ] || return 1
  rm "$OUT/load/fill.active" || return 1
}
 
scale_backlog() {
  local writer=${DS_NODES%% *} uid="scale-backlog-$REMOVED" count=50001 node
  [ "$writer" != "$REMOVED" ] || { fail 'no writer for the backlog'; return 1; }
  scale_wait 'backlog entry is created' scale_probe "$writer" "$REMOVED" backlog || return 1
  run_fill "$writer" "$uid" 1 1 "$OUT/scale-checkpoint/fill-first.log" || return 1
  # Save the first modification's own CSN before the remaining values replace it.
  ldaps_search "$writer" "uid=$uid,ou=People,$BASE_DN" base '(objectClass=*)' description ds-sync-hist \
    >"$OUT/scale-checkpoint/first.ldif" || return 1
  run_fill "$writer" "$uid" 2 "$count" "$OUT/scale-checkpoint/fill.log" || return 1
  # A successful response may still sit behind an earlier pending local change. The
  # final value's history carries its own CSN, unlike the DS's potentially stale state.
  ldaps_search "$writer" "uid=$uid,ou=People,$BASE_DN" base '(objectClass=*)' description ds-sync-hist \
    >"$OUT/scale-checkpoint/writer.ldif" || return 1
  for node in $RS_NODES; do
    [ "$node" != "$REMOVED" ] || continue
    SCALE_FENCE_ATTEMPT=0
    scale_wait_fence "$node reaches the final fill CSN" scale_fence "$node" || return 1
    scale_wait "$node holds the complete fill" scale_coverage "$node" || return 1
  done
  printf '%s changes while the server was absent\n' "$count" >"$OUT/scale-checkpoint/backlog.txt"
}
 
is_directory_node() { case " $DS_NODES " in *" $1 "*) return 0 ;; *) return 1 ;; esac; }
# Record successful and failed waits, including short ones, for the CI time budget.
scale_timed_wait() { # <seconds> <what> <predicate> [<argument>...]
  local start=$SECONDS what=$2 rc=0
  wait_until "$@" || rc=$?
  printf '%s\t%s\t%s\n' "$((SECONDS - start))" "$rc" "$what" >>"$OUT/scale-timings.tsv" || return 1
  return "$rc"
}
 
scale_wait() { # <what> <predicate> [<argument>...]
  local remaining=$((ROLLING_END - SECONDS))
  [ "$remaining" -gt 0 ] || { fail "scale change exceeded the load"; return 1; }
  [ "$remaining" -le "$DISTURB_TIMEOUT" ] || remaining=$DISTURB_TIMEOUT
  scale_timed_wait "$remaining" "$@" || return 1
  [ "$SECONDS" -lt "$ROLLING_END" ] || { fail "scale change exceeded the load"; return 1; }
}
 
# Fence catch-up may use all remaining load time; other individual waits stay bounded.
scale_wait_fence() { # <what> <predicate> [<argument>...]
  local remaining=$((ROLLING_END - SECONDS))
  [ "$remaining" -gt 0 ] || { fail "scale change exceeded the load"; return 1; }
  scale_timed_wait "$remaining" "$@" || return 1
  [ "$SECONDS" -lt "$ROLLING_END" ] || { fail "scale change exceeded the load"; return 1; }
}
 
# A successful, unique LDAP add while a node is down proves a write really happened in
# that interval; the final offline comparison proves it reached every replica.
scale_probe() { # <writer DS> <rolling node> <down|up>
  scale_probe_batch "$1" "$3" "$2"
}
 
# One LDAP session confirms a distinct write for each node while the whole group is down.
scale_probe_batch() { # <writer DS> <down|up> <rolling node>...
  local writer=$1 direction=$2 node uid name
  shift 2
  [ "$#" -gt 0 ] || return 1
  name=$1
  [ "$#" -eq 1 ] || name="batch-$name"
  {
    for node in "$@"; do
      uid="scale-$direction-$node"
      printf 'dn: uid=%s,ou=People,%s\nobjectClass: top\nobjectClass: person\nobjectClass: organizationalPerson\nobjectClass: inetOrgPerson\nuid: %s\ncn: Scale Probe\nsn: ScaleProbe\n\n' \
        "$uid" "$BASE_DN" "$uid"
    done
  } | docker exec -i "$writer" /bin/sh -c '
        deadline=$1; password=$2
        left=$((deadline - $(date +%s)))
        [ "$left" -gt 0 ] || exit 1
        exec /usr/bin/timeout "$left" /opt/opendj/bin/ldapmodify --noPropertiesFile --hostname localhost --port 1636 \
          --bindDN "cn=Directory Manager" --bindPassword "$password" --useSsl --trustAll --defaultAdd
      ' sh "$((ROLLING_END_MS / 1000))" "$ROOT_PASSWORD" >"$OUT/scale-progress/$direction-$name.txt" 2>&1
}
 
# 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.
# 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_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.
    [ "$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
}
 
scale_release_writers() {
  local node failed=
  for node in ${SCALE_HELD_WRITERS:-}; do rolling_resume "$node" || failed=1; done
  SCALE_HELD_WRITERS=
  [ -z "$failed" ]
}
 
# 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>
  mkdir -p "$OUT/bootstrap" || return 0
  docker logs --timestamps "$1" >"$OUT/bootstrap/$2-$1.log" 2>&1 || :
}
 
# Save the stopped RS before its container or volume is replaced, so an eventual
# gap can be compared with its pre-restart changelog in the uploaded artifact.
scale_capture_changelog() { # <node> <generation>
  local node=$1 generation=$2 start=$SECONDS
  local snapshot="$OUT/scale-checkpoint/$generation-$node-changelog.tar"
  docker cp "$node:/opt/opendj/data/changelogDb" - >"$snapshot.partial" || {
    fail "cannot save the $generation changelog of $node"; return 1;
  }
  mv "$snapshot.partial" "$snapshot" || return 1
  printf '%s\t0\t%s\n' "$((SECONDS - start))" "save $generation changelog of $node" >>"$OUT/scale-timings.tsv" || return 1
}
 
collect_scale_bootstrap() {
  local node
  for node in $ALL_NODES; do scale_capture_bootstrap "$node" final; done
}
 
# FileReplicaDB keeps only the newest ReplicaOfflineMsg per replica. Save these
# small state files between transitions, before a later stop overwrites them.
scale_capture_offline_states() { # <phase> <RS>...
  local phase=$1 node target captured
  shift
  for node in "$@"; do
    target="$OUT/scale-checkpoint/offline-$phase-$node.txt"
    captured=$(date +%s) || return 1
    printf 'capture-start-ms %s000\n' "$captured" >"$target.partial" || return 1
    docker exec "$node" sh -c '
      set -e
      cd /opt/opendj/data/changelogDb
      echo domains.state
      cat domains.state
      for file in *.dom/*.server/offline.state; do
        [ -f "$file" ] || continue
        printf "%s " "$file"
        cat "$file"
        echo
      done
    ' >>"$target.partial" || { fail "could not save offline states of $node after $phase"; return 1; }
    mv "$target.partial" "$target" || return 1
  done
}
 
scale_roll() { # <node> <peer list>
  local node=$1 peers=$2 role=directory from observer= writer= candidate direction=up
  [ "$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
  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
  mkdir -p "$OUT/scale-progress" || return 1
  scale_wait "another replica writes while $node is stopped" scale_probe "$writer" "$node" "$direction" || return 1
  scale_capture_bootstrap "$node" "$direction"
  docker rm "$node" >/dev/null || return 1
  PEERS="$peers" start_server "$node" "$role" || return 1
  scale_wait "$node serves again" started_since "$node" "$from" || return 1
  scale_wait "the join of $node ends" bootstrap_ended "$node" || return 1
  if is_directory_node "$node"; then rolling_resume "$node" || return 1; fi
}
 
# Launch every stop before waiting: slow graceful shutdowns share the same window.
# Wait for all jobs even after a failure so none survives a failed transition.
scale_stop_group() { # <node>...
  local node pid failed=
  local -a pids=()
  for node in "$@"; do
    ( trap - ERR; docker stop -t 120 "$node" >/dev/null ) &
    pids+=("$!")
  done
  for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
  [ -z "$failed" ]
}
 
# Accept a startup timeout only after the same DS/domain connected to an eligible
# RS before the successful bootstrap was observed in this rolling window. The retry
# may finish after CORE135; only timeouts before that startup marker are candidates.
# Admin/schema domains have their own DS IDs; another live RS may win the retry.
# Keep the full error as evidence so another record cannot inherit the allowance.
scale_record_reconnected_timeouts() { # <DS> <rolling RS> <direction>
  local node=$1 direction=$3 window="$OUT/logs/$1.window-$3-$1"
  local before after mark candidate address addresses= target="$OUT/scale-progress/timeouts-$3-$1.txt"
  [ -f "$window" ] && [ -f "$OUT/logs/$node.mark" ] || return 0
  bootstrap_ended "$node" || return 0
  read -r before _ <"$window" || return 0
  mark=$(cat "$OUT/logs/$node.mark") || return 0
  after=$(errors_lines "$node") || return 0
  for candidate in $RS_NODES; do
    [ "$direction" = up ] || [ "$candidate" != "$REMOVED" ] || continue
    address=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$candidate") || return 0
    case $address in ''|*[!0-9.]*) return 0 ;; esac
    addresses="$addresses $candidate=$address"
  done
  mkdir -p "$OUT/scale-progress" || return 1
  if ! since_mark "$node" | awk -v first="$((mark + 1))" -v before="$before" -v after="$after" \
      -v addresses="$addresses" -v node="$node" -v domain_base="$BASE_DN" -v evidence="$target.evidence" '
    BEGIN {
      printf "" > evidence
      count = split(addresses, peers, " ")
      for (i = 1; i <= count; i++) {
        split(peers[i], pair, "=")
        address[pair[1]] = pair[2]
      }
    }
    {
      line = first + NR - 1
      if (line <= before || line > after) next
      if (index($0, "category=CORE severity=NOTICE msgID=135 msg=The Directory Server has started successfully")) {
        startups++
        next
      }
      message = substr($0, index($0, " msg=") + 5)
      id = message; sub(/^Directory server DS\(/, "", id); sub(/\).*/, "", id)
      if (id !~ /^[0-9]+$/) next
      domain = message; sub(/^.* for domain "/, "", domain); sub(/".*/, "", domain)
      if (domain != domain_base && domain != "cn=admin data" && domain != "cn=schema") next
      if (!startups && index($0, "category=SYNC severity=ERROR msgID=212 ")) {
        for (rs in address) {
          if (message == "Directory server DS(" id ") timed out while connecting to replication server " rs ":8989 for domain \"" domain "\"") {
            key[++n] = id SUBSEP domain; position[n] = line; record[n] = $0
          }
        }
      }
      if (index($0, "category=SYNC severity=NOTICE msgID=62 ") \
          && index(message, "Directory server DS(" id ") has connected to replication server RS(") == 1) {
        for (rs in address) {
          if (index(message, " for domain \"" domain "\" at " address[rs] ":8989 ")) {
            for (i = 1; i <= n; i++) if (key[i] == id SUBSEP domain) confirmed[i] = 1
          }
        }
      }
    }
    END {
      # Another startup in this interval cannot prove recovery of the first one.
      if (startups == 1) for (i = 1; i <= n; i++) if (confirmed[i]) {
        print position[i] - 1, position[i], "startup-timeout:" node
        printf "%d\t%s\n", position[i], record[i] > evidence
      }
    }' >"$target"; then
    rm -f "$target" "$target.evidence"
    return 0
  fi
  cat "$target.evidence" >>"$OUT/logs/$node.startup-timeouts" || return 1
  cat "$target" >>"$OUT/logs/$node.windows"
}
 
# A surviving DS can reconnect after its startup, when another group stops its RS.
# Accept only the stopped RS address and a subsequent successful connection to the
# surviving RS, in this RS's exact rolling window and the same DS/domain.
# The returned RS is also a candidate during scale-out, after its join completed.
scale_record_roll_failover() { # <DS> <stopped RS> <observer RS> <direction> <old RS address>
  local node=$1 stopped=$2 observer=$3 direction=$4 old_address=$5
  local before after mark id address candidate addresses= target="$OUT/scale-progress/failover-$4-$2-$1.txt"
  local window="$OUT/logs/$1.window-$4-$2"
  [ -f "$window" ] && [ -f "$OUT/logs/$node.mark" ] || return 0
  case $old_address in ''|*[!0-9.]*) return 0 ;; esac
  read -r before _ <"$window" || return 0
  mark=$(cat "$OUT/logs/$node.mark") || return 0
  after=$(errors_lines "$node") || return 0
  id=$(awk -v n="$node" '$2 == n { print $1 }' "$OUT/server-ids.txt") || return 0
  case $id in ''|*[!0-9]*) return 0 ;; esac
  for candidate in $RS_NODES; do
    [ "$candidate" != "$stopped" ] || continue
    [ "$direction" = up ] || [ "$candidate" != "$REMOVED" ] || continue
    address=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$candidate") || return 0
    case $address in ''|*[!0-9.]*) return 0 ;; esac
    addresses="$addresses $candidate=$address"
  done
  mkdir -p "$OUT/scale-progress" || return 1
  if ! since_mark "$node" | awk -v first="$((mark + 1))" -v before="$before" -v after="$after" \
      -v id="$id" -v old="$old_address" -v addresses="$addresses" -v node="$node" -v domain="$BASE_DN" '
    BEGIN {
      count = split(addresses, peers, " ")
      for (i = 1; i <= count; i++) {
        split(peers[i], pair, "=")
        address[pair[1]] = pair[2]
      }
    }
    {
      line = first + NR - 1
      if (line <= before || line > after) next
      if (index($0, "category=SYNC severity=ERROR msgID=180 msg=Directory server DS(" id ") encountered an error while receiving changes for domain \"" domain "\" from replication server RS(") \
          && index($0, ") at " old ":8989. The connection will be closed,")) disconnected = line
      for (rs in address) {
        if (disconnected && index($0, "category=SYNC severity=ERROR msgID=212 msg=Directory server DS(" id ") timed out while connecting to replication server " rs ":8989 for domain \"" domain "\"")) {
          pending[++n] = line; timeoutPeer[n] = rs
        }
        if (disconnected && index($0, "category=SYNC severity=NOTICE msgID=62 msg=Directory server DS(" id ") has connected to replication server RS(") \
            && index($0, " for domain \"" domain "\" at " address[rs] ":8989 ")) {
          print disconnected - 1, disconnected, "disconnect:" node ":" old
          for (i = 1; i <= n; i++)
            if (timeoutPeer[i] == rs) print pending[i] - 1, pending[i], "timeout:" node ":" rs
          disconnected = n = 0
        }
      }
    }' >"$target"; then
    rm -f "$target"
    return 0
  fi
  cat "$target" >>"$OUT/logs/$node.windows"
}
 
# In the separate topology, roll two directory servers together with one RS. The
# other RS and a directory writer remain available; its checkpoint must cover the RS
# before stopping, and a single LDAP batch confirms one write per stopped node.
scale_roll_pair() { # <directory node> <directory node> <peer list> <RS>
  local first=$1 second=$2 peers=$3 rolling_rs=$4 direction=up node candidate writer= observer= from old_address
  [ "$TOPOLOGY" = rs534 ] || return 1
  [ "$peers" != "$SHORT_PEERS" ] || direction=down
  for candidate in $DS_NODES; do
    [ "$candidate" != "$REMOVED" ] && [ "$candidate" != "$first" ] && [ "$candidate" != "$second" ] || continue
    writer=$candidate; break
  done
  for candidate in $RS_NODES; do
    [ "$candidate" != "$REMOVED" ] && [ "$candidate" != "$rolling_rs" ] || continue
    observer=$candidate; break
  done
  [ -n "$writer" ] && [ -n "$observer" ] || { fail 'rolling group has no surviving writer or replication server'; return 1; }
  for node in "$first" "$second"; do rolling_request_pause "$node" || return 1; done
  for node in "$first" "$second"; do rolling_pause "$node" || return 1; done
  for node in "$first" "$second"; do window_open_key "$direction-$node" "dns:$REMOVED" || return 1; done
  window_open_key "$direction-$rolling_rs" "dns:$REMOVED" "dns:$rolling_rs" || return 1
  # Capture the checkpoint after opening all windows, immediately before the stops.
  scale_checkpoint_wait "$observer reaches a checkpoint of $rolling_rs" "$observer" "$rolling_rs" || return 1
  old_address=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$rolling_rs") || return 1
  from=$(date +%s) || return 1
  scale_stop_group "$first" "$second" "$rolling_rs" || return 1
  if [ "$SCALE_VOLUME" = empty ] && [ "$direction" = down ]; then
    scale_capture_changelog "$rolling_rs" down || return 1
  fi
  mkdir -p "$OUT/scale-progress" || return 1
  scale_wait "another replica writes while the group is stopped" scale_probe_batch "$writer" "$direction" "$first" "$second" "$rolling_rs" || return 1
  for node in "$first" "$second" "$rolling_rs"; do scale_capture_bootstrap "$node" "$direction"; done
  for node in "$first" "$second" "$rolling_rs"; do docker rm "$node" >/dev/null || return 1; done
  PEERS="$peers" start_server "$rolling_rs" replication || return 1
  for node in "$first" "$second"; do PEERS="$peers" start_server "$node" directory || return 1; done
  scale_wait "$rolling_rs serves again" started_since "$rolling_rs" "$from" || return 1
  for node in "$first" "$second"; do
    scale_wait "$node serves again" started_since "$node" "$from" || return 1
  done
  # Startup opens LDAP before the background join has finished its administrative
  # JVMs. Keep this group paused until every join succeeds, while the other DSs keep
  # writing. This also completes the group before the next surviving writer rolls.
  scale_wait "the join of $rolling_rs ends" bootstrap_ended "$rolling_rs" || return 1
  for node in "$first" "$second"; do
    scale_wait "the join of $node ends" bootstrap_ended "$node" || return 1
    scale_record_reconnected_timeouts "$node" "$rolling_rs" "$direction" || return 1
  done
  for node in "$first" "$second"; do rolling_resume "$node" || return 1; done
  for node in $DS_NODES; do
    [ "$node" != "$first" ] && [ "$node" != "$second" ] || continue
    scale_record_roll_failover "$node" "$rolling_rs" "$observer" "$direction" "$old_address" || return 1
  done
}
 
# Combined nodes stop one at a time. The separate topology overlaps the roll of
# directory pairs and one RS, never stopping both surviving replication servers.
scale_roll_batch() { # <peer list> <down|up>
  local peers=$1 direction=$2 node index=0 next_rs=0
  local -a directories=() replication=()
  if [ "$TOPOLOGY" = rs534 ]; then
    for node in $SURVIVORS; do
      if is_directory_node "$node"; then directories+=("$node"); else replication+=("$node"); fi
    done
    while [ "$index" -lt "${#directories[@]}" ]; do
      if [ $((index + 1)) -lt "${#directories[@]}" ] && [ "$next_rs" -lt "${#replication[@]}" ]; then
        scale_roll_pair "${directories[$index]}" "${directories[$((index + 1))]}" "$peers" "${replication[$next_rs]}" || return 1
        index=$((index + 2)); next_rs=$((next_rs + 1))
      else
        scale_roll "${directories[$index]}" "$peers" || return 1
        index=$((index + 1))
      fi
    done
    while [ "$next_rs" -lt "${#replication[@]}" ]; do
      scale_roll "${replication[$next_rs]}" "$peers" || return 1
      next_rs=$((next_rs + 1))
    done
  else
    for node in $SURVIVORS; do scale_roll "$node" "$peers" || return 1; done
  fi
  # A handshake begun before any join ended may log its timeout up to eight seconds later.
  sleep 10
  for node in $SURVIVORS; do window_close_key "$direction-$node" || return 1; done
}
 
# Keep the warning window at the return of the rebuilt RS. A DS may only get
# that endpoint back in its peer list during the subsequent scale-out roll.
scale_certificate_log() { # <node>
  local node=$1 bounds before warning_end last mark
  bounds=$(awk '$NF == "scale-cert-return" { print $1, $2; count++ }
    END { if (count != 1) exit 1 }' "$OUT/logs/$node.windows") || return 1
  read -r before warning_end <<<"$bounds" || return 1
  mark=$(cat "$OUT/logs/$node.mark") || return 1
  last=$warning_end
  if [ "$node" != "$REMOVED" ]; then last=$(errors_lines "$node") || return 1; fi
  [ "$mark" -le "$before" ] && [ "$before" -le "$warning_end" ] && [ "$warning_end" -le "$last" ] || return 1
  printf '@ %s %s\n' "$node" "$warning_end" || return 1
  since_mark "$node" | awk -v mark="$mark" -v before="$before" -v last="$last" '
    NR + mark > before && NR + mark <= last && /category=SYNC severity=(WARNING msgID=(105|119|312)|NOTICE msgID=(62|313|341)) / {
      printf "%d\t%s\n", NR + mark, $0
    }
    END { if (NR + mark < last) exit 1 }'
}
 
# Match WARN105 to the failed client's exact socket endpoints inside the return
# window. A later notice in that client's log must show a session for the same
# role, ID and domain on the rebuilt RS. A DS can recover during the roll, while
# an RS must recover within the return window.
scale_record_certificate_recoveries() { # <rebuilt RS address> <node=address>...
  local address=$1 mapping proof="$OUT/logs/scale-certificates"
  shift
  {
    for mapping in "$@"; do scale_certificate_log "${mapping%%=*}" || exit 1; done
    scale_certificate_log "$REMOVED" || exit 1
  } | awk -v rs="$REMOVED" -v address="$address" -v mappings="$*" -v ds_nodes="$DS_NODES" -v rs_nodes="$RS_NODES" '
    BEGIN {
      count = split(mappings, pairs, " ")
      for (i = 1; i <= count; i++) {
        split(pairs[i], pair, "=")
        peer_at[pair[2]] = pair[2] in peer_at ? "" : pair[1]
      }
      count = split(ds_nodes, nodes, " ")
      for (i = 1; i <= count; i++) directory_node[nodes[i]] = 1
      count = split(rs_nodes, nodes, " ")
      for (i = 1; i <= count; i++) replication_node[nodes[i]] = 1
    }
    function numeric_endpoint(endpoint) {
      sub(/^.*\//, "", endpoint)
      return endpoint
    }
    function prove(line, record) {
      printf "%s\t%d\t%s\n", node, line, record
    }
    $1 == "@" {
      node = $2
      warning_end = $3
      for (position in warning) delete warning[position]
      for (position in warning_key) delete warning_key[position]
      next
    }
    {
      line = $1 + 0
      record = substr($0, index($0, "\t") + 1)
      sep = index(record, " msg=")
      if (!sep) next
      header = substr(record, 1, sep - 1)
      message = substr(record, sep + 5)
      if (node == rs) {
        if (header !~ /category=SYNC severity=WARNING msgID=105$/ ||
            message !~ /^Replication server accepted a connection from [^ ]+ to local address [^ ]+ but the SSL handshake failed\./ ||
            message !~ /The error was: (\(bad_certificate\) )?Received fatal alert: bad_certificate$/) next
        split(message, words, " ")
        source = numeric_endpoint(words[7])
        destination = numeric_endpoint(words[11])
        if (split(source, socket, ":") != 2 || socket[2] !~ /^[0-9]+$/ || destination != address ":8989") next
        caller = peer_at[socket[1]]
        tuple = source SUBSEP destination
        if (caller != "" && attempts[caller, tuple] == 1 &&
            recovered_at[caller, attempt_path[caller, tuple]] > attempt_line[caller, tuple]) prove(line, record)
        next
      }
 
      if (!match(message, / for domain "[^"]+"/)) next
      domain = substr(message, RSTART, RLENGTH)
      prefix = substr(message, 1, RSTART - 1)
      suffix = substr(message, RSTART + RLENGTH)
      if (header ~ /category=SYNC severity=NOTICE msgID=341$/ && line <= warning_end &&
          prefix ~ /^Replication TLS client handshake failed for (DS|RS)\([0-9]+\)$/ &&
          suffix ~ /^ from [^ ]+ to [^ ]+$/) {
        client = prefix
        sub(/^Replication TLS client handshake failed for /, "", client)
        role = substr(client, 1, 2)
        if ((role == "DS" && !(node in directory_node)) || (role == "RS" && !(node in replication_node))) next
        split(suffix, words, " ")
        source = numeric_endpoint(words[2])
        destination = numeric_endpoint(words[4])
        if (split(source, socket, ":") != 2 || peer_at[socket[1]] != node || socket[2] !~ /^[0-9]+$/ ||
            destination != address ":8989") next
        tuple = source SUBSEP destination
        attempts[node, tuple]++
        attempt_path[node, tuple] = client SUBSEP domain
        attempt_line[node, tuple] = line
      }
      if (node in directory_node && prefix ~ /^Directory server DS\([0-9]+\) /) {
        client = prefix; sub(/^Directory server /, "", client); sub(/ .*/, "", client)
        key = client SUBSEP domain
        if (line <= warning_end && header ~ /category=SYNC severity=WARNING msgID=119$/ &&
            prefix == "Directory server " client " encountered an unexpected error while connecting to replication server " rs ":8989" &&
            suffix ~ /^: .*SSLHandshakeException.*bad_certificate/) {
          warning_key[line] = key
          warning[line] = record
        }
        if (header ~ /category=SYNC severity=NOTICE msgID=62$/ &&
            prefix ~ /^Directory server DS\([0-9]+\) has connected to replication server RS\([0-9]+\)$/ &&
            index(suffix, " at " address ":8989 with generation ID ") == 1) {
          recovered_at[node, key] = line
          for (position in warning) {
            if (warning_key[position] != key) continue
            prove(position, warning[position])
            delete warning[position]
            delete warning_key[position]
          }
        }
      }
      if (node in replication_node && line <= warning_end && header ~ /category=SYNC severity=NOTICE msgID=313$/ &&
          prefix ~ /^Replication server RS\([0-9]+\) connected to replication server / &&
          suffix == ", which it had reported it had no replication session with") {
        client = prefix; sub(/^Replication server /, "", client); sub(/ .*/, "", client)
        if (prefix == "Replication server " client " connected to replication server " rs ":8989") {
          recovered_at[node, client SUBSEP domain] = line
        }
      }
    }' >"$proof.partial" || return 1
  mv "$proof.partial" "$proof"
}
 
disturb() {
  local node from end address surviving_rs= REJOINED_WITH_NEW_ID=0
  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
  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
  printf '%s\n' "$ABSENCE_START" >"$OUT/scale-checkpoint/absence-start.txt" || return 1
  # Only changes after the stop returned count toward the backlog while it was absent.
  scale_monitor_search "$SURVIVING_RS" >"$OUT/scale-checkpoint/absent-start.ldif" || return 1
  # Save a stopped container's complete errors log for window boundaries while it is absent.
  docker cp "$REMOVED:/opt/opendj/data/logs/errors" "$OUT/logs/$REMOVED.offline-log" || return 1
  wc -l <"$OUT/logs/$REMOVED.offline-log" >"$OUT/logs/$REMOVED.offline" || return 1
  docker logs "$REMOVED" >"$OUT/logs/$REMOVED.previous-container" 2>&1 || return 1
  scale_capture_bootstrap "$REMOVED" removed
  if [ "${CSN_TRACE:-0}" = 1 ] && [ "$TOPOLOGY" = combined ] && [ "$SCALE_VOLUME" = empty ]; then
    capture_csn_trace "$REMOVED" || return 1
  fi
  # The empty-volume case destroys this RS's original changelog. Preserve it so a
  # gap after failover can be traced back to the departing RS or a surviving peer.
  if [ "$TOPOLOGY" = rs534 ] && [ "$SCALE_VOLUME" = empty ]; then
    scale_capture_changelog "$REMOVED" removed || return 1
  fi
  docker rm "$REMOVED" >/dev/null || return 1
  sleep 10
  window_close || return 1
  scale_roll_batch "$SHORT_PEERS" down || return 1
  for node in $RS_NODES; do [ "$node" = "$REMOVED" ] || surviving_rs="$surviving_rs $node"; done
  scale_capture_offline_states down $surviving_rs || return 1
  for node in $SURVIVORS; do scale_wait "$REMOVED leaves $node" peer_removed "$node" "$REMOVED" || return 1; done
  scale_backlog || return 1
  # A join repairs only peers that are registered while it runs. Bring the removed node
  # back before rolling survivors to the longer list, or an early join can finish before
  # it exists and leave it out of that survivor's local lists.
  if [ "$SCALE_VOLUME" = empty ]; then
    for node in $SURVIVORS; do
      address=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$node") || return 1
      case $address in ''|*[!0-9.]*) return 1 ;; esac
      certificate_peers+=("$node=$address")
      return_window+=("cert:$node:$REMOVED")
    done
    return_window+=("scale-cert-return")
  fi
  window_open "${return_window[@]}" || return 1
  if [ "$SCALE_VOLUME" = empty ]; then
    cp "$OUT/logs/$REMOVED.offline-log" "$OUT/logs/$REMOVED.previous" || return 1
    docker volume rm "vol-$REMOVED" >/dev/null || return 1
  fi
  if [ "$TOPOLOGY" = rs534 ] && [ "$SCALE_VOLUME" = empty ]; then
    recovery=(-e REPLICATION_RECOVER_FROM_RS=1)
  fi
  PEERS="$FULL_PEERS" start_server "$REMOVED" "$REMOVED_ROLE" "${recovery[@]}" || return 1
  scale_wait "$REMOVED serves again" started_since "$REMOVED" "$from" || return 1
  rm "$OUT/logs/$REMOVED.offline" || return 1
  scale_wait "the join of $REMOVED ends" bootstrap_ended "$REMOVED" || return 1
  if [ "$TOPOLOGY" = rs534 ] && [ "$SCALE_VOLUME" = empty ]; then
    # Scale-in verified that every DS removed this endpoint. The RS-only join
    # connects the mesh without advertising BASE_DN to those DSs. Catch up before
    # their scale-out bootstraps add it again: only retained, ordered RS history
    # can advance this position. Final offline checks still verify every CSN.
    scale_checkpoint_wait "$REMOVED receives retained RS history before serving writers" "$REMOVED" "$SURVIVING_RS" || return 1
  fi
  scale_capture_offline_states return $RS_NODES || return 1
  sleep 10
  dns_window_close || return 1
  window_close || return 1
  if is_directory_node "$REMOVED"; then
    scale_wait "the replica id of $REMOVED appears" record_rejoined_id "$REMOVED" || return 1
    rolling_resume "$REMOVED" || return 1
    if [ "$SCALE_VOLUME" = empty ] || [ "$REJOINED_WITH_NEW_ID" = 1 ]; then
      # The first roll can pause this worker before its first write with the new ID.
      scale_wait "$REMOVED accepts a write after rejoining" scale_probe "$REMOVED" "$REMOVED" rejoined || return 1
    fi
  fi
  scale_roll_batch "$FULL_PEERS" up || return 1
  scale_capture_offline_states up $RS_NODES || return 1
  for node in $SURVIVORS; do scale_wait "$REMOVED returns to $node" peer_present "$node" "$REMOVED" || return 1; done
  if [ "$SCALE_VOLUME" = empty ]; then
    address=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$REMOVED") || return 1
    case $address in ''|*[!0-9.]*) return 1 ;; esac
    scale_record_certificate_recoveries "$address" "${certificate_peers[@]}" || return 1
  fi
  end=$(date +%s) || return 1
  echo "$((from * 1000)) $((end * 1000)) $REMOVED scale-$SCALE_VOLUME" >>"$OUT/disturbances.txt" || return 1
}
 
settle() {
  local node
  for node in $ALL_NODES; do wait_until "$DISTURB_TIMEOUT" "the join of $node ends" bootstrap_ended "$node" || return 1; done
}