[#1208] Preserve replication history during scaling, recovery and shutdown (#1282)
During replication recovery, later updates can overtake missing history,
a dependency scan can hand one update to two replay threads, and a
closing session can delay failover handshakes on a live replication
server. This PR preserves ordered history and replay ownership, drains
accepted writes during shutdown without blocking unrelated runtime
handshakes, and exercises scale-in/scale-out under concurrent writes.
Docker fixtures require explicit bootstrap success before resuming
rolled writers, retain failure diagnostics and run OpenDJ without the
former 512 MiB Docker cap. When a DS moves back to an RS after a
restart, it now keeps reading from the previous RS until the stop
exchange completes.
Part of #1208; also exercises the empty-RS certificate and failover path
tracked in #1188.
## Scale scenarios and checks
| Topology | Retained volume | Empty volume |
|---|---|---|
| Four directory servers and three replication servers | `rs534 /
scale-rs-kept` | `rs534 / scale-rs-empty` |
| Four combined directory/replication servers | `combined / scale-kept`
| `combined / scale-empty` |
Each scenario removes one server from `REPLICATION_PEERS`, rolls the
survivors with the shorter list, verifies its removal from their
registries and local RS lists, returns it, and rolls the survivors with
the full list. Separate-server transitions roll two DS and one RS
together, leaving another RS and a writer available. Combined nodes roll
individually. A restarted separate-server group must finish the RS and
both DS bootstraps before either writer resumes or the next group rolls;
a combined node must finish its own bootstrap before resuming. Surviving
writers remain active throughout these waits. Before a combined
checkpoint, request pauses for the departing worker and the other
participating writers together. Their active segments can finish
concurrently while the observing replica continues to accept writes. The
checkpoint waits for all requested pauses, and the departing worker
resumes after successful bootstrap. Missing or failed bootstrap, failed
load workers and workload deadlines still abort the scenario.
Checkpoints precede stops, and writes on a surviving DS are verified
while the group is stopped. A returning combined DS must accept a
dedicated LDAP write before the first scale-out roll can pause its
worker if it has an empty volume or its retained-volume bootstrap
assigned a new replica ID. The probe runs after the current ID is
recorded. Changelog checks include both IDs when a rejoin changes the
replica identity. A checkpoint rereads a reference snapshot that lacks
the new origin and waits for the observing RS to reach that origin's
position.
While the removed server is absent, a dedicated client applies 50,001
distinct modifications. Every surviving RS must contain the complete CSN
interval before the server returns. After scale-out and membership
verification, every DS must complete a newly started load segment before
the workload ends. Checks cover indexed LDAP results, matching offline
LDIF exports, index verification, changelog continuity, RS mesh
connectivity and replication errors. The existing `rs534 / empty-rs` row
also tests failover in both directions after rebuilding an RS while a DS
is offline.
Scale load has a 2700-second ceiling and starts the disturbance at 120
seconds. Targets remain 100 modifications and 20 adds/deletes per second
per DS, with error-free clients and a duration-weighted minimum of 10%
of each target. Fifty-second segments rotate through three indexed
surnames per DS. Other rows retain their 900-second load. The scale job
and scenario step retain 75- and 70-minute limits respectively.
Convergence budgets are 900 seconds for `combined / scale-kept`, 600
seconds for `combined / scale-empty`, and 300 seconds for both
separate-server scale rows. Convergence still requires three complete
zero-lag samples spanning more than the 60-second monitor period plus
five seconds.
Host-side checkpoint and membership queries use a lightweight LDAP
reader through loopback-only admin ports, with explicit deadlines and
complete-result checks. Artifacts retain checkpoints, full backlog
coverage, pre-restart changelogs, offline-state snapshots, bootstrap
timings, prior container logs, CSN traces and post-load convergence
samples. Failed workers abort pending waits; failed snapshots or Docker
commands cannot count as successful progress.
## Replication correctness and bootstrap
- **Replay ownership:** stop each ADD/MODIFY/DELETE/MODDN dependency
scan after the first matching predecessor. `getNextUpdate()` already
waits for all earlier pending changes, so repeated parking is
unnecessary and can race with another replay thread taking ownership.
Parking requires the same pending-change object and current replay
owner; a stale scan after a clear/re-delivery or ownership transfer
cannot hand out the CSN again. This prevents the reproduced
double-handoff path ending in error `9` when the original replay
commits.
- **Offline-only sequence gaps:** complete CSN allocation traces can
distinguish an offline notification from a lost update. Classification
requires an offline allocation and no local-operation allocation for the
same domain, server ID and sequence in any recorded process generation,
including outside the load interval. Every expected generation, end
marker, record count and checksum must validate. Failed copies
invalidate eligibility, and the changelog checker validates the traces
again. `offline.state` snapshots alone remain diagnostic; incomplete
traces and sequences reused by local operations cannot excuse a gap.
- **RS shutdown:** stop connected DS handlers, close admission of direct
DS updates, and cross a read/write barrier that also covers readers
already removed from the connection map by concurrent teardown. A fatal
changelog exception releases the DS admission read lock before starting
synchronous shutdown, so that domain can cross the barrier within the
shared budget. Before closing RS writers, wait for accepted updates to
be written to peer sessions, using one 30-second deadline across all
domains and peers. Track selected-but-unwritten records until their
socket-write callbacks complete. Skipping an exact peer receipt cannot
credit an older pending write. Filtered updates retain a per-origin
delivery barrier tied to the local changelog generation: a peer-only
generation change cannot erase missing delivery, while a local reset
retires the old obligation. A delayed discard report from an old
selection cannot create a barrier in the new generation. Expiration is
logged. The existing collocated-DS offline-message shutdown
synchronization remains in place. A two-domain regression holds both
peer send windows closed and checks that the direct-update drain uses
one deadline and logs a warning for each undelivered target.
- **DS reconnect during teardown.** If a DS starts a handshake while the
previous session is closing or its registered handler is shutting down,
keep the ID reserved and reject the handshake until teardown releases
it. A conflict with a live session still logs error `54`.
- **Peer teardown:** unregister the old handler, stop accepting work and
remove its name-based monitors while holding the domain lock. Release
the lock before both `Session.close()` and reader/writer joins: closing
drains queued socket writes and can block on a slow peer, while a reader
applying its final topology message can need the same domain lock.
Neither wait may delay another peer's failover handshake. Reacquire the
lock before generation and topology decisions. Topology messages from
removed or replaced handlers are ignored; replacement monitors cannot be
deleted by late cleanup of the old handler. Receipt cleanup remains
after session closure and joins, and the full-server accepted-write
delivery barrier remains in place. Offline-message dispatch,
socket-write confirmation, and teardown now identify the recipient by a
per-connection token. The token does not retain the handler or session.
The shutdown continues to wait for a replacement with the same server ID
after the old connection finishes closing.
- **Peer receipts and catch-up:** incoming RS updates contribute to
monitoring state separately from the outgoing cursor. A migrating DS can
publish a newer CSN through a peer while older records remain queued
locally, so the incoming maximum proves neither the older history nor
its delivery. During ordered traversal, suppress only exact cached
receipts and preserve older unknown records. The receipt cache is
bounded by the existing queue capacity; eviction may cause a
conservative resend. Peer generation changes and shutdown clear cached
receipts. An exact receipt from the matching generation resolves its own
pending or filtered CSN in either callback order. Other outstanding CSNs
continue to fence delivery. The tracker keeps a bounded set of filtered
CSNs and one exact overflow CSN per origin. Multiple distinct overflow
CSNs for an origin keep a conservative barrier until a local generation
reset or session replacement. This fixes catch-up returning a peer's own
`DeleteMsg` when its assured sender expects an acknowledgement.
- **History received through peers:** record the newest peer update of
each origin on the domain before changelog publication. This state is
shared with newly registering RS handlers, so registration between
receipt and persistence cannot hide a missing prefix. Before sending a
queued direct update, compare its origin with peer history and reread
the available prefix when needed. A still newer peer receipt cannot
excuse older missing records. Local generation changes clear the history
marker; covered markers avoid a full domain-state snapshot, and
unavailable old-generation history cannot cause a retry loop. Idle peers
and direct writes from another origin do not trigger generic third-party
forwarding.
- **Local session closure:** a blocked socket read can wake with
`SocketException` after a local `Session.close()` but before the handler
is marked shutting down. The reader now checks the session's close
state, consistently with its EOF path and the writer. A genuine remote
TCP reset still reports error `181`; unexpected EOF from modern peers
also remains an error. The harness does not broadly suppress shutdown
disconnects.
- **Planned RS switches.** The DS sends `StopMsg` and continues to
receive and replay changes from the retiring RS. It moves to the next RS
after the peer replies or the switch deadline expires. The switch
deadline governs the wait after the old RS stops sending heartbeats. The
DS sends each `SAFE_READ` acknowledgement on the session that delivered
the update and retries local writes on the replacement when the old
session refuses them. During concurrent shutdown, the replacement must
receive the missing updates before the `ReplicaOfflineMsg`, within the
existing shutdown deadline. An initialization header from the retiring
session is discarded before a full import can claim the backend.
- **RS start handshake.** Send the outgoing RS start message and wait
for its reply outside the domain lock. A separate peer lock still
arbitrates crossed RS connections. An initialized domain already serving
a DS accepts another DS while the peer connect pass is in flight. A
domain still bootstrapping waits for that pass. If the advertised
generation changes during the wait, stop the stale handshake so a later
attempt advertises the current generation.
- **Offline delivery after a planned switch.** A stopping broker that
cannot open the elected connection to the former RS can try one other RS
that answered discovery. Check generation compatibility before selecting
it and again after its start reply. The stop watchdog closes the
provisional socket if the replacement is still in its handshake at the
write deadline. The broker uses the replacement session to send the
pending offline marker after any required recovery.
- **Failover retry.** On the first reconnect after losing an established
session, a timeout waiting for the elected RS's start reply keeps the
single retry on that RS. After TCP refusal from the elected former RS,
the broker prefers a compatible discovery responder (#1343). A different
RS that missed its discovery reply can take the retry if the former RS
fails phase one for another reason or if no compatible responder is
available after TCP refusal. If no RS answers discovery, the broker can
make one session attempt to an RS that missed its discovery reply. The
configured isolation policy applies if reconnection fails.
- **Empty-RS recovery:** only `rs534 / scale-rs-empty` sets
`REPLICATION_RECOVER_FROM_RS=1` on the returning RS. After scale-in has
verified endpoint removal from every DS, bootstrap selects an RS that
reports `ready` and checks its role and readiness again under the join
lock. The same readiness requirement applies when only `MASTER_SERVER`
is configured. Missing or unreadable sources are retried through RS
peers. Enable uses `--baseDN 'cn=admin data' --noSchemaReplication`, so
the new endpoint enters the administrative topology before the data and
schema replica lists. A retained-history checkpoint must pass before
scale-out DS restarts expose the endpoint. Final offline checks still
compare every CSN. The mode is off by default, preserving ordinary
bootstrap peer order and endpoint advertisement. `ready` remains a
membership signal; the caller must enforce the history barrier.
- **Bootstrap cost:** sequential administrative searches share one JVM
while each request creates a fresh LDAP connection and parser. Positive,
negative and stale JVM DNS caching are disabled for this worker so
recreated peers are resolved afresh. Private FIFOs preserve arguments,
output and LDAP status codes. A failed, malformed or timed-out worker is
disabled and reads fall back to ordinary `ldapsearch`. Genuine LDAP
errors retain their status. Existing batching of `dsconfig` changes and
immediate one-use membership snapshots remain in place; topology data is
not cached across mutations.
- **Partial bootstrap recovery:** disable local replication using the
local root account, without relying on an incomplete global-admin
registry or changing remote peers. `dsreplication disable --disableAll`
enumerates the actual local replication-domain configuration, including
domains below a backend's base DN. Verify that no local
replication-domain/server configuration remains before enabling again. A
persistent pending-reset marker keeps retries on the cleanup path even
if a failed disable already removed the data domain. Disable,
verification and join-lock release failures propagate; write and
readiness gates stay closed during repair. A terminal bootstrap marker
aborts harness waits, while ordinary predicate and Docker transport
failures remain retryable. Failure artifacts retain filtered regular
setup/replication/status tool logs.
- **Import preparation timeouts.** If a remotely initiated import times
out while draining replay or replication state saves, send the refusal
on its original session before restarting the broker. For a
single-target export on a v9 route, the importer retains the refusal for
that attempt and can send it through a replacement RS even if the first
reconnect fails. The exporter waits for an attempt-specific preparation
acknowledgement before streaming LDIF. The importer enters `FULL_UPDATE`
before draining, which keeps it out of `SAFE_READ` acknowledgement
tracking during preparation. The v8 wire format and initialization
behavior are preserved.
- **Initialization during reconnect.** Keep the import context when the
replication broker successfully publishes the initialization request. A
connection-state check made before publication could otherwise abandon
the import after the exporter had already started. The broker returns
whether its session accepted the message and restores the send-window
credit of a refused update.
- **Docker restart assertions.** Wait for the restarted member to
confirm membership and check for replication resets in the current
startup log. Recovery messages from the initial bootstrap no longer fail
a subsequent plain restart. An unreadable startup log fails the no-reset
assertion in both topologies.
- **Docker startup.** The base branch already starts the server after
the setup JVM exits (#1326). This PR tests that ordering and checks that
setup and startup failures reach the caller. The fixtures also exercise
launcher diagnostics and collect container state and cgroup OOM counters
when startup fails.
- **Bootstrap completion:** the entrypoint clears `.bootstrap-finished`
on every start, including retained-container restarts, and creates it
only after successful setup/upgrade and the requested background join.
Both test harnesses require this positive result and give
`.bootstrap-failed` priority. An absent join process during setup no
longer counts as completion. Health remains separate so retained volumes
preserve OrderedReady behavior while membership repair runs.
- **Maven failure audit diagnostics.** The test listener prints up to 16
KiB from the active audit log and reports rotations together. When Maven
fails, Build uploads the complete retained active and rotated audit
files for that matrix row and attempt, with five days of retention.
- **Stopped-container diagnostics:** waits guard the nodes required by
the current phase and abort if one exits or dies. Docker transport
failures remain retryable, and deliberately stopped peers are excluded
from these guards. The error trap preserves the original failure while
collecting Docker exit/OOM state, container logs, server logs and
filtered tool logs through `docker cp`, including from stopped
containers. It avoids command-line/password-file dumps. Replication
fixtures enable bootstrap timing and upload diagnostics in artifacts
named by image flavor and workflow attempt.
- **Docker CI memory:** remove the 512 MiB cap from 23 `docker run`
sites in the replication fixture and Docker workflow, including
failed-bootstrap and upgrade cases, and remove the two unused memory
variables. OpenDJ test containers now use the memory available on the
runner without a replacement Docker cap. The persistent search worker
and all correctness checks remain enabled; removing the Docker cap does
not change the JVM arguments or workload ceiling. The small non-Java
shared-memory holder retains its separate 64 MiB cap. Scale scenarios
already ran without the 512 MiB Docker cap.
- **Transient errors and convergence:** a rolling startup timeout must
occur before CORE135, and the same DS ID and domain must subsequently
connect to a verified eligible RS before the log boundary captured after
successful bootstrap in the recorded rolling window. Recovery may occur
after CORE135. Require exactly one startup and one of the data,
admin-data or schema domains; unknown peers/domains, later unrelated
restarts, incomplete bootstrap and unrecovered timeouts remain failures.
Record the exact timeout text and absolute log line; the filter accepts
only that proven line, including recovered `cn=admin data` timeouts.
During a separate-server roll, a surviving DS disconnect is accepted
only for the stopped RS address and after a later successful connection
to a verified eligible RS in the same domain and rolling window. The
returned RS becomes eligible only during scale-out; accepted intervening
timeouts must name the successful destination. Scale certificate
warnings require recovery evidence for the returned RS. `DS119` requires
a later `NOTICE 62` for the same DS ID, domain and rebuilt endpoint by
the end of scale-out. The two empty-volume scale rows enable per-attempt
TLS diagnostics for DS and RS clients. The acceptor's exact `105` line
must match a single in-window failed caller attempt by both TCP
addresses and ports. A later record in that caller's log must prove a
session for the same role, ID and domain with the rebuilt RS. DS
recovery can occur during the scale-out roll. RS recovery requires a
matching `NOTICE 313` inside the return window. The attempt diagnostic
covers retries that emit no new `RS312`. When `RS312` is present, the
caller filter still requires its own matching in-window `313`.
Unrecovered warnings and shutdown error `181` remain failures. The
longer convergence budgets apply only to the two combined scale
variants; the stable-zero criteria are unchanged.
CSN tracing and bootstrap timing are opt-in. The four scale rows and
`rs534 / empty-rs` enable allocation traces; scale rows also enable
bootstrap timing. Missing or unclosed traces fail validation. Failure
collection first preserves the live state, then normally stops DS
processes in parallel to close their traces; `KEEP=1` leaves the
containers running.
## Validation
### Rebase onto `master` at `0af6285cff`
The rebase preserves the ordinary failover path from #1343 alongside
this PR's start-reply timeout retry and offline delivery during
shutdown. The SAFE_READ ACK counter fix is already in `master` through
#1344. [Rebased
commit](https://github.com/OpenIdentityPlatform/OpenDJ/pull/1282/commits/c115be873557f40811b1b4e110363f91839f6e45)
Maven `verify` on macOS / JDK 21 passed all 423 selected integration
tests, including 41 broker stop tests and both assured replication
suites, with zero failures or skips. The 43 Python tests, 22 shell
self-tests, and `git diff --check` passed. [Current
Build](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/46137609745)
### Offline delivery during a planned switch and Maven audit output at
`b692c0da6e`
The [first Build
attempt](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45999690841/attempts/1)
at `e6b66c174e` passed all 32 jobs, including all nine Maven jobs and
all 13 Docker convergence scenarios. In the [Ubuntu / JDK 21
rerun](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45999690841/job/140606297336),
both RSs answered discovery during a stop. The elected former RS then
refused the connection, and the stopping broker withdrew the undelivered
`ReplicaOfflineMsg`. A controlled socket run reproduced the behavior on
the CI merge commit and on `master` with synchronization adapted to its
synchronous switch.
[Fix](https://github.com/OpenIdentityPlatform/OpenDJ/commit/b692c0da6eb43def5e118536dd056498ec4a8540)
- The broker suite passed **39 tests on macOS / JDK 21**, and the five
targeted shutdown-switch cases passed again before push. The regression
verifies delivery on the replacement, expiry of the stop deadline when
the replacement withholds topology, and generation mismatch at discovery
or in the new start reply. Removing the watchdog's close of the
provisional socket caused the deadline assertion to fail. [Socket
tests](https://github.com/OpenIdentityPlatform/OpenDJ/blob/b692c0da6eb43def5e118536dd056498ec4a8540/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java#L1185)
- The failing CI test began printing its audit log at 16:32 UTC. The 66
largest records, totaling 17.3 MB, took 2 h 28 min to appear. Maven
recorded its own finish after 54 minutes. Failure diagnostics now print
a 16 KiB tail of the active audit log and a notice for rotations. All
three audit tests passed on JDK 11 and 21, and an intentional listener
failure confirmed the console output and full files on disk. The Build
workflow uploads retained audit files on Maven failure. `actionlint` and
`git diff --check` passed. [Audit
regression](https://github.com/OpenIdentityPlatform/OpenDJ/blob/b692c0da6eb43def5e118536dd056498ec4a8540/opendj-server-legacy/src/test/java/org/opends/server/TestCaseUtilsAuditLogTest.java#L29)
· [Artifact
upload](https://github.com/OpenIdentityPlatform/OpenDJ/blob/b692c0da6eb43def5e118536dd056498ec4a8540/.github/workflows/build.yml#L163)
### SAFE_READ ACK monitor timing at `e6b66c174e`
The Ubuntu / JDK 21 Maven job at `a11ac4fc0a` failed in
`AssuredReplicationPluginTest.testSafeReadModeReply`. The fake RS
received a successful ACK before the replay thread incremented
`assured-sr-received-updates-acked`. The test now waits for that counter
before checking the monitor snapshot. [Failing
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45985178673/job/140458842270)
· [Test
change](https://github.com/OpenIdentityPlatform/OpenDJ/commit/e6b66c174e41fa2288505f00e89a7b58fea38397)
- A temporary 750 ms pause before the increment reproduced the CI
assertion (`expected [1] but found [0]`). Both parameterized cases
passed with the updated test and the same pause. With the pause removed,
all 14 tests in `AssuredReplicationPluginTest` passed on macOS / JDK 21
with zero failures, errors, or skips. `git diff --check` passed.
### Slow peer RS start replies at `a11ac4fc0a`
Build at `893f01d6b9` passed 31 of 32 jobs. During `rs534 / empty-rs`,
`cv-d2` lost its session to the stopped `cv-r1`. Two handshakes to
`cv-r0` timed out, and `cv-d2` returned LDAP 53 for 20,575 client writes
before it reconnected. The saved logs locate the failed handshakes. The
cause of the delay in that CI run remains open.
[Build](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45956172960/attempts/1)
· [Failing empty-RS
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45956172960/job/140395331379)
- A controlled test drives the real RS connect thread and withholds a
peer start reply after TLS. On the previous code, a second DS on the
same initialized domain waited for that reply. With the fix, the DS
registers while the peer is still waiting. The test also verifies that a
crossed incoming RS gives way and that a generation change aborts the
stale handshake in the negotiated framing.
[a11ac4fc0a](https://github.com/OpenIdentityPlatform/OpenDJ/commit/a11ac4fc0a65bcf38e96b5d8285d2a29fc57eac4)
· [Socket
regression](https://github.com/OpenIdentityPlatform/OpenDJ/blob/a11ac4fc0a65bcf38e96b5d8285d2a29fc57eac4/opendj-server-legacy/src/test/java/org/opends/server/replication/server/ReplicationServerConnectFailureTest.java#L113)
- Maven on macOS / JDK 17 passed **133 targeted replication tests**,
with zero failures, errors, or skips. The run covered failover, crossed
connections, generation changes, registration, multi-homed peers, and RS
shutdown. `git diff --check` passed.
### Elected RS retry priority at `893f01d6b9`
A start-reply timeout while opening the elected session keeps the retry
on that RS. If the former RS answers discovery and then refuses the
elected TCP connection, the broker still retries the other RS that timed
out during discovery. Both paths share the same one-retry limit.
[893f01d6b9](https://github.com/OpenIdentityPlatform/OpenDJ/commit/893f01d6b9297b93ba9dd7fe8376e0ee3a9cbf95)
· [Review
finding](https://github.com/OpenIdentityPlatform/OpenDJ/pull/1282#pullrequestreview-6083080872)
- The new socket regression lets the former RS answer discovery, drop
its first elected start reply, and answer the retry. The other RS can
withhold both replies, and the test checks that it receives only the
discovery probe. The test reproduced premature isolation before the fix.
It now checks that the broker reconnects to the elected RS without
setting `connectionError` and delivers a subsequent LDAP write.
- Maven on macOS / JDK 17 passed **10,875 unit tests** and **36
integration tests** in the targeted broker run. Both the new regression
and the closed-listener fallback case passed. `git diff --check` passed.
### Failover retry after the former RS disappears at `10db3a058c`
The Ubuntu / JDK 17 job at `2c432ed240` reported one failure in
`ReplicationBrokerStopTest.failoverAllowsOneRetryOfTheSurvivingRs`. The
survivor timed out during discovery, and the former RS was selected but
refused the connection. The broker entered isolation before retrying the
survivor. The fix directs the single retry to the survivor in this case.
[10db3a058c](https://github.com/OpenIdentityPlatform/OpenDJ/commit/10db3a058c0476bdd4d2481ae5e3f2f662f397c9)
· [Failing
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45871967027/job/140089520411)
- The socket regression reproduces this sequence by closing the former
RS listener after its discovery reply. It failed with the same
premature-isolation assertion before the fix. Maven on macOS / JDK 17
passed all **35 tests** in `ReplicationBrokerStopTest` and
`ReplicationBrokerConnectFailureTest`, including all six failover cases,
with zero failures, errors, or skips. `git diff --check` passed.
### CodeQL follow-up at `2c432ed240`
The receive loop uses one null-checked session from the connection
snapshot for reads, acknowledgements, and reconnect handling.
Single-target export initializes its ACK window with the validated
replica ID. The import caller closes `ReplInputStream` when either
backend import path returns or throws, including when preparation is
refused.
[Fix](https://github.com/OpenIdentityPlatform/OpenDJ/commit/2c432ed240384f197404400fd470b01dfe879f8f)
· [Session
warning](https://github.com/OpenIdentityPlatform/OpenDJ/security/code-scanning/1700)
· [Target
warning](https://github.com/OpenIdentityPlatform/OpenDJ/security/code-scanning/1712)
· [Stream
warning](https://github.com/OpenIdentityPlatform/OpenDJ/security/code-scanning/1713)
- Maven on macOS / JDK 21 passed all **120 tests** in `InitOnLineTest`,
`ReplicationDomainTest`, `ReplayDuringImportTest`, and
`ReplicationBrokerStopTest`, with zero failures, errors, or skips. `git
diff --check` passed. CodeQL reported no new alerts on `2c432ed240`.
[CodeQL
check](https://github.com/OpenIdentityPlatform/OpenDJ/runs/140089832795)
### v9 replication test fixtures at `6464860991`
The Ubuntu / JDK 21 build at `f326bc91f6` recorded five failures in two
test classes. The single-RS simulated importer did not send its v9
preparation acknowledgement. The four generation ID warning cases
decoded a hand-built v8 payload with the v9 decoder. [Failing
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45860524492/job/140050038184)
· [Fixture
fixes](https://github.com/OpenIdentityPlatform/OpenDJ/commit/6464860991dc34c4d69fe91bc5233884333eba44)
- Both single-target export fixtures send the preparation
acknowledgement when the header supplies an attempt ID. The warning
fixture decodes its byte array as v8, then sends the message over the
peer session using the negotiated protocol. It exercises routing for
both the symbolic and numeric message IDs.
- Maven on macOS / JDK 21 passed all **55 tests** in `InitOnLineTest`
and `ReplicationDomainTest`, including all five failing cases, with zero
failures, errors, or skips. `git diff --check` passed.
### Import refusal after an RS change at `f326bc91f6`
If the original RS accepts a preparation refusal after losing its route
to the exporter, the importer can resend the same refusal through the
replacement RS. A v9 preparation acknowledgement or refusal is matched
by attempt ID and importing replica ID. The exporter waits for that
reply even if the importer temporarily disappears from the topology.
[Blocking
review](https://github.com/OpenIdentityPlatform/OpenDJ/pull/1282#pullrequestreview-6076376014)
·
[Fix](https://github.com/OpenIdentityPlatform/OpenDJ/commit/f326bc91f6e2e0a15594b7a91e4ba5d587371212)
- The two-RS regression covers a direct reconnect to the exporter's RS,
a failed first reconnect, and a return to the original RS before
failover. It verifies that the exporter reports the exact preparation
failure, ignores a refusal for an earlier attempt, and sends no LDIF
before the importer is ready. The importer's existing data survives. A
separate case exercises successful preparation and import. [Socket
tests](https://github.com/OpenIdentityPlatform/OpenDJ/blob/f326bc91f6e2e0a15594b7a91e4ba5d587371212/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplayDuringImportTest.java#L666)
- The macOS / JDK 27 Maven reactor passed **93 selected tests** with
zero failures, errors, or skips. This includes all of
`ReplayDuringImportTest` and `ProtocolCompatibilityTest`, the multi-RS
single-target export test, and the single-RS generation ID test. The
codec tests verify that v9 messages retain the attempt ID, that scoped
replies are never sent as ordinary v8 replies, and that ordinary v8
messages remain compatible. `git diff --check` passed. [Protocol
tests](https://github.com/OpenIdentityPlatform/OpenDJ/blob/f326bc91f6e2e0a15594b7a91e4ba5d587371212/opendj-server-legacy/src/test/java/org/opends/server/replication/protocol/ProtocolCompatibilityTest.java#L1144)
### Import refusal during reconnect at `a7863a4de1`
The Ubuntu / JDK 25 Maven job at `7a79c63667` reached the ten-minute
timeout in
`ReplayDuringImportTest.aTimedOutDrainLeavesTheOriginalDataUsable`. The
importer had rejected the request before replacing the backend. Its
reconnect was refused while the RS still held its previous registration,
so the exporter did not receive the refusal. With periodic monitoring
frames, the test's broker read could keep waiting without reaching the
assertion deadline. [Failing
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45812528898/job/139883928282)
·
[Fix](https://github.com/OpenIdentityPlatform/OpenDJ/commit/a7863a4de1d115319c829e889fdbe7913f5a2d26)
- Both drain-timeout cases failed before the fix and passed afterward.
The test disables reconnect while keeping the original session open,
reads from the exporter's timed session, and verifies the exact refusal,
the original data, and a successful subsequent import. [Regression
test](https://github.com/OpenIdentityPlatform/OpenDJ/blob/a7863a4de1d115319c829e889fdbe7913f5a2d26/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplayDuringImportTest.java#L587)
- A local socket run delayed removal of the old DS registration by 750
ms, confirmed that the RS refused the immediate reconnect, and verified
that the exporter received the error and the subsequent import
succeeded. All 105 tests in `ReplayDuringImportTest`,
`ReplicationDomainTest`, and `ReplicationBrokerStopTest` passed on macOS
/ JDK 21. `git diff --check` passed. [Build
checks](https://github.com/OpenIdentityPlatform/OpenDJ/pull/1282/checks)
### Failover test readiness at `7a79c63667`
The failover fixture waits for the replacement RS ID and for the broker
to clear `connectionError` before asserting that LDAP writes resume. The
exhaustion cases verify LDAP 53 during isolation, then require a
successful modify and delivery after recovery.
[Review](https://github.com/OpenIdentityPlatform/OpenDJ/pull/1282#pullrequestreview-6073370300)
·
[Fix](https://github.com/OpenIdentityPlatform/OpenDJ/commit/7a79c636673846ba26dcb84e6c3f148343d687cc)
· [Updated
test](https://github.com/OpenIdentityPlatform/OpenDJ/blob/7a79c636673846ba26dcb84e6c3f148343d687cc/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java#L1603)
A local run with a 750 ms delay before clearing isolation reproduced the
premature LDAP 53 response in both exhaustion cases at `bfc52bf3c2`. All
five cases passed on JDK 21 with the test fix, both with the delay and
with the normal broker. The branch is based on `master` at `b24036b260`.
[Build
checks](https://github.com/OpenIdentityPlatform/OpenDJ/pull/1282/checks)
### Failover retry at `bfc52bf3c2`
On `19930c9fe6`, 31 of 32 Build jobs passed. In `rs534 / empty-rs`,
`cv-d3` timed out probing the surviving `cv-r0`, and `cv-d0` timed out
opening its session after a successful probe. The DSs returned 35,384
LDAP 53 responses before reconnecting to `cv-r0`. The load check failed
before LDIF and changelog validation. [Failing
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45771247952/job/139782051209)
· [CI
diagnostics](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45771247952/artifacts/15101853312)
- Three socket cases reproduced premature isolation on the previous
broker. With the retry, all five cases passed on JDK 21, including both
timeout paths, ordered delivery of LDAP writes, and LDAP 53 after the
retry expires. All five passed again on the branch rebased onto `master`
at `ede1b306bc`.
[Fix](https://github.com/OpenIdentityPlatform/OpenDJ/commit/bfc52bf3c2557b1f3a57ffa9cd91bf13efb8e5c4)
· [Regression
test](https://github.com/OpenIdentityPlatform/OpenDJ/blob/bfc52bf3c2557b1f3a57ffa9cd91bf13efb8e5c4/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java#L1538)
- The broader JDK 21 run passed 66 tests across
`ReplicationBrokerStopTest`, `HandshakeAbortRegistrationTest`, and
`ReplayDuringImportTest`. [Build on this
revision](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45804838237)
### Retiring-session initialization guard at `1369b20b51`
The DS checks the session that delivered an `InitializeTargetMsg` before
dispatching it to the import listener. A session that is closing for a
planned switch can continue delivering incremental changes. The broker
discards its initialization headers before dispatch. [Blocking
review](https://github.com/OpenIdentityPlatform/OpenDJ/pull/1282#pullrequestreview-6051721228)
· [Fix
commit](https://github.com/OpenIdentityPlatform/OpenDJ/commit/1369b20b511b96bacd4018bfe1a33119912ec9c1)
- The socket regression failed on the rebased parent because the
retiring session started full initialization. With the guard, the
existing entry remains readable and present in the active LDIF file. The
incremental delete from the retiring RS is replayed and persisted before
the stop reply.
- On JDK 21, **30 Maven integration tests passed**, covering the full
`ReplicationBrokerStopTest` class and both selected
`ReplayDuringImportTest` scenarios. The branch is based on `master` at
`ded55f7c56`. [Build
checks](https://github.com/OpenIdentityPlatform/OpenDJ/pull/1282/checks)
- On the first CI attempt at `4995d9c455`, the Ubuntu / JDK 27 Maven
step passed. The runner received a shutdown signal during the later
replication step. The interrupted matrix row skipped the downstream
Docker checks. [Previous Linux
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45494537218/job/138801569004)
### Planned RS switch at `4995d9c455`
The `rs534 / restart-rs` job on #1316 recorded `ERROR 211` when a DS
rebalanced from the surviving RS to the restarted RS. The retiring RS
reported a TCP reset with 99 messages still queued. Indexed searches and
offline checks passed, and both changelogs had zero gaps. [Failing
`restart-rs`
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45351125404/job/138543571882)
· [Replication logs and check
results](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45351125404/artifacts/14939560365)
- A socket regression on `d3cc5cc725` showed the DS leaving its old
session before that RS replied. On
[`4995d9c455`](https://github.com/OpenIdentityPlatform/OpenDJ/commit/4995d9c455644a19cd24ea2c344050e22978710c),
the DS replays an update from the old RS and sends its pending local
update once on the replacement. The regression also pauses the old RS
heartbeat during the stop exchange. Separate tests cover an unresponsive
peer and a genuine heartbeat failure.
- The JDK 21 Maven reactor passed **701 selected replication tests**
before the final heartbeat change. After that change, **72 focused
tests** passed across the broker, publisher, teardown and status-monitor
classes. The replication-error filter, restart and kill fixtures, and
summary self-tests passed.
- The local Docker `restart-rs` and `kill-rs` attempts ended at node
readiness before the convergence checks, including a retry with bounded
JVM resources. [Build
checks](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45494537218)
### Earlier merge candidate `d3cc5cc725`
This candidate is based on `master` at `9db63ab6e6`. Its replication
sources, replication tests and scenario scripts match the revision
approved at `af80f3243a`. The seven subsequent commits on RS switching,
failover and initialization were set aside for separate review. The
reviewer approved this candidate after verifying the split. [Candidate
approval](https://github.com/OpenIdentityPlatform/OpenDJ/pull/1282#pullrequestreview-6038726301)
[Candidate
commit](https://github.com/OpenIdentityPlatform/OpenDJ/commit/d3cc5cc7256275f5de5a82df14d56d56a2ad1027)
· [Earlier
approval](https://github.com/OpenIdentityPlatform/OpenDJ/pull/1282#pullrequestreview-6003626545)
- All 32 local checks passed on this SHA, covering 27 replication
scripts, four Docker fixtures and the Unix launcher fixture under
`dash`. The diff against the base passed `git diff --check`.
- All 33 Build jobs passed on the earlier approved revision. CodeQL
passed on this candidate. Its Build checks both `rs534 / kill-rs` and
`rs534 / empty-rs`. [Earlier
Build](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44819053721)
· [Candidate
Build](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45384412227)
· [Candidate
CodeQL](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45384412161)
<details>
<summary>Validation on earlier revisions</summary>
### Review follow-up at `af80f3243a`
- The JDK 21 Maven reactor passed **185 selected tests**, with zero
failures, errors, or skips. A real DS broker TLS handshake failure
produces `NOTICE341` with the role, replica ID, domain and both TCP
endpoints. The publication regression checks a session refusal and full
restoration of its send-window credit.
- All **31 shell/Python self-tests** passed, including **156
error-filter cases**. The restart fixture rejects a reset from the
current startup and an unreadable log. For a healthy combined node, it
detects both a missing membership wait and a reset assertion that ran
before membership was reported.
- The five-file review diff was preserved when rebasing onto
`fac7c60c5f`. The restart, replication-error and Docker entrypoint
self-tests and Bash syntax checks passed again on the rebased branch.
### Full CI at `ccc0e286d3`
[Build 44691688631, attempt
1](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44691688631/attempts/1)
passed **33 of 33 jobs**, including all nine Maven jobs, both Docker
replication and upgrade jobs, and all 13 convergence scenarios. Both
Docker variants passed the plain restarts, including the separate-role
restart that failed on `cfa0e0c081`.
[CodeQL](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44691688678)
passed all four analyses. The [Trivy
comparison](https://github.com/OpenIdentityPlatform/OpenDJ/runs/136534501507)
was neutral because two scheduled published-image configurations from
`master` were absent on the PR. Both built-image scan and SARIF upload
steps passed.
The four scale rows finished their workloads in 1330–2163 seconds under
the 2700-second ceiling. Both empty-volume rows recorded 50,001 updates
while the server was absent and zero missing changelog changes. The
certificate proof files were empty in both rows. [Separate-role
artifact](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44691688631/artifacts/14655321308),
[combined
artifact](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44691688631/artifacts/14636662788).
### Docker replication follow-up at `ccc0e286d3`
[Build
44620035038](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44620035038)
on `cfa0e0c081` passed all 13 convergence scenarios, including all four
scale rows. The [default Docker
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44620035038/job/135989621836)
failed because its restart check matched reset messages from the initial
bootstrap. The [failure
artifact](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44620035038/artifacts/14590617482)
shows that `dj-d0` started exporting while `dj-d1` reported a
disconnected broker, and that `dj-r0` confirmed membership after the
restart without a new reset.
- The new replication regression reproduced an exporter starting while
the importer reported a disconnected broker. It passed after the fix and
verified transferred data and successful completion on both sides. All
43 `ReplicationDomainTest` cases passed on JDK 21 with zero failures or
skips.
- The shell regression accepts an old reset and rejects one in the
current startup. The Docker diagnostics and bootstrap self-tests, Bash
syntax checks, and `git diff --check` passed.
- Locally, the default CI image with the corrected replication class
passed the four-node `#534` startup and plain-restart phases, including
replication in both directions and both membership checks. This run
covered those two phases of the Docker fixture.
### TLS attempt correlation at `cfa0e0c081`
- The error-filter regression accepts paired failures logged in adjacent
seconds and TLS retries without a new outage warning. It rejects
unrelated socket endpoints, ambiguous attempts, and missing or
out-of-window RS recovery. The dedicated caller fixture verifies that an
in-window `NOTICE313` clears `WARN312` and an out-of-window one leaves
the exact warning.
- The JDK 21 Maven reactor passed **30 selected tests**, with zero
failures or skips. The socket regression captures both endpoints for
each of two retries while the caller reports the outage once. All **27
replication shell/Python self-test files** passed on macOS and Linux,
including **156 error-filter cases**. All 13 Docker convergence
scenarios passed in the CI run linked above.
### TLS and retained-volume scale follow-up at `4b2fffa22a`
In [Build
44520106015](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44520106015)
at `a6e8c6495a`, both separate-server scale rows and `combined /
scale-empty` passed. [`combined /
scale-kept`](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44520106015/job/135641927702)
timed out at the first scale-out checkpoint. The retained-volume
bootstrap reassigned `cv-c3` from replica ID `5593` to `10069`. The new
process's trace contained only offline allocations. All 323 comparisons
rejected the reference snapshot for its missing workload position for DS
`10069`. The new-ID write probe now runs before this checkpoint in both
combined scale variants. [Failure
artifact](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44520106015/artifacts/14544294597)
- The certificate fixtures reproduce the two review failures on the
previous code. They cover a same-second `62` followed by a later valid
`62`, recovered `RS312` with a matching acceptor `105`, and a combined
caller with same-second warnings in both roles. Missing recovery, the
wrong source or session, and RS recovery outside the return window
remain errors.
- The lifecycle fixture covers a retained-volume rejoin with a new ID,
aborts the roll when its LDAP probe fails, and checks the probe ordering
before the first pause. The identity fixture validates recording a new
ID and recognizing a previously recorded one.
- All 27 replication shell/Python self-tests passed on macOS and Linux
with GNU awk, including 151 error-filter cases. Shell syntax and `git
diff --check` passed. All 13 Docker convergence scenarios later passed
on this revision, including all four scale rows. [Build
44561609276](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44561609276)
### CI follow-up at `a6e8c6495a`
[Build 44343640204, attempt
3](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44343640204/attempts/3)
on `80fb0f9369` passed 31 of 33 Build jobs, including all Maven jobs and
11 of 13 Docker convergence scenarios. CodeQL passed.
- [`rs534 /
scale-rs-empty`](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44343640204/job/135127285794)
converged in 17 seconds. LDIF, index and changelog checks passed,
including complete coverage of the 50,001-change backlog. The online
error check found `54` on `cv-r0` when its local `cn=admin data` DS
tried to reconnect as the rebuilt RS was added to the peer list. The DS
connected to `cv-r1` one second later.
- [`combined /
scale-kept`](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44343640204/job/135127285839)
completed scale-out around 2632 seconds into the 2700-second load. All
230 clients exited with status `0`. The remaining 68 seconds fell below
the 70-second minimum for launching a post-scale segment, so the job
ended before convergence and offline checks.
- The JDK 21 Maven reactor passed all 85 selected Java tests with zero
failures or skips. The handshake regression reproduces error `54` before
the fix for both a closing session and a handler already marked for
shutdown. It also verifies rejection and error reporting for a live
duplicate.
- All 27 replication shell/Python self-tests passed on macOS and on
Linux with GNU awk. The scale fixture rejects the old serial pause order
and checks that failure releases the surviving writers. Shell syntax and
`git diff --check` passed.
### Review follow-up at `80fb0f9369`
- The two targeted TestNG classes ran on JDK 21 using the reactor
classpath and freshly compiled changed classes. All 55 tests passed with
zero failures or skips. The shutdown regression exercises a fatal
changelog write error for DS and RS sources. The receipt regressions
cover both callback orders, a different generation, an outstanding
earlier write, cache eviction, and overflow. The CLI regression uses a
backend-root domain and a nested domain. The prior code timed out at the
DS shutdown barrier, kept the exact receipt blocked, and left the nested
domain configured.
- All 32 local shell/Python self-test files passed, including 137
replication error filter cases. Scale fixtures require the returned DS's
first write and refresh a reference snapshot missing the new origin. The
join fixtures exercise readiness at selection and under lock, confirm
that only recovery disables schema replication, and reject independent
mutations to the wrapper's exit status and failure marker. Shell syntax,
copyright headers and `git diff --check` passed.
### Scale return-window follow-up at `34439d8870`
- The regression feeds the allowances emitted by `disturb()` to the real
error filter. It failed before the fix and passed for both surviving RSs
afterward. The filter tests still cover missing recovery, a different
peer or domain, and recovery outside the return window.
- All 27 replication self-tests and the launcher self-test passed on
macOS. The error filter passed 137 cases. Shell syntax checks and `git
diff --check` passed. Local verification used log fixtures for this
change. In [Build
44303119965](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44303119965),
both separate-server scale rows and `combined / scale-empty` passed.
[`combined /
scale-kept`](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44303119965/job/134899066020)
reached convergence, then failed the online replication-error check on
`cv-c1`.
### Review follow-up at `6ca519583a`
- The JDK 21 Maven reactor passed **162 selected tests** with zero
failures, errors, or skips. The replacement-session regression failed
before the fix because the old teardown cleared the outstanding forward,
then passed with per-session ownership.
- The two-domain direct-update test recorded both timeout warnings and
completed the forwarding wait in about 2.1 seconds with a shared
2-second budget. The LDAP test used a listener returning an entry
followed by `sizeLimitExceeded` (`4`) and verified output, status and
the next worker request. The shell fixture also compares partial LDIF
byte for byte and verifies that the worker result does not trigger a
fallback.
- All **27 replication self-test files** and the launcher self-test
passed on macOS. The error filter passed **137 cases**, including
cross-domain, wrong-peer and out-of-window recovery checks. The launcher
fixture checks exit `2`, diagnostics with a still-running child, and
that the final startability probe is skipped. `git diff --check` passed.
- The scale certificate checks were exercised with fixtures and archived
logs. See [Build
44259103177](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/44259103177)
for CI on that revision.
### Previous validation at `7451e3f79f`
[Build 43994616243, attempt
1](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/43994616243),
on head `7451e3f79f`, passed all 33 jobs. All nine Maven jobs, both
Docker replication/upgrade fixture jobs, and all 13 convergence
scenarios passed. CodeQL also passed on its first attempt. The scale
scenarios completed the workload and online/offline checks within their
configured limits:
| Scenario | Load | Convergence phase |
|---|---:|---:|
| `rs534 / scale-rs-kept` | 1036 s | 108 s |
| `rs534 / scale-rs-empty` | 1114 s | 101 s |
| `combined / scale-kept` | 1304 s | 131 s |
| `combined / scale-empty` | 1944 s | 194 s |
The previously failing `rs534 / empty-rs` scenario also passed. The
Trivy check is neutral: GitHub could not compare alerts for
`trivy-image-alpine` and `trivy-image-latest` because those
configurations from `master` were not found on the PR.
The completed [Build 43914906507, attempt
1](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/43914906507),
at preceding head `1cb60c42f9`, finished with **29 successful jobs and
four failures**. Both complete Docker replication/upgrade fixture jobs
and all nine Maven jobs passed. Head `7451e3f79f` addressed the four
failing rows:
| Scenario | Result at `1cb60c42f9` | Corresponding correction |
|---|---|---|
| `combined / scale-empty` | Passed all checks; workload 1746 s | The
previous 99-record gap and unexpected error `181` did not recur in this
run. |
| `combined / scale-kept` | Workload 2218 s; stable-zero phase completed
in 510 s within the 900-second budget; final data/index/history checks
passed, but one replay error `9` failed the row | Prevent dependency
re-parking after replay ownership transfers. |
| `rs534 / scale-rs-kept` | Workload 2185 s; final data/index/history
checks passed, but a recovered admin-data startup timeout failed the row
| Record exact same-DS/domain recovery after CORE135 and before observed
successful bootstrap. |
| `rs534 / scale-rs-empty` | Aborted during scaling after 715 s of load:
a 50-second add segment averaged about 1.72 operations/s, below the 2/s
floor, with zero LDAP errors while bootstrap commands were still running
| Complete the whole restarted group's bootstrap before resuming
measured load. |
| `rs534 / empty-rs` | A surviving RS handshake timed out during
failover; DS writes were rejected with LDAP result 53 before
reconnection | Release the live RS domain lock before session closure
can block on draining accepted writes. |
Local verification at `7451e3f79f`:
- The combined **12-class Java run passed 242 tests, with zero failures
or skips**, in 136 seconds. It covers pending-change ownership,
dependency ordering, selected replay-unwind paths, historical ordering,
RS/session shutdown, reader/writer disconnects, missed-update recovery,
catch-up and send-window handling. Existing disabled or excluded tests
are not counted as executed; this is a targeted regression suite, not
the full Maven suite.
- Twelve new deterministic ownership cases failed before the fix and
passed afterward, across ADD/MODIFY/DELETE/MODDN. They cover double
handoff, clear plus same-CSN re-delivery and stale foreign-owner scans.
Removing either the identity guard or the owner guard independently
causes four expected failures.
- Two new tests use real sessions and a real broker handshake while
another DS or RS session's close is deliberately held in a socket flush.
Both timed out before the lifecycle split and passed afterward.
Reader-join, replacement-monitor and concurrent full-shutdown
regressions also pass. The drain remains graceful; no new broker retry
suppression or timeout increase was introduced.
- All **27 replication shell/Python self-test files passed on macOS and
Linux**. Bootstrap tests cover every member of the group, active
surviving writers, positive completion, terminal failure, retryable
transport errors, worker failure and deadline exhaustion. Timeout tests
reject mismatched domains/DSs, unknown peers, unrelated restarts,
incomplete bootstrap and out-of-window recovery. Four harness mutations
fail their intended assertions.
- Replaying the saved CI bootstrap log changes the recovered-timeout
result from zero accepted records to exactly one: DS8716, `cn=admin
data`, with the original error text and line retained as evidence. Shell
syntax, copyright checks and `git diff --check` pass.
The exact CI thread interleavings were not captured; the regressions
reproduce concrete ownership and handshake-blocking mechanisms
consistent with the failures. Bootstrap overlap is established by the
saved timing logs; the new scheduling completed all four scale workloads
within 2700 seconds in the CI run above. No heavy local OpenDJ/Docker
load run was repeated on the busy host.
The 2700-second scale workload ceiling, 900/600/300-second convergence
budgets, throughput floors and strict data/index/history/error checks
remain unchanged. Longer bootstrap waits fail within those bounds rather
than bypassing them.
</details>
59 files modified
45 files added
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | # Best-effort diagnostics; the caller retains the original test exit code. |
| | | set -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | . "$HERE/replication/collect.sh" |
| | | node=${1:?container name required} |
| | | out=${2:?output directory required} |
| | | mkdir -p "$out" || exit 1 |
| | | docker inspect --format '{{json .State}}' "$node" >"$out/state.json" 2>&1 || true |
| | | docker logs --timestamps "$node" >"$out/container.log" 2>&1 || true |
| | | docker cp "$node:/opt/opendj/data/logs" "$out/" >/dev/null 2>&1 || true |
| | | collect_tool_logs "$node" "$out/tool-logs" || true |
| | | docker cp "$node:/opt/opendj/.bootstrap-failed" "$out/bootstrap-failed" >/dev/null 2>&1 || true |
| | | docker exec "$node" sh -c ' |
| | | for file in /sys/fs/cgroup/memory.events /sys/fs/cgroup/memory.events.local \ |
| | | /sys/fs/cgroup/memory.current /sys/fs/cgroup/memory.peak /sys/fs/cgroup/memory.max \ |
| | | /sys/fs/cgroup/memory.swap.current /sys/fs/cgroup/memory.swap.peak /sys/fs/cgroup/memory.swap.max \ |
| | | /sys/fs/cgroup/memory/memory.oom_control /sys/fs/cgroup/memory/memory.failcnt \ |
| | | /sys/fs/cgroup/memory/memory.memsw.usage_in_bytes /sys/fs/cgroup/memory/memory.memsw.limit_in_bytes \ |
| | | /proc/1/status; do |
| | | if [ -r "$file" ]; then printf "%s\n" "$file"; cat "$file"; fi |
| | | done |
| | | ps -eo pid,ppid,rss,comm 2>/dev/null || true |
| | | ' >"$out/processes-and-memory.txt" 2>&1 || true |
| | | printf '::group::Docker diagnostics (%s)\n' "$node" |
| | | cat "$out/state.json" "$out/processes-and-memory.txt" |
| | | [ ! -f "$out/logs/start-ds.log" ] || cat "$out/logs/start-ds.log" |
| | | [ ! -f "$out/logs/errors" ] || tail -n 1000 "$out/logs/errors" |
| | | for file in "$out"/tool-logs/*.log; do |
| | | [ ! -f "$file" ] || { printf '%s\n' "$file"; cat "$file"; } |
| | | done |
| | | tail -n 100 "$out/container.log" |
| | | printf '::endgroup::\n' |
| | |
| | | |
| | | set -eE -o pipefail |
| | | |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | DIAGNOSTICS=${DIAGNOSTICS:-${RUNNER_TEMP:-/tmp}/docker-replication} |
| | | IMAGE=${1:?usage: $0 <image>} |
| | | NODES="dj-0 dj-1 dj-2 dj-x dj-solo dj-bf dj-fi dj-f dj-p0 dj-p1 dj-p2 dj-ipm dj-ipr dj-sdsr dj-shm-probe dj-shm dj-d0 dj-d1 dj-r0 dj-r1 dj-dn0 dj-dn1 dj-rf dj-rfd dj-nm dj-nmr dj-bogus" |
| | | VOLUMES="vol-dj-0 vol-dj-1 vol-dj-2 vol-dj-x vol-dj-solo vol-dj-bf vol-dj-fi vol-dj-f vol-dj-ipr vol-dj-p0 vol-dj-p1 vol-dj-p2 vol-dj-d0 vol-dj-d1 vol-dj-r0 vol-dj-r1 vol-dj-dn0 vol-dj-dn1 vol-dj-rf vol-dj-rfd vol-dj-nm vol-dj-nmr vol-dj-bogus" |
| | |
| | | docker volume rm -f $VOLUMES >/dev/null 2>&1 || true |
| | | } |
| | | cleanup |
| | | # the container log says that a dsreplication failed and where its detailed log is; the errors |
| | | # log of the server and those detailed logs say why. Both are in the instance, which the |
| | | # image keeps under /opt/opendj/data, and a stopped container has nothing to exec in |
| | | # Preserve the exit/OOM state and files even after PID 1 has exited. docker exec |
| | | # cannot read a stopped container; the collector uses docker cp for its logs. |
| | | dump_logs() { |
| | | local c |
| | | for c in $NODES; do |
| | | echo "::group::container logs ($c)" |
| | | docker logs $c 2>&1 || true |
| | | echo "::endgroup::" |
| | | [ "$(docker inspect -f '{{.State.Running}}' $c 2>/dev/null)" = true ] || continue |
| | | echo "::group::server logs ($c)" |
| | | docker exec $c sh -c 'tail -n 1000 /opt/opendj/data/logs/errors; for f in /opt/opendj/data/tmp/opendj-replication-*.log; do [ -f "$f" ] && echo "--- $f" && cat "$f"; done' 2>&1 || true |
| | | echo "::endgroup::" |
| | | docker inspect "$c" >/dev/null 2>&1 || continue |
| | | bash "$HERE/docker-startup-diagnostics.sh" "$c" "$DIAGNOSTICS/$c" || true |
| | | done |
| | | } |
| | | # set -E hands the trap to every $(...) as well, where a failing command would dump the logs |
| | | # into the value being captured and remove the containers under the running test: there the |
| | | # failure only ends the subshell, and the main shell decides |
| | | trap 'code=$?; [ "$BASH_SUBSHELL" -eq 0 ] || exit $code; dump_logs; timings; cleanup; exit $code' ERR |
| | | trap 'code=$?; [ "$BASH_SUBSHELL" -eq 0 ] || exit $code; trap - ERR; set +e; dump_logs; timings; cleanup; exit $code' ERR |
| | | |
| | | # Where the time goes: each case logs when it starts, in seconds since the script started, and |
| | | # a wait that takes long logs how long; the run ends - failed or not - with the cases sorted by |
| | |
| | | # Not right after the start: until this start logs <since> itself, the last such line and the |
| | | # text after it are those of the start before - run.sh prints "Starting OpenDJ" only after |
| | | # the upgrade |
| | | # Return 1 for a missing match and 2 when the log could not be read. |
| | | logs_have_since() { # <container> <since> <text> |
| | | docker logs "$1" 2>&1 | awk -v s="$2" 'index($0, s) { buf = ""; next } { buf = buf $0 "\n" } END { printf "%s", buf }' \ |
| | | | grep -F -- "$3" >/dev/null |
| | | local log |
| | | log=$(docker logs "$1" 2>&1 | |
| | | awk -v s="$2" 'index($0, s) { buf = ""; next } { buf = buf $0 "\n" } END { printf "%s", buf }') || return 2 |
| | | grep -F -- "$3" <<<"$log" >/dev/null |
| | | } |
| | | |
| | | assert_no_replication_reset() { # <container> |
| | | local status=0 |
| | | logs_have_since "$1" "Starting OpenDJ" "taking its replication configuration down" || status=$? |
| | | case "$status" in |
| | | 0) fail "$1 reset its replication on a plain restart" ;; |
| | | 1) return 0 ;; |
| | | *) fail "could not read the current startup log for $1" ;; |
| | | esac |
| | | } |
| | | |
| | | # Only nodes explicitly required by this wait are checked: other scenarios stop |
| | | # peers deliberately, and some waits observe an expected failed bootstrap. |
| | | container_running() { # <container> |
| | | local state |
| | | state=$(docker inspect --format '{{.State.Status}}' "$1" 2>/dev/null) || return 1 |
| | | case "$state" in |
| | | running) return 0 ;; |
| | | exited|dead) |
| | | echo "::error::$1 stopped while it was required by the test" |
| | | docker inspect --format '{{json .State}}' "$1" 2>&1 || true |
| | | return 200 ;; |
| | | *) return 1 ;; |
| | | esac |
| | | } |
| | | |
| | | wait_running() { # <space-separated containers> <seconds> <what> <command> [<argument>...] |
| | | local WAIT_NODES=$1 |
| | | shift |
| | | wait_until "$@" |
| | | } |
| | | |
| | | wait_until() { # <seconds> <what> <command> [<argument>...] |
| | | local deadline=$((SECONDS + $1)) what=$2 start=$SECONDS |
| | | local deadline=$((SECONDS + $1)) what=$2 start=$SECONDS rc c |
| | | shift 2 |
| | | until "$@"; do |
| | | [ "$SECONDS" -lt "$deadline" ] || fail "timed out waiting until $what" |
| | | while :; do |
| | | rc=0 |
| | | for c in ${WAIT_NODES:-}; do |
| | | container_running "$c" || rc=$? |
| | | [ "$rc" -eq 0 ] || break |
| | | done |
| | | if [ "$rc" -eq 0 ]; then "$@" || rc=$?; fi |
| | | [ "$rc" -ne 0 ] || break |
| | | [ "$rc" -ne 200 ] || { fail "terminal failure while waiting until $what"; return 1; } |
| | | [ "$SECONDS" -lt "$deadline" ] || { fail "timed out waiting until $what"; return 1; } |
| | | sleep 2 |
| | | done |
| | | [ $((SECONDS - start)) -lt 20 ] || echo " [$((SECONDS - start)) s] until $what" |
| | |
| | | } |
| | | |
| | | wait_healthy() { |
| | | wait_until 480 "$1 is healthy" is_healthy "$1" |
| | | wait_running "$1" 480 "$1 is healthy" is_healthy "$1" |
| | | } |
| | | |
| | | # A container reports itself healthy only after a probe that finds the marker, and the |
| | |
| | | } |
| | | |
| | | wait_has() { # <container> <DN> |
| | | wait_until 60 "$2 is on $1" ldaps_has "$1" "$2" |
| | | wait_running "$1" 60 "$2 is on $1" ldaps_has "$1" "$2" |
| | | } |
| | | |
| | | admin_search() { # <container> <base DN> <scope> <filter> [<attribute>...] |
| | |
| | | docker exec "$1" cat /opt/opendj/data/.replication-role 2>/dev/null |
| | | } |
| | | |
| | | # no join.sh or replicate.sh runs in the container any more. A volume that holds the data |
| | | # reports itself healthy from the start while its join still runs, and the join keeps its |
| | | # password file until it ends. The bracket keeps the pattern from matching the command line |
| | | # of the sh that greps for it |
| | | # Health can precede the retained-volume join. Its wrapper records completion only |
| | | # after the child has exited (including its trap which removes the password file). |
| | | bootstrap_ended() { # <container> |
| | | ! docker exec "$1" sh -c "grep -qs -e 'bootstrap/[j]oin\.sh' -e 'bootstrap/[r]eplicate\.sh' /proc/[0-9]*/cmdline" |
| | | docker exec "$1" sh -c 'test ! -f "${BOOTSTRAP_FAILED:-/opt/opendj/.bootstrap-failed}" || exit 200; |
| | | test -f "${BOOTSTRAP_FINISHED:-/opt/opendj/.bootstrap-finished}"' |
| | | } |
| | | |
| | | # the writability-mode the backend of dc=example,dc=com is configured with, empty where its |
| | |
| | | local name=$1 peers=$2 |
| | | shift 2 |
| | | docker volume create "vol-$name" >/dev/null |
| | | docker run -d --memory="512m" --network $NETWORK --name "$name" --hostname "$name" \ |
| | | docker run -d --network $NETWORK --name "$name" --hostname "$name" \ |
| | | -v "vol-$name:/opt/opendj/data" \ |
| | | -e ROOT_PASSWORD="$ROOT_PASSWORD" -e ADD_BASE_ENTRY="--addBaseEntry" \ |
| | | -e OPENDJ_REPLICATION_TYPE=simple -e REPLICATION_PEERS="$peers" \ |
| | | -e REPLICATION_RETRY_COUNT=10 -e REPLICATION_RETRY_INTERVAL=3 -e REPLICATION_ATTEMPT_TIMEOUT=90 \ |
| | | -e JOIN_TIMING=1 -e REPLICATION_RETRY_COUNT=10 -e REPLICATION_RETRY_INTERVAL=3 -e REPLICATION_ATTEMPT_TIMEOUT=90 \ |
| | | "$@" "$IMAGE" >/dev/null |
| | | } |
| | | |
| | |
| | | # turn it healthy - and its backend stays held, since only a join lets the writes in again: |
| | | # the server says which backend that is |
| | | docker rm -f dj-0 >/dev/null |
| | | docker run -d --memory="512m" --network $NETWORK --name dj-0 --hostname dj-0 -v vol-dj-0:/opt/opendj/data \ |
| | | docker run -d --network $NETWORK --name dj-0 --hostname dj-0 -v vol-dj-0:/opt/opendj/data \ |
| | | -e ROOT_PASSWORD="$ROOT_PASSWORD" "$IMAGE" >/dev/null |
| | | wait_until 300 "dj-0 says that no join lets the writes in" logs_have dj-0 "The backend userRoot may still refuse the writes of clients" |
| | | wait_healthy dj-0 |
| | |
| | | wait_until 120 "dj-0 is healthy while dj-1 is down" is_healthy dj-0 |
| | | docker start dj-1 >/dev/null |
| | | wait_healthy dj-1 |
| | | # a member is healthy before its join runs: the role is recorded once the join found it a member |
| | | # A member can be healthy before its join checks membership and records the role. |
| | | wait_until 300 "the restarted dj-0 is a member again" logs_have_since dj-0 "Starting OpenDJ" "already a member of the replication topology" |
| | | wait_until 300 "the restarted dj-1 is a member again" logs_have_since dj-1 "Starting OpenDJ" "already a member of the replication topology" |
| | | [ "$(recorded_role_of dj-1)" = combined ] || fail "dj-1 was recorded $(recorded_role_of dj-1) from its combined replication configuration" |
| | | add_ou dj-1 replicated2 |
| | |
| | | # peer registers any more does that, or one that its own cn=admin data does not register, |
| | | # and a reset followed by a new enable passes every check above |
| | | for n in dj-0 dj-1; do |
| | | if logs_have $n "taking its replication configuration down"; then fail "$n reset its replication on a plain restart"; fi |
| | | assert_no_replication_reset "$n" |
| | | done |
| | | |
| | | phase "seed without a domain" |
| | |
| | | # are not its to remove |
| | | docker run -d --memory="64m" --ipc=shareable --name dj-shm --entrypoint sleep "$IMAGE" 600 >/dev/null |
| | | docker exec dj-shm sh -c ': >/dev/shm/opendj-join.4444.killed && : >/dev/shm/opendj-replicate.4444.killed && : >/dev/shm/opendj-join.5444.other' |
| | | docker run -d --memory="512m" --network $NETWORK --ipc=container:dj-shm --name dj-shm-probe --hostname dj-shm-probe \ |
| | | docker run -d --network $NETWORK --ipc=container:dj-shm --name dj-shm-probe --hostname dj-shm-probe \ |
| | | -e ROOT_PASSWORD="$ROOT_PASSWORD" "$IMAGE" >/dev/null |
| | | # the planted files only: the probe's own bootstrap keeps a password file of its ADMIN_PORT |
| | | # there while it runs |
| | |
| | | start_node dj-0 dj-0 |
| | | wait_healthy dj-0 |
| | | for n in dj-1 dj-2; do |
| | | wait_until 180 "$n leaves cn=admin data of dj-0" admin_data_lacks dj-0 $n |
| | | wait_until 120 "$n leaves the replication server lists of dj-0" lists_lack dj-0 $n |
| | | wait_running dj-0 180 "$n leaves cn=admin data of dj-0" admin_data_lacks dj-0 $n |
| | | wait_running dj-0 120 "$n leaves the replication server lists of dj-0" lists_lack dj-0 $n |
| | | done |
| | | hold_lock dj-0 |
| | | start_node dj-1 dj-0,dj-1,dj-2 -e REPLICATION_RETRY_COUNT=30 -e REPLICATION_ATTEMPT_TIMEOUT=1800 |
| | | dj1_rejoining() { [ "$(published_state dj-1)" = rejoining ]; } |
| | | wait_until 300 "dj-1 publishes that it is rejoining" dj1_rejoining |
| | | wait_running "dj-0 dj-1" 300 "dj-1 publishes that it is rejoining" dj1_rejoining |
| | | start_node dj-2 dj-0,dj-1,dj-2 -e REPLICATION_RETRY_COUNT=30 -e REPLICATION_ATTEMPT_TIMEOUT=1800 |
| | | wait_until 300 "dj-1 passes over the rejoining dj-2" logs_have dj-1 "dj-2 is rejoining, not a peer to join through" |
| | | wait_running "dj-0 dj-1 dj-2" 300 "dj-1 passes over the rejoining dj-2" logs_have dj-1 "dj-2 is rejoining, not a peer to join through" |
| | | drop_lock dj-2 |
| | | wait_until 180 "dj-2 passes over the rejoining dj-1" logs_have dj-2 "dj-1 is rejoining, not a peer to join through" |
| | | wait_running "dj-0 dj-1 dj-2" 180 "dj-2 passes over the rejoining dj-1" logs_have dj-2 "dj-1 is rejoining, not a peer to join through" |
| | | sleep 12 |
| | | for n in dj-1 dj-2; do |
| | | docker exec $n test ! -e /opt/opendj/.bootstrap-complete || fail "$n reports itself ready while its replication is down" |
| | |
| | | # their joins took the replication down, and the status turns unhealthy only after the |
| | | # probe's retries. Their joins publish them ready once the writes are let in again |
| | | for n in dj-1 dj-2; do |
| | | wait_until 480 "$n rejoins and publishes itself ready" published_ready $n |
| | | wait_running "dj-0 dj-1 dj-2" 480 "$n rejoins and publishes itself ready" published_ready $n |
| | | done |
| | | wait_healthy dj-1 |
| | | wait_healthy dj-2 |
| | | for n in dj-1 dj-2; do |
| | | wait_until 300 "$n registers with dj-0 again" registered_in_dj0 $n |
| | | wait_running "dj-0 dj-1 dj-2" 300 "$n registers with dj-0 again" registered_in_dj0 $n |
| | | done |
| | | [ "$(backend_mode dj-2)" = internal-only ] || fail "the rejoin of dj-2 let the writes of clients in on a backend the operator made read-only" |
| | | add_ou dj-1 rejoined-together |
| | |
| | | # off the network for as long instead would leave its replication server holding the dead |
| | | # connection of dj-0's own directory server, and route the initialize of the replica into it |
| | | docker network create $NETWORK_ALONE >/dev/null |
| | | docker run -d --memory="512m" --network $NETWORK_ALONE --name dj-sdsr --hostname dj-sdsr \ |
| | | docker run -d --network $NETWORK_ALONE --name dj-sdsr --hostname dj-sdsr \ |
| | | -e ROOT_PASSWORD="$ROOT_PASSWORD" -e MASTER_SERVER=dj-0 -e OPENDJ_REPLICATION_TYPE=sdsr "$IMAGE" >/dev/null |
| | | wait_until 420 "dj-sdsr tries again" logs_have dj-sdsr "exited with 8, trying again" |
| | | docker network connect $NETWORK dj-sdsr |
| | |
| | | # and a replica joins and initializes through that address |
| | | for n in dj-ipm dj-ipr; do |
| | | if [ $n = dj-ipm ]; then extra="--ip $MASTER_ADDRESS -e SAMPLE_DATA=10"; else extra="-v vol-dj-ipr:/opt/opendj/data"; fi |
| | | docker run -d --memory="512m" --network $NETWORK --name $n --hostname $n $extra \ |
| | | docker run -d --network $NETWORK --name $n --hostname $n $extra \ |
| | | -e ROOT_PASSWORD="$ROOT_PASSWORD" -e ADD_BASE_ENTRY="--addBaseEntry" \ |
| | | -e OPENDJ_REPLICATION_TYPE=simple -e MASTER_SERVER=$MASTER_ADDRESS \ |
| | | -e REPLICATION_RETRY_COUNT=10 -e REPLICATION_RETRY_INTERVAL=3 "$IMAGE" >/dev/null |
| | |
| | | # is registered by its address - in cn=admin data and in its replication server lists - |
| | | # rather than taking it for a server that left the topology |
| | | docker rm -f dj-ipr >/dev/null |
| | | docker run -d --memory="512m" --network $NETWORK --name dj-ipr --hostname dj-ipr -v vol-dj-ipr:/opt/opendj/data \ |
| | | docker run -d --network $NETWORK --name dj-ipr --hostname dj-ipr -v vol-dj-ipr:/opt/opendj/data \ |
| | | -e ROOT_PASSWORD="$ROOT_PASSWORD" -e OPENDJ_REPLICATION_TYPE=simple -e REPLICATION_PEERS=dj-ipm,dj-ipr \ |
| | | -e REPLICATION_RETRY_COUNT=2 -e REPLICATION_RETRY_INTERVAL=3 "$IMAGE" >/dev/null |
| | | wait_until 300 "the moved dj-ipr has looked for departed servers" logs_have dj-ipr "the health check may probe it" |
| | |
| | | docker restart $n >/dev/null |
| | | wait_until 300 "the restarted $n is a member again" logs_have_since $n "Starting OpenDJ" "already a member of the replication topology" |
| | | wait_healthy $n |
| | | if logs_have $n "taking its replication configuration down"; then fail "$n reset its replication on a plain restart"; fi |
| | | assert_no_replication_reset "$n" |
| | | done |
| | | roles_hold |
| | | phase "roles: role-less volumes" |
| | |
| | | || { echo "::error::$n holds other data than $first, see diff/$n.ldif"; failed=1; } |
| | | done |
| | | assert_changelogs || failed=1 |
| | | [ -z "$failed" ] || fail "the replicas do not hold the same data" |
| | | [ -z "$failed" ] || fail "the offline checks failed" |
| | | } |
| | | |
| | | # The changes of every replica in the changelog of every replication server, one after the |
| | | # other: a gap in the sequence numbers of a replica's changes during the load is a change that |
| | | # reached no replication server. The data shows it only while no later change of the same |
| | | # attribute overwrites it, and missing-changes never (#1195). docker cp streams the changelog |
| | | # other: a gap in the sequence numbers may indicate a lost change, an offline message, or |
| | | # history that cannot be reconstructed on an empty RS. Missing-changes alone cannot prove |
| | | # which happened (#1195). docker cp streams the changelog |
| | | # out of the stopped container; changelog-gaps.py reads it |
| | | assert_changelogs() { |
| | | local n id code failed= |
| | | local -a evidence=() |
| | | case ${DISTURBANCE:-none} in |
| | | scale-*) evidence=(--offline-snapshots "$OUT/scale-checkpoint") ;; |
| | | esac |
| | | # A failed copy must not authorize evidence left by an earlier snapshot. The checker |
| | | # validates the complete traces again rather than trusting the human-readable report. |
| | | if [ "${CSN_TRACES_COMPLETE:-0}" = 1 ]; then |
| | | evidence+=(--csn-traces "$OUT/csn-traces" --csn-manifest "$OUT/csn-trace-expected.txt") |
| | | fi |
| | | mkdir -p "$OUT/changelog" |
| | | for n in $RS_NODES; do |
| | | code=0 |
| | | docker cp "$n:/opt/opendj/data/changelogDb" - \ |
| | | | python3 -I "$HERE/changelog-gaps.py" "$BASE_DN" "$LOAD_START_MS" "$LOAD_END_MS" \ |
| | | | python3 -I "$HERE/changelog-gaps.py" "$BASE_DN" "$LOAD_START_MS" "$LOAD_END_MS" "${evidence[@]}" \ |
| | | | awk 'FILENAME == ARGV[1] { name[$1] = $2; next } |
| | | $1 == "replica" { id = $2; sub(/:$/, "", id); if (id in name) $2 = id " (" name[id] "):" } |
| | | { print }' "$OUT/server-ids.txt" - >"$OUT/changelog/$n.txt" || code=$? |
| | | case $code in |
| | | 0) ;; |
| | | 1) echo "::error::changes of the load are missing from the changelog of $n, see changelog/$n.txt"; failed=1 ;; |
| | | 1) echo "::error::sequence numbers of the load are missing from the changelog of $n, see changelog/$n.txt"; failed=1 ;; |
| | | *) echo "::error::the changelog of $n could not be read, see changelog/$n.txt"; failed=1; continue ;; |
| | | esac |
| | | # every directory server made changes in the load: a changelog whose records the script |
| | |
| | | # (objectClass=inetOrgPerson) over the seeded users did - so unindexed_searches checks that |
| | | # each search went through the index |
| | | INDEXED_FILTERS="(sn=AddRate) (sn=Diverged)" |
| | | case ${DISTURBANCE:-none} in |
| | | scale-*) |
| | | INDEXED_FILTERS="(sn=Diverged)" |
| | | for n in $DS_NODES; do |
| | | for shard in 1 2 3; do INDEXED_FILTERS="$INDEXED_FILTERS (sn=AddRate-$n-$shard)"; done |
| | | done |
| | | ;; |
| | | esac |
| | | |
| | | # The searches of INDEXED_FILTERS a directory server ran without an index, or that its access |
| | | # log does not hold, as errors. Every access log file is read: the load rotates them |
| | | # log does not hold, as errors. Read rotated logs in chronological order, then the active log: |
| | | # connection and operation numbers can be reused after a server restart. |
| | | unindexed_searches() { # <node> |
| | | docker exec $1 sh -c 'grep -h " SEARCH " /opt/opendj/data/logs/access*; [ $? -le 1 ]' \ |
| | | docker exec $1 sh -c 'for file in /opt/opendj/data/logs/access.[0-9]* /opt/opendj/data/logs/access; do |
| | | [ -f "$file" ] || continue |
| | | grep -h " SEARCH " "$file"; status=$? |
| | | [ "$status" -le 1 ] || exit "$status" |
| | | done' \ |
| | | | awk -v node=$1 -v base="$BASE_DN" -v filters="$INDEXED_FILTERS" ' |
| | | BEGIN { n = split(filters, f, " ") } |
| | | $3 == "SEARCH" && $4 == "REQ" && index($0, " base=\"" base "\" scope=sub ") { |
| | | for (i = 1; i <= n; i++) if (index($0, " filter=\"" f[i] "\" ")) req[$5 " " $6] = f[i] |
| | | $3 == "SEARCH" && $4 == "REQ" { |
| | | key = $5 " " $6 |
| | | delete req[key] |
| | | if (index($0, " base=\"" base "\" scope=sub ")) |
| | | for (i = 1; i <= n; i++) if (index($0, " filter=\"" f[i] "\" ")) { |
| | | req[key] = f[i]; seen[f[i]] = 1 |
| | | } |
| | | } |
| | | $3 == "SEARCH" && $4 == "RES" && / unindexed( |$)/ { unindexed[$5 " " $6] = 1 } |
| | | $3 == "SEARCH" && $4 == "RES" { |
| | | key = $5 " " $6 |
| | | if (key in req && / unindexed( |$)/) printf "::error::%s ran %s without an index\n", node, req[key] |
| | | delete req[key] |
| | | } |
| | | END { |
| | | for (k in req) { seen[req[k]] = 1; if (k in unindexed) printf "::error::%s ran %s without an index\n", node, req[k] } |
| | | for (i = 1; i <= n; i++) if (!(f[i] in seen)) printf "::error::the access log of %s holds no search of %s\n", node, f[i] |
| | | }' |
| | | } |
| | |
| | | # replication errors of their own while the servers come up one after the other, and only what |
| | | # follows is the run's. A log that cannot be read fails the run: a cat that fails in a pipe |
| | | # would count 0 lines and exit 0, and window_open would take that for a window from the first |
| | | # line, while a redirect that fails ends sh with 2 |
| | | # line, while a redirect that fails ends sh with 2. A replacement RS retains its previous log |
| | | # as a prefix on the host so that marks and windows cover both volumes. |
| | | errors_lines() { # <node> |
| | | docker exec $1 sh -c 'wc -l </opt/opendj/data/logs/errors' |
| | | local current previous=0 |
| | | # A scale-in captures the stopped node before removing its container. Its log cannot |
| | | # change until it starts again, but the other nodes still open and close windows. |
| | | if [ -f "$OUT/logs/$1.offline" ]; then |
| | | cat "$OUT/logs/$1.offline" |
| | | return |
| | | fi |
| | | current=$(docker exec "$1" sh -c 'wc -l </opt/opendj/data/logs/errors') || return 1 |
| | | if [ -f "$OUT/logs/$1.previous" ]; then |
| | | previous=$(wc -l <"$OUT/logs/$1.previous") || return 1 |
| | | fi |
| | | echo $((previous + current)) |
| | | } |
| | | |
| | | mark_logs() { |
| | |
| | | } |
| | | |
| | | since_mark() { # <node> |
| | | docker exec $1 tail -n +$(($(cat "$OUT/logs/$1.mark") + 1)) /opt/opendj/data/logs/errors |
| | | local first=$(($(cat "$OUT/logs/$1.mark") + 1)) |
| | | if [ -f "$OUT/logs/$1.previous" ]; then |
| | | { cat "$OUT/logs/$1.previous" || exit 1; docker exec "$1" tail -n +1 /opt/opendj/data/logs/errors; } | tail -n +"$first" |
| | | else |
| | | docker exec "$1" tail -n +"$first" /opt/opendj/data/logs/errors |
| | | fi |
| | | } |
| | | |
| | | # A disturbance window over the errors log of every server (#1208): window_open before the |
| | | # disturbance, with the msgIDs of the errors it expects besides the failed handshakes, |
| | | # or dns:<hostname> for ERROR 51 naming exactly that temporarily unavailable host, |
| | | # window_close once the disturbed server serves again, a line "<lines before> <lines after> |
| | | # [<msgID>|dns:<hostname>...]" in logs/<node>.windows |
| | | window_open() { # [<msgID>|dns:<hostname>...] |
| | | local n lines |
| | | # dns:<hostname> for ERROR 51 naming exactly that temporarily unavailable host, or |
| | | # cert:<DS>:<RS> for that DS's transient bad-certificate handshake with the rebuilt RS, or |
| | | # cert-peer:<RS>:<DS IP> for the corresponding RS-side warning after the DS restarts. |
| | | # scale-cert-return keeps the certificate window for RS312/313. The scale |
| | | # disturbance separately records exact DS119 and RS105 lines after proving recovery. |
| | | # timeout:<DS>:<RS> is recorded on one startup error line only after that DS reconnects to |
| | | # that RS in the same domain, as confirmed by scale_record_reconnected_timeouts. |
| | | # window_close records "<lines before> <lines after> [<allowance>...]" in logs/<node>.windows. |
| | | window_open() { window_open_key '' "$@"; } |
| | | window_close() { window_close_key ''; } |
| | | |
| | | # Separate keys permit overlapping joins while retaining the exact window for each node. |
| | | window_open_key() { # <key> [<msgID>|dns:<hostname>...] |
| | | local key=$1 n lines file |
| | | shift |
| | | case $key in *[!a-zA-Z0-9_-]*) return 1 ;; esac |
| | | for n in $ALL_NODES; do |
| | | # an assignment, so that a log that cannot be read stops the run here as well |
| | | lines=$(errors_lines $n) |
| | | echo "$lines${*:+ $*}" >"$OUT/logs/$n.window" |
| | | file="$OUT/logs/$n.window${key:+-$key}" |
| | | [ ! -e "$file" ] || return 1 |
| | | lines=$(errors_lines "$n") || return 1 |
| | | echo "$lines${*:+ $*}" >"$file" || return 1 |
| | | done |
| | | } |
| | | |
| | | window_close() { |
| | | local n lines before ids |
| | | window_close_key() { # <key> |
| | | local key=$1 n lines before ids file |
| | | case $key in *[!a-zA-Z0-9_-]*) return 1 ;; esac |
| | | for n in $ALL_NODES; do |
| | | lines=$(errors_lines $n) |
| | | read -r before ids <"$OUT/logs/$n.window" |
| | | echo "$before $lines${ids:+ $ids}" >>"$OUT/logs/$n.windows" |
| | | rm "$OUT/logs/$n.window" |
| | | file="$OUT/logs/$n.window${key:+-$key}" |
| | | lines=$(errors_lines "$n") || return 1 |
| | | read -r before ids <"$file" || return 1 |
| | | echo "$before $lines${ids:+ $ids}" >>"$OUT/logs/$n.windows" || return 1 |
| | | rm "$file" || return 1 |
| | | done |
| | | } |
| | | |
| | | # A server removed during a scale-in has no Docker DNS name between individual rolling |
| | | # windows. Allow only that hostname for this whole interval, not other handshake failures. |
| | | dns_window_open() { # <hostname> |
| | | local n lines |
| | | for n in $ALL_NODES; do |
| | | lines=$(errors_lines "$n") || return 1 |
| | | printf '%s %s\n' "$lines" "$1" >"$OUT/logs/$n.dns-window" || return 1 |
| | | done |
| | | } |
| | | |
| | | dns_window_close() { |
| | | local n lines before host |
| | | for n in $ALL_NODES; do |
| | | lines=$(errors_lines "$n") || return 1 |
| | | read -r before host <"$OUT/logs/$n.dns-window" || return 1 |
| | | printf '%s %s dns-only dns:%s\n' "$before" "$lines" "$host" >>"$OUT/logs/$n.windows" || return 1 |
| | | rm "$OUT/logs/$n.dns-window" || return 1 |
| | | done |
| | | } |
| | | |
| | |
| | | # msgIDs as well. A dns:<hostname> token expects only ERROR 51's exact resolution-failure |
| | | # message for that hostname, not other DNS errors inside the window. This covers the stopped |
| | | # RS container's name temporarily disappearing during kill-rs, restart-rs or a combined |
| | | # kill-ds or restart-ds. DS-only crashes and restarts pass no DNS token, and other hosts remain |
| | | # errors. |
| | | # kill-ds or restart-ds. The certificate allowance is limited to the named DS and rebuilt RS; |
| | | # its later forced connection to that RS must succeed. Other hosts and DS remain errors. |
| | | # The other allowances cover what one disturbance leaves behind besides the handshakes, such |
| | | # as the connections a killed replication server breaks (disturb-kill-rs.sh), which a window of |
| | | # another one does not expect. Those go to logs/<node>.expected; outside a window, and anything |
| | |
| | | local windows= |
| | | [ ! -f "$OUT/logs/$1.windows" ] || windows=$(tr '\n' ';' <"$OUT/logs/$1.windows") |
| | | since_mark $1 | awk -v first=$(($(cat "$OUT/logs/$1.mark") + 1)) -v windows="$windows" \ |
| | | -v expected="$OUT/logs/$1.expected" ' |
| | | -v expected="$OUT/logs/$1.expected" -v node="$1" -v base_dn="$BASE_DN" \ |
| | | -v startup_timeouts="$OUT/logs/$1.startup-timeouts" \ |
| | | -v scale_certificates="$OUT/logs/scale-certificates" ' |
| | | BEGIN { |
| | | while ((getline proof < startup_timeouts) > 0) { |
| | | separator = index(proof, "\t") |
| | | if (separator > 1) startup[substr(proof, 1, separator - 1)] = substr(proof, separator + 1) |
| | | } |
| | | close(startup_timeouts) |
| | | while ((getline proof < scale_certificates) > 0) { |
| | | separator = index(proof, "\t") |
| | | if (substr(proof, 1, separator - 1) != node) continue |
| | | proof = substr(proof, separator + 1) |
| | | separator = index(proof, "\t") |
| | | if (separator > 1) scale_cert[substr(proof, 1, separator - 1)] = substr(proof, separator + 1) |
| | | } |
| | | close(scale_certificates) |
| | | n = split(windows, w, ";") |
| | | for (i = 1; i <= n; i++) { |
| | | k = split(w[i], f, " ") |
| | |
| | | for (j = 3; j <= k; j++) ids[i] = ids[i] f[j] " " |
| | | } |
| | | } |
| | | /category=SYNC severity=NOTICE msgID=313 msg=Replication server RS\([0-9]+\) connected to replication server / { |
| | | recovery = substr($0, index($0, " msg=") + 5) |
| | | sub(/, which it had reported it had no replication session with$/, "", recovery) |
| | | line = first + NR - 1 |
| | | for (p in pendingCert) { |
| | | split(p, position, SUBSEP) |
| | | if (line <= to[position[1]] + 0 && recovery == pendingCert[p]) { |
| | | allowed[position[2]] = 1 |
| | | delete pendingCert[p] |
| | | } |
| | | } |
| | | } |
| | | !/category=SYNC severity=ERROR|SSLHandshakeException|bad_certificate/ { next } |
| | | { |
| | | records[NR] = $0; order[++recordCount] = NR |
| | | line = first + NR - 1 |
| | | handshake = /category=SYNC severity=ERROR msgID=(145|178|179) / \ |
| | | || /category=SYNC severity=WARNING .*SSLHandshakeException\(Remote host terminated the handshake\)/ |
| | |
| | | dns = " dns:" parts[3] " " |
| | | } |
| | | } |
| | | for (i = 1; i <= n; i++) |
| | | for (i = 1; i <= n; i++) { |
| | | scale_return = index(ids[i], " scale-cert-return ") |
| | | cert = scale_return && scale_cert[line] == $0 && /category=SYNC severity=WARNING msgID=(105|119) / |
| | | timeout = disconnect = 0 |
| | | if (id == "180" && index($0, "msg=Directory server DS(") \ |
| | | && index($0, " changes for domain \"" base_dn "\" from replication server RS(")) { |
| | | count = split(ids[i], tokens, " ") |
| | | for (j = 1; j <= count; j++) { |
| | | if (split(tokens[j], part, ":") == 3 && part[1] == "disconnect" && part[2] == node \ |
| | | && index($0, ") at " part[3] ":8989. The connection will be closed,")) disconnect = 1 |
| | | } |
| | | } |
| | | if (id == "212" && index($0, "msg=Directory server DS(")) { |
| | | if (index(ids[i], " startup-timeout:" node " ") && startup[line] == $0) timeout = 1 |
| | | count = split(ids[i], tokens, " ") |
| | | for (j = 1; j <= count; j++) { |
| | | if (split(tokens[j], part, ":") == 3 && part[1] == "timeout" && part[2] == node \ |
| | | && index($0, " timed out while connecting to replication server " part[3] ":8989 for domain \"" base_dn "\"")) timeout = 1 |
| | | } |
| | | } |
| | | if (!scale_return \ |
| | | && /category=SYNC severity=WARNING msgID=119 / && /SSLHandshakeException/ && /bad_certificate/) { |
| | | count = split(ids[i], tokens, " ") |
| | | for (j = 1; j <= count; j++) { |
| | | if (split(tokens[j], part, ":") == 3 && part[1] == "cert" && part[2] == node \ |
| | | && index($0, " connecting to replication server " part[3] ":8989 for domain ")) cert = 1 |
| | | } |
| | | } |
| | | if (line > from[i] + 0 && line <= to[i] + 0 \ |
| | | && (handshake || index(ids[i], " " id " ") || (dns != "" && index(ids[i], dns)))) { |
| | | print >expected |
| | | && /category=SYNC severity=WARNING msgID=312 msg=Replication server RS\([0-9]+\) could not connect to replication server / \ |
| | | && /: SSLHandshakeException\(\(bad_certificate\)/) { |
| | | count = split(ids[i], tokens, " ") |
| | | for (j = 1; j <= count; j++) { |
| | | if (split(tokens[j], part, ":") == 3 && part[1] == "cert" && part[2] == node \ |
| | | && index($0, " connect to replication server " part[3] ":8989 for domain ")) { |
| | | recovery = substr($0, index($0, " msg=") + 5) |
| | | sub(/: SSLHandshakeException.*/, "", recovery) |
| | | sub(/ could not connect to /, " connected to ", recovery) |
| | | pendingCert[i, NR] = recovery |
| | | } |
| | | } |
| | | } |
| | | if (!scale_return && /category=SYNC severity=WARNING msgID=105 / \ |
| | | && /The error was: (\(bad_certificate\) )?Received fatal alert: bad_certificate$/) { |
| | | count = split(ids[i], tokens, " ") |
| | | for (j = 1; j <= count; j++) { |
| | | if (split(tokens[j], part, ":") != 3 || part[1] != "cert-peer" || part[2] != node) continue |
| | | if (split($0, sides, " from ") != 2 || split(sides[2], ends, " to local address ") != 2) continue |
| | | if (split(ends[1], remote, ":") != 2 || remote[2] !~ /^[0-9]+$/) continue |
| | | suffix = "/" part[3] |
| | | if (length(remote[1]) >= length(suffix) \ |
| | | && substr(remote[1], length(remote[1]) - length(suffix) + 1) == suffix) cert = 1 |
| | | } |
| | | } |
| | | if (line > from[i] + 0 && line <= to[i] + 0 \ |
| | | && ((handshake && !index(ids[i], " dns-only ")) || cert || timeout || disconnect || index(ids[i], " " id " ") || (dns != "" && index(ids[i], dns)))) { |
| | | allowed[NR] = 1 |
| | | next |
| | | } |
| | | print |
| | | } |
| | | } |
| | | END { |
| | | for (r = 1; r <= recordCount; r++) { |
| | | line = order[r] |
| | | if (allowed[line]) print records[line] >expected |
| | | else print records[line] |
| | | } |
| | | }' |
| | | } |
| | | |
| | |
| | | [ -z "$lines" ] || { printf '%s\n' "$lines" >"$OUT/logs/$n.errors"; echo "::error::$n logged replication errors, see logs/$n.errors"; failed=1; } |
| | | done |
| | | assert_rs_mesh || failed=1 |
| | | [ -z "$failed" ] || fail "the replicas do not answer the same" |
| | | [ -z "$failed" ] || fail "the online checks failed" |
| | | } |
| New file |
| | |
| | | # |
| | | # 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. |
| | | |
| | | """Compare RS changelog positions, not the periodically cached missing-changes monitor. |
| | | |
| | | Usage: changelog-checkpoint.py <base DN> <server-ids.txt> <reference.ldif> <current.ldif> |
| | | The LDAP snapshots contain replicationServer-database, domain-name and last-change from |
| | | FileReplicaDB's monitors. Each (domain, originating DS) has its own position. Exit 0 once |
| | | current reaches every reference position, 1 while behind, and 2 for unusable input. |
| | | This checks positions, not holes below them; the final changelog/data checks remain necessary. |
| | | """ |
| | | |
| | | import base64 |
| | | from pathlib import Path |
| | | import re |
| | | import sys |
| | | |
| | | |
| | | def changelog_positions(path): |
| | | # Unfold before decoding: ldapsearch may wrap a CSN or a base64 domain name. |
| | | lines = [] |
| | | for line in Path(path).read_text().splitlines(): |
| | | if line.startswith(" "): |
| | | if not lines or not lines[-1]: |
| | | raise ValueError("orphan LDIF continuation in " + path) |
| | | lines[-1] += line[1:] |
| | | else: |
| | | lines.append(line) |
| | | positions, seen, attributes = {}, set(), {} |
| | | for line in lines + [""]: |
| | | if line.startswith("#") or line == "version: 1": |
| | | continue |
| | | if line: |
| | | name, separator, value = line.partition(":") |
| | | name = name.lower() |
| | | if not separator or name in attributes or value.startswith("<"): |
| | | raise ValueError("invalid or duplicate LDIF attribute in " + path) |
| | | if value.startswith(":"): |
| | | value = base64.b64decode(value[1:].strip(), validate=True).decode("utf-8") |
| | | else: |
| | | value = value.lstrip(" ") |
| | | attributes[name] = value |
| | | elif attributes: |
| | | domain = attributes.get("domain-name", "").lower() |
| | | replica = attributes.get("replicationserver-database", "") |
| | | if not domain or not re.fullmatch(r"[0-9]+", replica) or not attributes.get("dn"): |
| | | raise ValueError("incomplete changelog monitor entry in " + path) |
| | | key = (domain, int(replica)) |
| | | if key in seen: |
| | | raise ValueError("duplicate changelog monitor entry in " + path) |
| | | seen.add(key) |
| | | if "last-change" in attributes: |
| | | value = attributes["last-change"].split() |
| | | csn = value[0].lower() if value else "" |
| | | if not re.fullmatch(r"[0-9a-f]{28}", csn) or int(csn[16:20], 16) != key[1]: |
| | | raise ValueError("invalid last-change for %s DS(%s)" % key) |
| | | positions[key] = csn |
| | | attributes = {} |
| | | return positions |
| | | |
| | | |
| | | def position(csn): |
| | | # CSN.compare orders by timestamp, then the signed sequence number, then origin. |
| | | # The origin is already the map key. Avoid float conversion of the 64-bit timestamp. |
| | | sequence = int(csn[20:28], 16) |
| | | return int(csn[:16], 16), sequence if sequence < 2**31 else sequence - 2**32 |
| | | |
| | | |
| | | def main(argv): |
| | | if len(argv) != 5: |
| | | print(__doc__, file=sys.stderr) |
| | | return 2 |
| | | base, ids_path, reference_path, current_path = argv[1:] |
| | | try: |
| | | ids = [line.split()[0] for line in Path(ids_path).read_text().splitlines() if line.strip()] |
| | | if not ids or any(not re.fullmatch(r"[0-9]+", replica) for replica in ids): |
| | | raise ValueError("missing or invalid workload server IDs") |
| | | reference = changelog_positions(reference_path) |
| | | current = changelog_positions(current_path) |
| | | for replica in ids: |
| | | if (base.lower(), int(replica)) not in reference: |
| | | raise ValueError("reference lacks a workload position for %s DS(%s)" % (base, replica)) |
| | | behind = False |
| | | for (domain, replica), wanted in sorted(reference.items()): |
| | | actual = current.get((domain, replica)) |
| | | if actual is None or position(actual) < position(wanted): |
| | | print("%s DS(%s): needs %s, has %s" % (domain, replica, wanted, actual or "no position")) |
| | | behind = True |
| | | return 1 if behind else 0 |
| | | except (OSError, ValueError) as error: |
| | | print(str(error), file=sys.stderr) |
| | | return 2 |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | sys.exit(main(sys.argv)) |
| | |
| | | """Finds the changes a replication server's changelog lacks (#1090, #1195). |
| | | |
| | | A directory server numbers the changes it makes one after the other: CSNGenerator.newCSN() |
| | | adds one to the sequence number of the CSN for every change, whatever its time. So the |
| | | changes of one replica in a changelog have no gap in their sequence numbers unless a change |
| | | was never published - an operation that failed after it had its CSN, or one that was lost on |
| | | its way to the replication servers. During the load of the convergence run no operation fails |
| | | (load.sh checks that), so a gap there is a lost change: a change the data of the other |
| | | replicas misses, while their ServerState and missing-changes say nothing, since both only |
| | | know the newest CSN. |
| | | adds one to the sequence number of the CSN for every change, whatever its time. A gap can |
| | | indicate an unpublished or lost change, but does not prove data loss: an offline message also |
| | | consumes a sequence number, and a replica recovering an empty RS from historical information |
| | | can reconstruct only changes whose values have not since been replaced. The convergence run |
| | | checks every RS so gaps can be investigated alongside replica data and logs. |
| | | |
| | | Usage: changelog-gaps.py <base DN> <from ms> <to ms> [<changelogDb directory>] |
| | | [--offline-snapshots <directory>] |
| | | |
| | | Without a directory it reads the changelogDb as a tar stream on its standard input, as |
| | | "docker cp <container>:/opt/opendj/data/changelogDb -" writes it. It reports, for every |
| | | replica of the domain of <base DN>, the changes whose CSN time is between <from ms> and |
| | | <to ms>, and the sequence numbers missing between them. Exit code 1: a change is missing; |
| | | 2: the changelog cannot be read (no such domain, or it is encrypted). |
| | | <to ms>, and the sequence numbers missing between them. Captured offline states can identify an |
| | | offline message with the same replica and sequence. They do not prove that an update did not later |
| | | reuse the sequence after a restart: CSN time is logical and can be ahead of the real clock. The |
| | | matching offline message is reported for investigation, and the gap remains an error. With |
| | | --csn-traces and --csn-manifest, all expected process traces must validate. Only a sequence |
| | | allocated exclusively to offline messages in this domain, with no local allocation in any |
| | | generation (even outside the load window), is classified as offline-only. Exit code 1: |
| | | a sequence number is missing; |
| | | 2: the arguments or changelog cannot be read (no such domain, or it is encrypted). |
| | | |
| | | What it cannot tell. A change lost at either end of a replica's changes in the window - its |
| | | last ones, or its first ones when no earlier change of the replica is in the changelog - leaves |
| | | no gap between two changes that are there; the data of the other replicas shows such a change |
| | | unless a later change of another server overwrites it. |
| | | |
| | | A restart leaves no gap of its own. A directory server that stops numbers its ReplicaOfflineMsg |
| | | A server restart need not leave a gap. A directory server that stops numbers its ReplicaOfflineMsg |
| | | like a change, and no log file holds the message - only the offline.state of the replica, the |
| | | newest one. But the message does not enter the ServerState of the replica |
| | | (ReplicaOfflineMsg.contributesToDomainState()), from whose newest change of its own the server |
| | | numbers again once it starts (CSNGenerator), so its first change after the restart takes the |
| | | sequence number of the message again, at a later time: the changes of the restarted server had |
| | | no gap in run 39834888428 (#1208). A gap around a restart is a lost change, the kind #1195 lost. |
| | | no gap in run 39834888428 (#1208). A service restart within a server process can behave differently. |
| | | |
| | | The file format is the one of FileReplicaDB: every log file is cut into blocks of 256 bytes, |
| | | and every block after the first starts with a 4-byte offset (BlockLogWriter); in between, a |
| | |
| | | import re |
| | | import sys |
| | | import tarfile |
| | | import argparse |
| | | import runpy |
| | | from pathlib import Path |
| | | |
| | | BLOCK_SIZE = 256 |
| | | SIZE_OF_BLOCK_OFFSET = 4 |
| | |
| | | yield member.name, tar.extractfile(member).read() |
| | | |
| | | |
| | | def offline_evidence(directory, base_dn): |
| | | """Read offline CSNs and snapshot times; a matching sequence is diagnostic only.""" |
| | | try: |
| | | evidence = {} |
| | | for path in Path(directory).glob('offline-*.txt'): |
| | | lines = path.read_text().splitlines() |
| | | captures = [int(line.split()[1]) for line in lines if line.startswith('capture-start-ms ')] |
| | | if len(captures) != 1: |
| | | continue |
| | | domains = {} |
| | | for line in lines: |
| | | if match := re.fullmatch(r'(\d+):\s*(.+)', line): |
| | | domains[match.group(1)] = match.group(2).strip().lower() |
| | | for line in lines: |
| | | match = re.fullmatch(r'(\d+)\.dom/(\d+)\.server/offline\.state ([0-9a-f]{28})', line) |
| | | if not match or domains.get(match.group(1)) != base_dn: |
| | | continue |
| | | sid, csn = int(match.group(2)), match.group(3) |
| | | if int(csn[16:20], 16) != sid: |
| | | continue |
| | | seq, time = int(csn[20:], 16), int(csn[:16], 16) |
| | | evidence.setdefault((sid, seq), []).append((time, captures[0], csn)) |
| | | return evidence |
| | | except (OSError, ValueError, IndexError): |
| | | return {} |
| | | |
| | | |
| | | def offline_matches(evidence, sid, seq, previous, following): |
| | | matches = set() |
| | | for time, captured, csn in evidence.get((sid, seq), []): |
| | | if previous[1] <= time <= following[1] < captured: |
| | | matches.add(csn) |
| | | return sorted(matches) |
| | | |
| | | |
| | | def main(argv): |
| | | if len(argv) not in (4, 5): |
| | | sys.stderr.write(__doc__) |
| | | return 2 |
| | | base_dn, start, end = argv[1].lower(), int(argv[2]), int(argv[3]) |
| | | entries = from_directory(argv[4]) if len(argv) == 5 else from_tar(sys.stdin.buffer) |
| | | parser = argparse.ArgumentParser(description=__doc__) |
| | | parser.add_argument('base_dn') |
| | | parser.add_argument('start', type=int) |
| | | parser.add_argument('end', type=int) |
| | | parser.add_argument('directory', nargs='?') |
| | | parser.add_argument('--offline-snapshots') |
| | | parser.add_argument('--csn-traces') |
| | | parser.add_argument('--csn-manifest') |
| | | args = parser.parse_args(argv[1:]) |
| | | if bool(args.csn_traces) != bool(args.csn_manifest): |
| | | parser.error('--csn-traces and --csn-manifest must be supplied together') |
| | | base_dn, start, end = args.base_dn.lower(), args.start, args.end |
| | | entries = from_directory(args.directory) if args.directory else from_tar(sys.stdin.buffer) |
| | | evidence = {} |
| | | if args.offline_snapshots: |
| | | evidence = offline_evidence(args.offline_snapshots, base_dn) |
| | | try: |
| | | domains, changes = read_changelog(entries) |
| | | except EncryptedChangelog as e: |
| | |
| | | if base_dn not in domains: |
| | | print("no domain %s in the changelog, which holds %s" % (base_dn, sorted(domains))) |
| | | return 2 |
| | | lost = False |
| | | loads = {} |
| | | for (domain_id, server_id), found in sorted(changes.items()): |
| | | if domain_id != domains[base_dn]: |
| | | continue |
| | | load = sorted((seqnum, time, kind) for seqnum, time, kind in found if start <= time <= end) |
| | | if not load: |
| | | continue |
| | | if load: |
| | | loads[server_id] = load |
| | | offline_only = {} |
| | | if args.csn_traces: |
| | | wanted = {(sid, seq) for sid, load in loads.items() |
| | | for previous, following in zip(load, load[1:]) |
| | | for seq in range(previous[0] + 1, following[0])} |
| | | trace = runpy.run_path(str(Path(__file__).with_name('csn-trace.py'))) |
| | | try: |
| | | events = trace['read_traces'](args.csn_traces, args.csn_manifest, wanted) |
| | | except ValueError as exc: |
| | | print('incomplete CSN allocation trace: %s' % exc) |
| | | return 2 |
| | | local = set() |
| | | for kind, domain, csn, _, _ in events: |
| | | if domain.strip().lower() != base_dn: |
| | | continue |
| | | pair = (int(csn[16:20], 16), int(csn[20:], 16)) |
| | | if kind == 'L': |
| | | local.add(pair) |
| | | else: |
| | | offline_only.setdefault(pair, set()).add(csn) |
| | | for pair in local: |
| | | offline_only.pop(pair, None) |
| | | lost = False |
| | | for server_id, load in loads.items(): |
| | | seqnums = [seqnum for seqnum, _, _ in load] |
| | | missing = [] |
| | | offline = {} |
| | | for previous, following in zip(load, load[1:]): |
| | | missing += [(seqnum, previous, following) for seqnum in range(previous[0] + 1, following[0])] |
| | | for seqnum in range(previous[0] + 1, following[0]): |
| | | if (server_id, seqnum) in offline_only: |
| | | continue |
| | | missing.append((seqnum, previous, following)) |
| | | matched = offline_matches(evidence, server_id, seqnum, previous, following) |
| | | if matched: |
| | | offline[seqnum] = matched |
| | | print("replica %d: %d changes in the load, sequence numbers %d to %d, %d missing" |
| | | % (server_id, len(load), seqnums[0], seqnums[-1], len(missing))) |
| | | for (sid, seqnum), csns in sorted(offline_only.items()): |
| | | if sid == server_id: |
| | | print(' offline-only %d: CSN %s; complete traces contain no local allocation' |
| | | % (seqnum, ', '.join(sorted(csns)))) |
| | | for seqnum, csns in sorted(offline.items()): |
| | | print(" offline %d: captured CSN %s; a restart may have reused the sequence" % (seqnum, ', '.join(csns))) |
| | | for seqnum, previous, following in missing[:20]: |
| | | print(" missing %d, between the %s %d (%d) and the %s %d (%d)" |
| | | % (seqnum, previous[2], previous[0], previous[1], following[2], following[0], following[1])) |
| | |
| | | # every run, and the state of every server of a failed one - what #534 could not get from its |
| | | # reporter. |
| | | |
| | | # Trace files are unique to a server process. Copy the departing combined server before its |
| | | # empty-volume replacement, and every directory server after the final stop. A missing file or |
| | | # unsuccessful copy is an error; the validator also checks every expected process generation. |
| | | capture_csn_trace() { # <directory server> |
| | | [ "${CSN_TRACE:-0}" = 1 ] || return 0 |
| | | mkdir -p "$OUT/csn-traces/$1" || return 1 |
| | | docker cp "$1:/opt/opendj/data/csn-trace/." "$OUT/csn-traces/$1/" || return 1 |
| | | } |
| | | |
| | | expect_csn_trace_restart() { # <directory server whose container is restarted> |
| | | local token next file |
| | | [ "${CSN_TRACE:-0}" = 1 ] || return 0 |
| | | token=$(cat "$OUT/csn-trace-tokens/$1") || return 1 |
| | | next=$(python3 -c 'import uuid; print(uuid.uuid4().hex)') || return 1 |
| | | file="$OUT/csn-trace-tokens/$1.restart" |
| | | printf '%s\n' "$next" >"$file" || return 1 |
| | | # docker cp creates a root-owned file; the unprivileged server must read it. |
| | | chmod 644 "$file" || return 1 |
| | | docker cp "$file" "$1:/opt/opendj/data/csn-trace-token-$token" || return 1 |
| | | printf '%s %s\n' "$1" "$next" >>"$OUT/csn-trace-expected.txt" |
| | | } |
| | | |
| | | check_csn_traces() { |
| | | local node failed= |
| | | CSN_TRACES_COMPLETE=0 |
| | | [ "${CSN_TRACE:-0}" = 1 ] || return 0 |
| | | for node in $DS_NODES; do |
| | | capture_csn_trace "$node" || failed=1 |
| | | done |
| | | if [ -n "$failed" ]; then |
| | | echo 'incomplete CSN allocation trace: could not copy every directory server trace' >"$OUT/csn-trace-validation.txt" |
| | | echo '::error::CSN trace is incomplete; see csn-trace-validation.txt' |
| | | return 1 |
| | | fi |
| | | python3 -I "$HERE/csn-trace.py" "$OUT/csn-traces" "$OUT/csn-trace-expected.txt" \ |
| | | >"$OUT/csn-trace-validation.txt" 2>&1 || failed=1 |
| | | [ -z "$failed" ] || { echo '::error::CSN trace is incomplete; see csn-trace-validation.txt'; return 1; } |
| | | CSN_TRACES_COMPLETE=1 |
| | | } |
| | | |
| | | # Preserve the live snapshot first (collect), then allow the running DS processes to close their |
| | | # traces before copying them again. Missing containers and killed processes remain incomplete. |
| | | # KEEP leaves the servers untouched and validation will report any still-open trace. |
| | | finalize_failure_csn_traces() { |
| | | local node pid |
| | | local -a pids=() |
| | | [ "${CSN_TRACE:-0}" = 1 ] || return 0 |
| | | if [ "${KEEP:-0}" != 1 ]; then |
| | | for node in $DS_NODES; do |
| | | docker inspect "$node" >/dev/null 2>&1 || continue |
| | | ( trap - ERR; docker stop -t 120 "$node" >/dev/null ) & |
| | | pids+=("$!") |
| | | done |
| | | for pid in "${pids[@]}"; do wait "$pid" || true; done |
| | | fi |
| | | check_csn_traces || true |
| | | } |
| | | |
| | | # Look up the first gaps reported for each replica on each RS. This is evidence only: |
| | | # local allocations include operations which may have failed and never committed. |
| | | diagnose_csn_gaps() { |
| | | local pair |
| | | local -a pairs=() |
| | | [ "${CSN_TRACE:-0}" = 1 ] || return 0 |
| | | grep -Fx 'CSN allocation traces complete; local allocations may be uncommitted' \ |
| | | "$OUT/csn-trace-validation.txt" >/dev/null 2>&1 || return 0 |
| | | [ -d "$OUT/changelog" ] || return 0 |
| | | compgen -G "$OUT/changelog/*.txt" >/dev/null || return 0 |
| | | while IFS= read -r pair; do [ -z "$pair" ] || pairs+=("$pair"); done < <( |
| | | awk '/^replica [0-9]+(:| \([^)]*\):)/ { id=$2; sub(/:$/, "", id) } |
| | | /^ missing [0-9]+,/ { seq=$2; sub(/,$/, "", seq); if (id != "") print id ":" seq }' \ |
| | | "$OUT"/changelog/*.txt | sort -u |
| | | ) |
| | | [ "${#pairs[@]}" -gt 0 ] || return 0 |
| | | python3 -I "$HERE/csn-trace.py" "$OUT/csn-traces" "$OUT/csn-trace-expected.txt" "${pairs[@]}" \ |
| | | >"$OUT/csn-trace-gaps.txt" 2>&1 |
| | | } |
| | | |
| | | # The server id each directory server has in the replication domain of BASE_DN, which the |
| | | # samples name the servers by: "Directory server DS(<id>) <host:port>" (ReplicationMonitor) |
| | | record_server_ids() { |
| | |
| | | || fail "the server id of a directory server is missing, see server-ids.txt" |
| | | } |
| | | |
| | | # A combined server can return with a new replica ID after a bootstrap reset, |
| | | # including on a retained volume. Keep every ID for the changelog checks. |
| | | record_rejoined_id() { # <directory server> |
| | | local node=$1 result ids id owner |
| | | result=$(admin_search "$node" "$MONITOR_DOMAIN" one '(objectClass=*)' 1.1) || return 1 |
| | | ids=$(printf '%s\n' "$result" | sed -n 's/^dn: cn=Directory server DS(\([0-9]*\)).*/\1/p') |
| | | [ "$(printf '%s\n' "$ids" | awk 'NF { n++ } END { print n+0 }')" -eq 1 ] || return 1 |
| | | id=$ids |
| | | owner=$(awk -v id="$id" '$1 == id { print $2 }' "$OUT/server-ids.txt") || return 1 |
| | | [ -z "$owner" ] || [ "$owner" = "$node" ] || return 1 |
| | | REJOINED_WITH_NEW_ID=0 |
| | | if [ -z "$owner" ]; then |
| | | printf '%s %s\n' "$id" "$node" >>"$OUT/server-ids.txt" || return 1 |
| | | REJOINED_WITH_NEW_ID=1 |
| | | fi |
| | | } |
| | | |
| | | # CLI failures carry the detailed cause in tmp/opendj-*.log. Read Docker archive |
| | | # streams so diagnostics survive a stopped container too, copying only regular |
| | | # tool logs (never passwords, worker FIFOs or unrelated temporary data). |
| | | collect_tool_logs() { # <node> <output directory> |
| | | mkdir -p "$2" || return 1 |
| | | docker cp "$1:/opt/opendj/data/tmp/." - 2>/dev/null | python3 -c ' |
| | | import pathlib, re, shutil, sys, tarfile |
| | | out = pathlib.Path(sys.argv[1]) |
| | | with tarfile.open(fileobj=sys.stdin.buffer, mode="r|*") as archive: |
| | | for item in archive: |
| | | name = pathlib.PurePosixPath(item.name).name |
| | | if item.isfile() and re.fullmatch(r"opendj-(setup|replication|status)-[^/]+[.]log", name): |
| | | with archive.extractfile(item) as source, (out / name).open("wb") as target: |
| | | shutil.copyfileobj(source, target) |
| | | ' "$2" 2>/dev/null |
| | | } |
| | | |
| | | # Every server's container log, logs/, config/ and changelogDb, packed into state.tgz; docker cp |
| | | # reads a stopped or killed container as well. Nothing here may fail the run a second time |
| | | collect() { |
| | | local n |
| | | for n in $ALL_NODES; do |
| | | docker inspect $n >/dev/null 2>&1 || continue |
| | | case " $DS_NODES " in *" $n "*) capture_csn_trace "$n" || true ;; esac |
| | | mkdir -p "$OUT/state/$n" |
| | | docker logs $n >"$OUT/state/$n/container.log" 2>&1 || true |
| | | collect_tool_logs "$n" "$OUT/state/$n/tool-logs" || true |
| | | docker cp "$n:/opt/opendj/.bootstrap-failed" "$OUT/state/$n/bootstrap-failed" >/dev/null 2>&1 || true |
| | | docker cp $n:/opt/opendj/data/logs "$OUT/state/$n/" >/dev/null 2>&1 || true |
| | | docker cp $n:/opt/opendj/data/config "$OUT/state/$n/" >/dev/null 2>&1 || true |
| | | docker cp $n:/opt/opendj/data/changelogDb "$OUT/state/$n/" >/dev/null 2>&1 || true |
| | |
| | | echo "| | |" |
| | | echo "|---|---|" |
| | | echo "| servers | $ALL_NODES |" |
| | | echo "| load | $DURATION s on each directory server, at most $LOAD_MOD_RATE modifications and $LOAD_ADD_RATE adds or deletes a second |" |
| | | case $DISTURBANCE in |
| | | scale-*) echo "| load | ${ROLLING_ELAPSED:--} s elapsed (limit $DURATION s), at most $LOAD_MOD_RATE modifications and $LOAD_ADD_RATE adds or deletes a second per directory server |" ;; |
| | | *) echo "| load | $DURATION s on each directory server, at most $LOAD_MOD_RATE modifications and $LOAD_ADD_RATE adds or deletes a second |" ;; |
| | | esac |
| | | echo "| seeded users | $SAMPLE_DATA |" |
| | | if [ -s "$OUT/disturbances.txt" ]; then |
| | | completed=$(wc -l <"$OUT/disturbances.txt") |
| | | awk -v start="${LOAD_START_MS:-0}" '{ printf "| disturbance | %s of %s %d s into the load, serving again %d s later |\n", |
| | | $4, $3, ($1 - start) / 1000, ($2 - $1) / 1000 }' "$OUT/disturbances.txt" |
| | | awk -v start="${LOAD_START_MS:-0}" '{ action = ($4 ~ /^scale-/ ? "completed" : "serving again") |
| | | printf "| disturbance | %s of %s %d s into the load, %s %d s later |\n", |
| | | $4, $3, ($1 - start) / 1000, action, ($2 - $1) / 1000 }' "$OUT/disturbances.txt" |
| | | fi |
| | | if [ "$DISTURBANCE" != none ] && [ -z "${LOAD_START_MS:-}" ]; then |
| | | # run.sh sets LOAD_START_MS as the load starts |
| | |
| | | echo "| disturbance | $DISTURBANCE not completed: $((completed)) of $DISTURB_STEPS steps completed |" |
| | | fi |
| | | fi |
| | | if [ -f "$OUT/scale-checkpoint/backlog.txt" ]; then |
| | | awk '/^[0-9]+ changes while the server was absent$/ { printf "| scale backlog | %s |\n", $0 }' \ |
| | | "$OUT/scale-checkpoint/backlog.txt" |
| | | fi |
| | | echo "| converged | ${CONVERGED_IN:--} s after the load |" |
| | | if [ "$DISTURBANCE" = empty-rs ] && [ -n "${CONVERGED_IN:-}" ]; then |
| | | if [ -s "$OUT/failover.txt" ]; then |
| | | awk '{ printf "| failover | stopped %s; all directory servers connected to %s after %d s |\n", $1, $2, $3 }' "$OUT/failover.txt" |
| | | completed=$(( $(wc -l <"$OUT/failover.txt") )) |
| | | else |
| | | completed=0 |
| | | fi |
| | | if [ "$completed" -lt 2 ]; then |
| | | echo "| failover | incomplete: $completed of 2 replication servers checked |" |
| | | fi |
| | | fi |
| | | if [ -s "$OUT/samples.txt" ]; then |
| | | awk '{ t[$1] = 1 } END { for (s in t) { n++; if (!min || s < min) min = s; if (s > max) max = s } |
| | | printf "| samples of the monitor | %d, one every %d s |\n", n, (n > 1 ? (max - min) / (n - 1) : 0) }' "$OUT/samples.txt" |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # 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. |
| | | |
| | | """Validate opt-in CSN allocation traces and look up replica/sequence pairs. |
| | | |
| | | A local allocation is an attempted operation, not proof that it committed. These traces |
| | | do not prove that a local allocation committed. The changelog checker may classify an |
| | | offline-only sequence only when every trace validates and no local allocation reused that |
| | | domain/server/sequence in any generation. A process with an absent, truncated, altered, |
| | | duplicated, or unclosed trace fails |
| | | validation. The manifest lists every expected server-process generation, including restarts. |
| | | """ |
| | | |
| | | import argparse |
| | | import base64 |
| | | from collections import Counter |
| | | from pathlib import Path |
| | | import re |
| | | import sys |
| | | import zlib |
| | | |
| | | EVENT = re.compile(rb'([LO]) ([A-Za-z0-9+/]+={0,2}) ([0-9a-f]{28})\n') |
| | | START = re.compile(rb'START 1 ([a-zA-Z0-9_-]+)\n') |
| | | END = re.compile(rb'END ([0-9]+) ([0-9a-f]{8})\n') |
| | | |
| | | |
| | | def read_traces(root, manifest, wanted): |
| | | root = Path(root) |
| | | try: |
| | | expected = Counter(tuple(line.split()) for line in Path(manifest).read_text().splitlines()) |
| | | if not expected or any(len(item) != 2 for item in expected): |
| | | raise ValueError('empty or invalid expected-generations manifest') |
| | | if any(count != 1 for count in expected.values()) or len({item[1] for item in expected}) != len(expected): |
| | | raise ValueError('generation tokens must be unique') |
| | | found, actual = [], Counter() |
| | | files = sorted(root.glob('*/*.txt')) |
| | | for path in files: |
| | | node = path.parent.name |
| | | with path.open('rb') as stream: |
| | | start = START.fullmatch(stream.readline()) |
| | | if not start: |
| | | raise ValueError('%s: invalid start' % path) |
| | | token = start.group(1).decode('ascii') |
| | | actual[(node, token)] += 1 |
| | | count = checksum = 0 |
| | | for line in stream: |
| | | end = END.fullmatch(line) |
| | | if end: |
| | | if int(end.group(1)) != count or int(end.group(2), 16) != checksum or stream.read(1): |
| | | raise ValueError('%s: invalid end, checksum, count or trailing records' % path) |
| | | break |
| | | event = EVENT.fullmatch(line) |
| | | if not event: |
| | | raise ValueError('%s: invalid or incomplete event' % path) |
| | | count += 1 |
| | | checksum = zlib.crc32(line, checksum) |
| | | csn = event.group(3).decode('ascii') |
| | | sid, seq = int(csn[16:20], 16), int(csn[20:], 16) |
| | | try: |
| | | domain = base64.b64decode(event.group(2), validate=True).decode('utf-8') |
| | | except (ValueError, UnicodeDecodeError) as exc: |
| | | raise ValueError('%s: invalid domain' % path) from exc |
| | | if (sid, seq) in wanted: |
| | | found.append((event.group(1).decode('ascii'), domain, csn, node, token)) |
| | | else: |
| | | raise ValueError('%s: missing end' % path) |
| | | if actual != expected: |
| | | raise ValueError('generation mismatch: expected %s, found %s' % (dict(expected), dict(actual))) |
| | | return found |
| | | except OSError as exc: |
| | | raise ValueError(str(exc)) from exc |
| | | |
| | | |
| | | def main(): |
| | | parser = argparse.ArgumentParser(description=__doc__) |
| | | parser.add_argument('directory') |
| | | parser.add_argument('manifest') |
| | | parser.add_argument('pairs', nargs='*', help='replica-id:sequence-number') |
| | | args = parser.parse_args() |
| | | try: |
| | | wanted = {tuple(map(int, pair.split(':'))) for pair in args.pairs} |
| | | if any(len(pair) != 2 for pair in wanted): |
| | | raise ValueError('pairs must be replica-id:sequence-number') |
| | | found = read_traces(args.directory, args.manifest, wanted) |
| | | except ValueError as exc: |
| | | print('incomplete CSN allocation trace: %s' % exc, file=sys.stderr) |
| | | return 1 |
| | | for kind, domain, csn, node, token in found: |
| | | print('%s %s %s %s %s' % (node, token, kind, domain, csn)) |
| | | print('CSN allocation traces complete; local allocations may be uncommitted') |
| | | return 0 |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | sys.exit(main()) |
| New file |
| | |
| | | # |
| | | # 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. |
| | | |
| | | # Rebuild an RS on an empty volume while a DS is down (#1208, #1188). Its clients are |
| | | # segmented by run_load; all the other DS keep writing. Once the load has ended and the |
| | | # topology converged, force every DS to connect to each RS in turn, including the DS that |
| | | # missed the new instance key. Run only with two independent replication servers. |
| | | [ "$(echo $RS_ONLY | wc -w)" -eq 2 ] && [ "$(echo $RS_NODES | wc -w)" -eq 2 ] \ |
| | | || { echo "empty-rs needs exactly two replication-only servers: TOPOLOGY=rs534" >&2; exit 2; } |
| | | DISTURBED=$(echo $DS_NODES | cut -d' ' -f2) |
| | | SURVIVOR=$(echo $RS_ONLY | cut -d' ' -f1) |
| | | REBUILT=$(echo $RS_ONLY | cut -d' ' -f2) |
| | | DISTURB_STEPS=1 |
| | | |
| | | rs_serves_since() { # <RS> <start time> |
| | | started_since "$1" "$2" && bootstrap_ended "$1" && [ "$(rs_peers "$1")" -eq 1 ] |
| | | } |
| | | |
| | | # Positions are checked before stopping either RS. The monitor snapshots and comparison |
| | | # diagnostics are retained; equality of the last positions does not prove older gaps absent, |
| | | # so the offline changelog and data checks still run after this scenario. |
| | | rs_caught_up() { # <RS to leave up> <RS about to stop> |
| | | local rs=$1 reference=$2 dir="$OUT/rs-catchup" |
| | | mkdir -p "$dir" || return 1 |
| | | bootstrap_ended "$rs" || return 1 |
| | | admin_search "$reference" cn=monitor sub '(replicationServer-database=*)' \ |
| | | replicationServer-database domain-name last-change >"$dir/$reference.ldif" 2>"$dir/check.txt" || return 1 |
| | | admin_search "$rs" cn=monitor sub '(replicationServer-database=*)' \ |
| | | replicationServer-database domain-name last-change >"$dir/$rs.ldif" 2>>"$dir/check.txt" || return 1 |
| | | python3 -I "$HERE/changelog-checkpoint.py" "$BASE_DN" "$OUT/server-ids.txt" \ |
| | | "$dir/$reference.ldif" "$dir/$rs.ldif" >"$dir/check.txt" 2>&1 |
| | | } |
| | | |
| | | connected_to() { # <DS> <RS> |
| | | local address |
| | | address=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$2") || return 1 |
| | | [ -n "$address" ] || return 1 |
| | | admin_search "$1" "$MONITOR_DOMAIN" one '(connected-to=*)' connected-to \ |
| | | | grep -Fx "connected-to: $address:8989" >/dev/null |
| | | } |
| | | |
| | | disturb() { |
| | | local from served cert_start cert_end address |
| | | window_open "dns:$REBUILT" "cert:$DISTURBED:$REBUILT" 180 |
| | | from=$(date +%s) |
| | | echo " [$SECONDS s] stopping $DISTURBED and rebuilding $REBUILT" |
| | | docker stop -t 120 "$DISTURBED" >/dev/null |
| | | docker stop -t 120 "$REBUILT" >/dev/null |
| | | # Keep the old log before removing its volume. errors_lines and since_mark treat it and |
| | | # the new log as one sequence, so neither pre-replacement errors nor window bounds vanish. |
| | | [ ! -e "$OUT/logs/$REBUILT.previous" ] || fail "the old errors log of $REBUILT already exists" |
| | | docker logs "$REBUILT" >"$OUT/logs/$REBUILT.previous-container" 2>&1 |
| | | docker cp "$REBUILT:/opt/opendj/data/logs/errors" "$OUT/logs/$REBUILT.previous" |
| | | docker rm "$REBUILT" >/dev/null |
| | | docker volume rm "vol-$REBUILT" >/dev/null |
| | | start_server "$REBUILT" replication |
| | | wait_until "$DISTURB_TIMEOUT" "$REBUILT serves again" rs_serves_since "$REBUILT" "$from" |
| | | # The RS may log the same transient rejection on its side as warning 105. Restrict that |
| | | # allowance to this DS's actual Docker address, and to the period after it restarts. |
| | | cert_start=$(errors_lines "$REBUILT") |
| | | [ "${CSN_TRACE:-0}" != 1 ] || expect_csn_trace_restart "$DISTURBED" |
| | | docker start "$DISTURBED" >/dev/null |
| | | address=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$DISTURBED") |
| | | [ -n "$address" ] || fail "cannot determine the address of $DISTURBED" |
| | | wait_until "$DISTURB_TIMEOUT" "$DISTURBED serves again" started_since "$DISTURBED" "$from" |
| | | served=$(date +%s) |
| | | sleep 10 |
| | | cert_end=$(errors_lines "$REBUILT") |
| | | printf '%s %s cert-peer:%s:%s\n' "$cert_start" "$cert_end" "$REBUILT" "$address" >>"$OUT/logs/$REBUILT.windows" |
| | | window_close |
| | | echo "$((from * 1000)) $((served * 1000)) $DISTURBED rebuild-$REBUILT" >>"$OUT/disturbances.txt" |
| | | } |
| | | |
| | | settle() { |
| | | wait_until "$DISTURB_TIMEOUT" "the join of $DISTURBED ends" bootstrap_ended "$DISTURBED" |
| | | wait_until "$DISTURB_TIMEOUT" "the join of $REBUILT ends" bootstrap_ended "$REBUILT" |
| | | } |
| | | |
| | | after_convergence() { |
| | | local stopped active n from saved_converged=$CONVERGED_IN |
| | | for stopped in "$SURVIVOR" "$REBUILT"; do |
| | | if [ "$stopped" = "$SURVIVOR" ]; then active=$REBUILT; else active=$SURVIVOR; fi |
| | | wait_until "$QUIESCE_TIMEOUT" "$active reaches the checkpoint of $stopped" rs_caught_up "$active" "$stopped" |
| | | window_open "dns:$stopped" 180 |
| | | from=$(date +%s) |
| | | docker stop -t 120 "$stopped" >/dev/null |
| | | for n in $DS_NODES; do |
| | | wait_until "$DISTURB_TIMEOUT" "$n connects to $active" connected_to "$n" "$active" |
| | | done |
| | | echo "$stopped $active $(($(date +%s) - from))" >>"$OUT/failover.txt" |
| | | docker start "$stopped" >/dev/null |
| | | wait_until "$DISTURB_TIMEOUT" "$stopped serves again" rs_serves_since "$stopped" "$from" |
| | | wait_until "$DISTURB_TIMEOUT" "the join of $stopped ends" bootstrap_ended "$stopped" |
| | | sleep 10 |
| | | window_close |
| | | wait_converged |
| | | done |
| | | CONVERGED_IN=$saved_converged |
| | | } |
| New file |
| | |
| | | # |
| | | # 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 |
| | | } |
| | |
| | | DISTURBANCE=${DISTURBANCE:-none} |
| | | # seconds of load. A disturbed run takes the load of its CI rows: a restarted server served |
| | | # again 131 to 225 s after the restart there, and the load has to go on after that |
| | | if [ "$DISTURBANCE" = none ]; then |
| | | DURATION=${DURATION:-120} |
| | | else |
| | | DURATION=${DURATION:-900} |
| | | fi |
| | | case $DISTURBANCE in |
| | | none) DURATION=${DURATION:-120} ;; |
| | | scale-*) DURATION=${DURATION:-2700} ;; |
| | | *) DURATION=${DURATION:-900} ;; |
| | | esac |
| | | # the most modifications, and adds or deletes, per second the load sends to each directory |
| | | # server; a runner that cannot keep up sends fewer, which the summary shows |
| | | LOAD_MOD_RATE=${LOAD_MOD_RATE:-423} |
| | | LOAD_ADD_RATE=${LOAD_ADD_RATE:-85} |
| | | case $DISTURBANCE in |
| | | scale-*) LOAD_MOD_RATE=${LOAD_MOD_RATE:-100}; LOAD_ADD_RATE=${LOAD_ADD_RATE:-20} ;; |
| | | *) LOAD_MOD_RATE=${LOAD_MOD_RATE:-423}; LOAD_ADD_RATE=${LOAD_ADD_RATE:-85} ;; |
| | | esac |
| | | # users the first directory server imports; the others get them from its initialize |
| | | SAMPLE_DATA=${SAMPLE_DATA:-2000} |
| | | # the heap of every server and every load client. Without a bound each JVM may take a quarter |
| | |
| | | # 1: write to one replica only, which the run must report (a self-test of its checks) |
| | | INJECT_DIVERGENCE=${INJECT_DIVERGENCE:-0} |
| | | # seconds into the load at which the disturbance starts |
| | | DISTURB_AT=${DISTURB_AT:-$((DURATION / 3))} |
| | | case $DISTURBANCE in |
| | | scale-*) |
| | | # Keep the 120-second warmup when extending the scale load; shorter custom loads |
| | | # still start the disturbance proportionally earlier. |
| | | scale_start=$((DURATION * 2 / 15)) |
| | | [ "$scale_start" -le 120 ] || scale_start=120 |
| | | DISTURB_AT=${DISTURB_AT:-$scale_start} |
| | | ;; |
| | | *) DISTURB_AT=${DISTURB_AT:-$((DURATION / 3))} ;; |
| | | esac |
| | | # seconds a disturbed server is given to serve again, and its join to end after the load |
| | | DISTURB_TIMEOUT=${DISTURB_TIMEOUT:-900} |
| | | # where the summary, the samples, the exports, the differences and a failed run's state go: a |
| | |
| | | exit 2 |
| | | ;; |
| | | esac |
| | | # A scale-in removes one RS and then rolls every survivor. Two remaining RS are needed |
| | | # so writes can continue when either one is restarted; the other rs534 rows keep two. |
| | | case "$TOPOLOGY:$DISTURBANCE" in |
| | | rs534:scale-rs-kept|rs534:scale-rs-empty) |
| | | RS_ONLY="cv-r0 cv-r1 cv-r2" |
| | | RS_NODES=$RS_ONLY |
| | | ;; |
| | | esac |
| | | ALL_NODES=$(echo $DS_NODES $RS_ONLY) |
| | | PEERS=$(echo $ALL_NODES | tr ' ' ',') |
| | | |
| | |
| | | } |
| | | |
| | | wait_until() { # <seconds> <what> <command> [<argument>...] |
| | | local deadline=$((SECONDS + $1)) what=$2 start=$SECONDS |
| | | local deadline=$((SECONDS + $1)) what=$2 start=$SECONDS rc |
| | | shift 2 |
| | | until "$@"; do |
| | | [ "$SECONDS" -lt "$deadline" ] || fail "timed out waiting until $what" |
| | | while :; do |
| | | if [ "${SCALE_DEADLINE_ACTIVE:-0}" = 1 ] && declare -F rolling_worker_failed >/dev/null && rolling_worker_failed; then |
| | | fail "load worker failed while waiting until $what"; return 1 |
| | | fi |
| | | rc=0 |
| | | "$@" || rc=$? |
| | | [ "$rc" -ne 0 ] || break |
| | | # Reserve 200 for terminal bootstrap failure; existing predicates may retry status 2. |
| | | [ "$rc" -ne 200 ] || { fail "terminal failure while waiting until $what"; return 1; } |
| | | [ "$SECONDS" -lt "$deadline" ] || { fail "timed out waiting until $what"; return 1; } |
| | | sleep 2 |
| | | done |
| | | [ $((SECONDS - start)) -lt 20 ] || echo " [$((SECONDS - start)) s] until $what" |
| | | } |
| | | |
| | | is_healthy() { # <container> |
| | | [ "$(docker inspect --format='{{.State.Health.Status}}' "$1")" = healthy ] |
| | | local rc=0 state |
| | | docker exec "$1" sh -c 'test ! -f "${BOOTSTRAP_FAILED:-/opt/opendj/.bootstrap-failed}" || exit 200' 2>/dev/null || rc=$? |
| | | [ "$rc" -ne 200 ] || return 200 |
| | | [ "$rc" -eq 0 ] || return 1 |
| | | state=$(docker inspect --format='{{.State.Health.Status}}' "$1") || return 1 |
| | | [ "$state" = healthy ] |
| | | } |
| | | |
| | | # The server of the container logged that it started (msgID 135, once its connection handlers |
| | |
| | | |
| | | # The background join of the image goes on once the container reports itself healthy: it adds |
| | | # replication servers to the replication server lists while its peers register |
| | | # (repair_replication_servers in join.sh). Ended once no bootstrap script runs any more, as |
| | | # docker-test-replication.sh waits for it |
| | | # (repair_replication_servers in join.sh). Only the wrapper's successful result proves |
| | | # completion: no join process also means setup has not launched it yet. |
| | | bootstrap_ended() { # <container> |
| | | ! docker exec "$1" sh -c "grep -qs -e 'bootstrap/[j]oin\.sh' -e 'bootstrap/[r]eplicate\.sh' /proc/[0-9]*/cmdline" |
| | | docker exec "$1" sh -c 'test ! -f "${BOOTSTRAP_FAILED:-/opt/opendj/.bootstrap-failed}" || exit 200; |
| | | test -f "${BOOTSTRAP_FINISHED:-/opt/opendj/.bootstrap-finished}"' |
| | | } |
| | | |
| | | ldaps_search() { # <container> <base DN> <scope> <filter> [<attribute>...] |
| | |
| | | start_client() { |
| | | local name=$1 tool=$2 |
| | | shift 2 |
| | | docker run -d --name "$name" --network $NETWORK -e OPENDJ_JAVA_ARGS="$CLIENT_JAVA_ARGS" \ |
| | | -v "$OUT/load:/load:ro" --entrypoint /opt/opendj/bin/$tool "$IMAGE" "$@" >/dev/null |
| | | if [ -n "${ROLLING_END_MS:-}" ]; then |
| | | # The container enforces the absolute deadline as well as the host watchdog: it |
| | | # cannot start a late operation if Docker finishes creating it after the watchdog scan. |
| | | docker run -d --name "$name" --network "$NETWORK" -e OPENDJ_JAVA_ARGS="$CLIENT_JAVA_ARGS" \ |
| | | -v "$OUT/load:/load:ro" --entrypoint /bin/sh "$IMAGE" -c ' |
| | | deadline=$1; tool=$2; shift 2 |
| | | left=$((deadline - $(date +%s))) |
| | | [ "$left" -gt 0 ] || exit 1 |
| | | exec /usr/bin/timeout "$left" "/opt/opendj/bin/$tool" "$@" |
| | | ' sh "$((ROLLING_END_MS / 1000))" "$tool" "$@" >/dev/null |
| | | else |
| | | docker run -d --name "$name" --network $NETWORK -e OPENDJ_JAVA_ARGS="$CLIENT_JAVA_ARGS" \ |
| | | -v "$OUT/load:/load:ro" --entrypoint /opt/opendj/bin/$tool "$IMAGE" "$@" >/dev/null |
| | | fi |
| | | } |
| | | |
| | | CLIENTS= |
| | |
| | | # start at once next to the servers, and a runner that is short of CPU for a while accepts |
| | | # their connections late |
| | | start_clients() { # <node> <segment> <seconds> |
| | | local n=$1 name=$1 c |
| | | local n=$1 name=$1 c surname=AddRate |
| | | local -a addrate_options=() |
| | | case ${DISTURBANCE:-none} in |
| | | # Purging a segment at shutdown can take longer than the segment itself. |
| | | # FIFO deletes remain enabled; cycle each DS across three indexed shards. |
| | | scale-*) surname="AddRate-$n-$((($2 - 1) % 3 + 1))"; addrate_options=(--noPurge) ;; |
| | | esac |
| | | [ "$2" -eq 1 ] || name=$1-$2 |
| | | [ ! -e "$OUT/load/deadline" ] || return 1 |
| | | # entries of its own on each server, so that the adds and deletes of two servers never meet |
| | | # on one DN: a naming conflict is not what this load is after |
| | | cat >"$OUT/load/addrate-$name.template" <<TEMPLATE |
| | |
| | | objectClass: inetOrgPerson |
| | | uid: addrate-$name.<sequential:0> |
| | | cn: AddRate {uid} |
| | | sn: AddRate |
| | | sn: $surname |
| | | userPassword: password |
| | | TEMPLATE |
| | | chmod 644 "$OUT/load/addrate-$name.template" |
| | |
| | | --bindDN "cn=Directory Manager" --bindPassword "$ROOT_PASSWORD" --maxDuration "$3" \ |
| | | --statInterval $STAT_INTERVAL --numConnections 8 --numThreads 1 --scriptFriendly --targetThroughput "$LOAD_MOD_RATE" \ |
| | | --targetDN "uid=user.%d,ou=People,$BASE_DN" --argument "rand(0,$((SAMPLE_DATA - 1)))" \ |
| | | --argument "randstr(16)" "description:$name-%2\$s" |
| | | --argument "randstr(16)" "description:$name-%2\$s" || return 1 |
| | | if [ -e "$OUT/load/deadline" ]; then |
| | | docker kill "load-mod-$name" >/dev/null 2>&1 || true |
| | | return 1 |
| | | fi |
| | | # adds, and deletes of the oldest once 100 of them are there: a slow runner gets to the deletes as well |
| | | start_client load-add-$name addrate --hostname $n --port 1389 --connectTimeout 120000 --noRebind \ |
| | | --bindDN "cn=Directory Manager" --bindPassword "$ROOT_PASSWORD" --maxDuration "$3" \ |
| | | --statInterval $STAT_INTERVAL --numConnections 8 --numThreads 1 --scriptFriendly --targetThroughput "$LOAD_ADD_RATE" \ |
| | | --deleteMode fifo --deleteSizeThreshold 100 "/load/addrate-$name.template" |
| | | --deleteMode fifo --deleteSizeThreshold 100 "${addrate_options[@]}" "/load/addrate-$name.template" || return 1 |
| | | if [ -e "$OUT/load/deadline" ]; then |
| | | docker kill "load-mod-$name" "load-add-$name" >/dev/null 2>&1 || true |
| | | return 1 |
| | | fi |
| | | # check_client reads how long each client was to run |
| | | for c in load-mod-$name load-add-$name; do |
| | | echo "$3" >"$OUT/load/$c.seconds" |
| | |
| | | # prints the error to its error output, which goes to the same file. So the client has to have |
| | | # done work, every interval of its CSV output has to report no errors (the "Errors/second" |
| | | # column), the output has to cover the seconds the client was to run - a line every |
| | | # STAT_INTERVAL seconds, of which the last may be missing - and hold nothing but the CSV |
| | | # STAT_INTERVAL seconds, of which the last may be missing - and hold nothing but the CSV. |
| | | # Scale rows also require a minimum time-weighted throughput; the last CSV interval can |
| | | # be much shorter than STAT_INTERVAL or have the same timestamp as the preceding row. |
| | | check_client() { # <client> |
| | | awk -F, -v c=$1 -v exit_state="$(cat "$OUT/load/$1.exit")" -v want=$(($(cat "$OUT/load/$1.seconds") / STAT_INTERVAL - 1)) ' |
| | | local minimum_rate=0 |
| | | case ${DISTURBANCE:-none}:$1 in |
| | | scale-*:load-mod-*) minimum_rate=$((LOAD_MOD_RATE / 10)) ;; |
| | | scale-*:load-add-*) minimum_rate=$((LOAD_ADD_RATE / 10)) ;; |
| | | esac |
| | | awk -F, -v c=$1 -v minimum_rate="$minimum_rate" -v exit_state="$(cat "$OUT/load/$1.exit")" -v want=$(($(cat "$OUT/load/$1.seconds") / STAT_INTERVAL - 1)) ' |
| | | /^Time \(seconds\)/ { for (i = 1; i <= NF; i++) { if ($i == "Recent throughput (ops/second)") t = i; if ($i == "Errors/second") e = i }; next } |
| | | t && $1 ~ /^[0-9.]+$/ { rows++; ops += $t; errors += $e; last = $0; next } |
| | | t && $1 ~ /^[0-9.]+$/ { |
| | | rows++; ops += $t; errors += $e; last = $0 |
| | | elapsed = $1 + 0; duration = elapsed - previous |
| | | if (duration < 0) bad_time = 1 |
| | | else if (duration > 0) { weighted_ops += $t * duration; observed += duration } |
| | | previous = elapsed |
| | | next |
| | | } |
| | | NF { other++ } |
| | | END { |
| | | if (!rows || ops == 0) { printf "::error::%s did no work (exit code and OOM kill: %s)\n", c, exit_state; exit 1 } |
| | | if (errors > 0) { printf "::error::%s got errors back\n", c; exit 1 } |
| | | if (minimum_rate && (bad_time || observed <= 0)) { printf "::error::%s has invalid interval times\n", c; exit 1 } |
| | | if (minimum_rate && weighted_ops / observed < minimum_rate) { printf "::error::%s averaged %.1f ops/s, below minimum %d ops/s\n", c, weighted_ops / observed, minimum_rate; exit 1 } |
| | | if (exit_state != "0 false") { printf "::error::%s ended with exit code and OOM kill %s\n", c, exit_state; exit 1 } |
| | | if (other) { printf "::error::%s printed %d lines besides its CSV output, see load/%s.csv\n", c, other, c; exit 1 } |
| | | if (rows < want) { printf "::error::%s stopped after %d of %d intervals\n", c, rows, want; exit 1 } |
| | |
| | | converged_once() { |
| | | local s rs want |
| | | s=$(sample) || return 1 |
| | | if [ "${CONVERGENCE_RECORDING:-0}" = 1 ]; then |
| | | printf '%s\n' "$s" >>"$OUT/convergence-samples.txt" || return 1 |
| | | fi |
| | | want=$(echo $DS_NODES | wc -w) |
| | | for rs in $RS_NODES; do |
| | | [ "$(echo "$s" | awk -v rs=$rs '$2 == rs { print $3 }' | sort -u | wc -l)" -eq "$want" ] || return 1 |
| | |
| | | # the publisher's 5 s latch) after the first ended. Sets CONVERGED_IN to the seconds from |
| | | # <start> (a value of SECONDS, now by default) until the first of them |
| | | wait_converged() { # [<start>] |
| | | local start=${1:-$SECONDS} hits=0 first= last= |
| | | local start=${1:-$SECONDS} hits=0 first= last= CONVERGENCE_RECORDING=1 |
| | | until [ $hits -ge 3 ] && [ $((last - first)) -gt $((MONITORING_PERIOD + 5)) ]; do |
| | | last=$SECONDS |
| | | if converged_once; then hits=$((hits + 1)); first=${first:-$SECONDS}; else hits=0; first=; fi |
| New file |
| | |
| | | # |
| | | # 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. |
| | | |
| | | # Bound Docker commands in the scale scenario too: a blocked daemon or a large online |
| | | # changelog copy must not make a predicate run past the load deadline. |
| | | docker() { |
| | | if [ "${SCALE_DEADLINE_ACTIVE:-0}" = 1 ]; then |
| | | python3 -I "$HERE/scale-deadline.py" "$ROLLING_END_MS" "$(command -v docker)" "$@" |
| | | else |
| | | command docker "$@" |
| | | fi |
| | | } |
| | | |
| | | # Each DS gets naturally ending segments. A rolling replacement waits for both clients |
| | | # before stopping it; other DS keep writing. Three surnames per DS keep each indexed |
| | | # shard below the entry limit while allowing short segments for an hour-long load. |
| | | ROLLING_SEGMENT=${ROLLING_SEGMENT:-50} |
| | | # Docker's finish time includes JVM startup and connection setup, unlike --maxDuration. |
| | | # A successful run cannot claim the requested duration if a client exited after it. |
| | | finished_before_deadline() { # <Docker UTC timestamp> <deadline in epoch milliseconds> |
| | | python3 -I - "$1" "$2" <<'PYTIME' |
| | | from datetime import datetime, timezone |
| | | import re |
| | | import sys |
| | | match = re.fullmatch(r"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z", sys.argv[1]) |
| | | try: |
| | | if not match: |
| | | raise ValueError("invalid Docker finish time") |
| | | seconds = int(datetime.strptime(match[1], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc).timestamp()) |
| | | nanoseconds = seconds * 10**9 + int((match[2] or "").ljust(9, "0")) |
| | | sys.exit(0 if nanoseconds <= int(sys.argv[2]) * 10**6 else 1) |
| | | except ValueError: |
| | | sys.exit(1) |
| | | PYTIME |
| | | } |
| | | |
| | | # Keep recent LDAP rejections and replication warnings close to a failed client. |
| | | # The complete logs are still collected by the failed-run handler. |
| | | rolling_collect_error_context() { # <directory server> |
| | | docker exec "$1" /bin/sh -c ' |
| | | logs=/opt/opendj/data/logs |
| | | echo "Recent nonzero LDAP results:" |
| | | tail -n 5000 "$logs"/access* 2>/dev/null | grep -E "(MODIFY|ADD|DELETE) RES .*result=[1-9][0-9]*" | tail -n 30 || : |
| | | echo "Recent replication warnings and errors:" |
| | | tail -n 500 "$logs/errors" 2>/dev/null | grep -E "category=SYNC severity=(WARNING|ERROR)" | tail -n 30 || : |
| | | ' >"$OUT/load/$1.recent-errors.log" 2>&1 || : |
| | | echo "::group::Recent server errors for $1" |
| | | cat "$OUT/load/$1.recent-errors.log" || : |
| | | echo "::endgroup::" |
| | | } |
| | | |
| | | rolling_worker() { # <directory server> |
| | | local n=$1 segment=1 name c length remaining finished failed post_segment |
| | | # The parent reports this worker's failure; do not run run.sh's collection trap here. |
| | | trap - ERR |
| | | while [ ! -e "$OUT/load/stop" ]; do |
| | | if [ -e "$OUT/load/$n.pause" ]; then |
| | | touch "$OUT/load/$n.parked" || return 1 |
| | | while [ -e "$OUT/load/$n.pause" ] && [ ! -e "$OUT/load/stop" ]; do sleep 1; done |
| | | rm -f "$OUT/load/$n.parked" || return 1 |
| | | continue |
| | | fi |
| | | length=$ROLLING_SEGMENT |
| | | if [ -n "${ROLLING_END:-}" ]; then |
| | | # --maxDuration starts only after the JVM and its connections are ready. Leave |
| | | # a small launch/teardown allowance; FinishedAt still enforces the hard deadline. |
| | | remaining=$((ROLLING_END - SECONDS - 40)) |
| | | [ "$remaining" -ge $((3 * STAT_INTERVAL)) ] || break |
| | | [ "$length" -le "$remaining" ] || length=$remaining |
| | | fi |
| | | name=$n |
| | | [ "$segment" -eq 1 ] || name=$n-$segment |
| | | post_segment= |
| | | [ ! -e "$OUT/load/post-start" ] || post_segment=1 |
| | | printf 'load-mod-%s load-add-%s\n' "$name" "$name" >"$OUT/load/$n.active" || return 1 |
| | | if ! start_clients "$n" "$segment" "$length"; then |
| | | [ ! -e "$OUT/load/deadline" ] || rolling_kill_active "$n" |
| | | return 1 |
| | | fi |
| | | if [ -e "$OUT/load/deadline" ]; then |
| | | rolling_kill_active "$n" |
| | | return 1 |
| | | fi |
| | | failed= |
| | | for c in "load-mod-$name" "load-add-$name"; do |
| | | docker wait "$c" >/dev/null || { echo "::error::docker wait failed for $c" >&2; return 1; } |
| | | if [ -n "${ROLLING_END_MS:-}" ]; then |
| | | finished=$(docker inspect -f '{{.State.FinishedAt}}' "$c") || { echo "::error::cannot inspect finish time for $c" >&2; return 1; } |
| | | printf '%s\n' "$finished" >"$OUT/load/$c.finished" || return 1 |
| | | fi |
| | | docker logs "$c" >"$OUT/load/$c.csv" 2>&1 || { echo "::error::cannot collect logs for $c" >&2; return 1; } |
| | | docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' "$c" >"$OUT/load/$c.exit" || { echo "::error::cannot inspect exit state for $c" >&2; return 1; } |
| | | docker rm "$c" >/dev/null || { echo "::error::cannot remove client $c" >&2; return 1; } |
| | | if [ -n "${ROLLING_END_MS:-}" ]; then |
| | | finished_before_deadline "$finished" "$ROLLING_END_MS" || { |
| | | echo "::error::$c finished after the load deadline ($finished)" >&2; failed=1; touch "$OUT/load/$n.failed" || return 1; |
| | | } |
| | | fi |
| | | check_client "$c" || { failed=1; touch "$OUT/load/$n.failed" || return 1; } |
| | | done |
| | | if [ -n "$failed" ]; then rolling_collect_error_context "$n"; return 1; fi |
| | | [ -z "$post_segment" ] || touch "$OUT/load/$n.post-verified" || return 1 |
| | | rm "$OUT/load/$n.active" || return 1 |
| | | segment=$((segment + 1)) |
| | | done |
| | | } |
| | | # A marker is written before Docker starts the clients; require both containers to be |
| | | # running before relying on this DS as the sole load writer during a checkpoint. |
| | | rolling_clients_running() { # <directory server> |
| | | local node=$1 mod add extra client state |
| | | [ ! -e "$OUT/load/$node.pause" ] && [ -f "$OUT/load/$node.active" ] || return 1 |
| | | read -r mod add extra <"$OUT/load/$node.active" || return 1 |
| | | case $mod in "load-mod-$node"|"load-mod-$node-"*) ;; *) return 1 ;; esac |
| | | [ -z "$extra" ] && [ "$add" = "load-add-${mod#load-mod-}" ] || return 1 |
| | | for client in "$mod" "$add"; do |
| | | state=$(docker inspect -f '{{.State.Running}}' "$client") || return 1 |
| | | [ "$state" = true ] || return 1 |
| | | done |
| | | } |
| | | rolling_worker_failed() { |
| | | local marker |
| | | for marker in "$OUT"/load/*.failed; do [ ! -e "$marker" ] || return 0; done |
| | | return 1 |
| | | } |
| | | rolling_parked() { [ -e "$OUT/load/$1.parked" ] || [ -e "$OUT/load/$1.done" ] || rolling_worker_failed; } |
| | | rolling_request_pause() { touch "$OUT/load/$1.pause"; } |
| | | rolling_pause() { # <directory server> |
| | | local timeout=${DISTURB_TIMEOUT:-900} left |
| | | if [ -n "${ROLLING_END:-}" ]; then |
| | | left=$((ROLLING_END - SECONDS)) |
| | | [ "$left" -gt 0 ] || return 1 |
| | | [ "$left" -ge "$timeout" ] || timeout=$left |
| | | fi |
| | | rolling_request_pause "$1" || return 1 |
| | | wait_until "$timeout" "$1 clients finish" rolling_parked "$1" || return 1 |
| | | if rolling_worker_failed || [ -e "$OUT/load/$1.done" ]; then |
| | | echo "::error::load worker $1 failed or stopped before it could pause" >&2 |
| | | return 1 |
| | | fi |
| | | } |
| | | rolling_resume() { rm -f "$OUT/load/$1.pause"; } |
| | | |
| | | # At the hard limit, kill only the load clients of this run which are still active. |
| | | # A killed client makes the run fail; it is never counted as a successful segment. |
| | | rolling_kill_active() { # <directory server> |
| | | local c clients |
| | | [ -f "$OUT/load/$1.active" ] || return 0 |
| | | clients=$(cat "$OUT/load/$1.active") || return 1 |
| | | for c in $clients; do |
| | | if [ "$(SCALE_DEADLINE_ACTIVE=0 docker inspect -f '{{.State.Running}}' "$c" 2>/dev/null || :)" = true ]; then |
| | | touch "$OUT/load/cutoff" || return 1 |
| | | SCALE_DEADLINE_ACTIVE=0 docker kill "$c" >/dev/null 2>&1 || true |
| | | fi |
| | | done |
| | | } |
| | | |
| | | rolling_deadline() { # <seconds> |
| | | local n sleep_pid |
| | | sleep "$1" & sleep_pid=$! |
| | | trap 'kill "$sleep_pid" 2>/dev/null || true; exit 1' TERM INT |
| | | wait "$sleep_pid" || return 1 |
| | | trap - TERM INT |
| | | touch "$OUT/load/deadline" "$OUT/load/stop" || return 1 |
| | | for n in $DS_NODES fill; do rolling_kill_active "$n" || return 1; done |
| | | } |
| | | |
| | | # The sampler is a subshell, so establish the same cutoff before starting it. |
| | | prepare_rolling_deadline() { |
| | | ROLLING_END=$((SECONDS + DURATION)) |
| | | ROLLING_END_MS=$(( ${LOAD_START_MS:-$(($(date +%s) * 1000))} + DURATION * 1000 )) |
| | | SCALE_DEADLINE_ACTIVE=1 |
| | | } |
| | | |
| | | # Every writer must complete and pass both clients of a segment launched after |
| | | # scale-out. A worker that ended earlier must wake the wait and fail it. |
| | | rolling_post_segments_complete() { |
| | | local n |
| | | [ ! -e "$OUT/load/deadline" ] || return 1 |
| | | for n in $DS_NODES; do |
| | | [ ! -e "$OUT/load/$n.done" ] && [ ! -e "$OUT/load/$n.failed" ] || return 1 |
| | | [ -e "$OUT/load/$n.post-verified" ] || return 1 |
| | | done |
| | | } |
| | | rolling_post_segments_ready() { |
| | | local n |
| | | for n in $DS_NODES; do [ ! -e "$OUT/load/$n.done" ] || return 0; done |
| | | rolling_post_segments_complete |
| | | } |
| | | |
| | | # Used in place of run_load for a rolling scale change. The deadline covers the complete |
| | | # disturbance: a late return is a failed run, even if the topology later converges. |
| | | rolling_index_budget() { |
| | | local segments per_shard |
| | | [ "$ROLLING_SEGMENT" -gt 0 ] || return 1 |
| | | segments=$(((DURATION + ROLLING_SEGMENT - 1) / ROLLING_SEGMENT)) |
| | | per_shard=$(((segments + 2) / 3)) |
| | | # The FIFO threshold is 100; allow for concurrent in-flight adds on eight |
| | | # connections. Each DS cycles through three indexed surnames. |
| | | [ $((per_shard * 160)) -lt 4000 ] |
| | | } |
| | | |
| | | rolling_run_load() { |
| | | local n pid watchdog pids= failed= left |
| | | rolling_index_budget || { fail "rolling segments exceed the sn index entry limit"; return 1; } |
| | | mkdir -p "$OUT/load" || return 1 |
| | | [ -n "${ROLLING_END_MS:-}" ] || prepare_rolling_deadline |
| | | left=$((ROLLING_END - SECONDS)) |
| | | [ "$left" -gt 0 ] || { SCALE_DEADLINE_ACTIVE=0; fail 'load deadline already passed'; return 1; } |
| | | ( trap - ERR; rolling_deadline "$left" ) & |
| | | watchdog=$! |
| | | for n in $DS_NODES; do |
| | | ( if rolling_worker "$n"; then touch "$OUT/load/$n.done"; else touch "$OUT/load/$n.failed"; exit 1; fi ) & |
| | | pids="$pids $!" |
| | | done |
| | | left=$((DISTURB_AT - (SECONDS - (ROLLING_END - DURATION)))) |
| | | [ "$left" -le 0 ] || sleep "$left" |
| | | disturb || failed=1 |
| | | if [ -z "$failed" ]; then |
| | | touch "$OUT/load/post-start" || failed=1 |
| | | left=$((ROLLING_END - SECONDS)) |
| | | if [ "$left" -le 0 ] || ! wait_until "$left" 'post-scale segments finish on every writer' rolling_post_segments_ready; then |
| | | echo "::error::scale change left too little of the $DURATION s limit for verified writes after it" >&2 |
| | | failed=1 |
| | | elif ! rolling_post_segments_complete; then |
| | | echo '::error::a load worker stopped before all post-scale segments were verified' >&2 |
| | | failed=1 |
| | | fi |
| | | fi |
| | | if [ -n "$failed" ]; then |
| | | # Workers stop after their current segment. Keep the deadline guard alive while |
| | | # waiting: a client or docker wait may be stuck until the deadline kills it. |
| | | touch "$OUT/load/stop" || true |
| | | for pid in $pids; do wait "$pid" || true; done |
| | | kill "$watchdog" 2>/dev/null || true |
| | | wait "$watchdog" 2>/dev/null || true |
| | | else |
| | | touch "$OUT/load/stop" || failed=1 |
| | | for pid in $pids; do wait "$pid" || failed=1; done |
| | | kill "$watchdog" 2>/dev/null || true |
| | | wait "$watchdog" 2>/dev/null || true |
| | | fi |
| | | [ ! -e "$OUT/load/cutoff" ] || failed=1 |
| | | [ ! -e "$OUT/load/deadline" ] || failed=1 |
| | | SCALE_DEADLINE_ACTIVE=0 |
| | | ROLLING_ELAPSED=$((SECONDS - (ROLLING_END - DURATION))) |
| | | [ -z "$failed" ] || fail "the rolling load or scale change failed" |
| | | } |
| | |
| | | . "$HERE/load.sh" |
| | | . "$HERE/assert-converged.sh" |
| | | . "$HERE/collect.sh" |
| | | after_convergence() { :; } |
| | | if [ "$DISTURBANCE" != none ]; then |
| | | [ -f "$HERE/disturb-$DISTURBANCE.sh" ] \ |
| | | || { echo "unknown DISTURBANCE $DISTURBANCE: none, or the <name> of a disturb-<name>.sh in $HERE" >&2; exit 2; } |
| | | [ "$DISTURB_AT" -gt 0 ] && [ "$DISTURB_AT" -lt "$DURATION" ] \ |
| | | || { echo "DISTURB_AT=$DISTURB_AT is not within the load of $DURATION s" >&2; exit 2; } |
| | | . "$HERE/disturb-$DISTURBANCE.sh" |
| | | case $DISTURBANCE in |
| | | scale-kept|scale-empty|scale-rs-kept|scale-rs-empty) |
| | | SCALE_VOLUME=${DISTURBANCE##*-} |
| | | . "$HERE/scale-membership.sh" |
| | | . "$HERE/rolling-load.sh" |
| | | . "$HERE/disturb-scale.sh" |
| | | ;; |
| | | *) |
| | | [ -f "$HERE/disturb-$DISTURBANCE.sh" ] \ |
| | | || { echo "unknown DISTURBANCE $DISTURBANCE: none, or the <name> of a disturb-<name>.sh in $HERE" >&2; exit 2; } |
| | | . "$HERE/disturb-$DISTURBANCE.sh" |
| | | ;; |
| | | esac |
| | | fi |
| | | |
| | | # the files of an earlier run would mix into this one's: the samples are appended to, and the |
| | |
| | | # the main shell decides. A run that fails before the online checks - a load check, a wait |
| | | # that timed out, which a reconnection under load would explain - counts the reconnections |
| | | # while the servers are still up |
| | | trap 'code=$?; [ "$BASH_SUBSHELL" -eq 0 ] || exit $code; sampler_stop; [ -f "$OUT/reconnections.txt" ] || [ ! -f "$OUT/logs/${DS_NODES%% *}.mark" ] || record_reconnections || true; timings; collect; summarize failed; [ "$KEEP" = 1 ] || cleanup; exit $code' ERR |
| | | trap 'code=$?; [ "$BASH_SUBSHELL" -eq 0 ] || exit $code; sampler_stop; [ -f "$OUT/reconnections.txt" ] || [ ! -f "$OUT/logs/${DS_NODES%% *}.mark" ] || record_reconnections || true; timings; case $DISTURBANCE in scale-*) collect_scale_bootstrap ;; esac; collect; finalize_failure_csn_traces; summarize failed; [ "$KEEP" = 1 ] || cleanup; exit $code' ERR |
| | | cleanup |
| | | |
| | | phase "topology up ($TOPOLOGY)" |
| | |
| | | mark_logs |
| | | record_server_ids |
| | | |
| | | phase "load ($DURATION s${DISTURBED:+, $DISTURBANCE of $DISTURBED at $DISTURB_AT s})" |
| | | case $DISTURBANCE in scale-*) load_limit='up to ' ;; *) load_limit= ;; esac |
| | | phase "load (${load_limit}$DURATION s${DISTURBED:+, $DISTURBANCE of $DISTURBED at $DISTURB_AT s})" |
| | | # the changes of the load: assert_changelogs looks for gaps among the changes made in between |
| | | LOAD_START_MS=$(($(date +%s) * 1000)) |
| | | case $DISTURBANCE in |
| | | scale-kept|scale-empty|scale-rs-kept|scale-rs-empty) prepare_rolling_deadline ;; |
| | | esac |
| | | sampler_start |
| | | run_load |
| | | case $DISTURBANCE in |
| | | scale-kept|scale-empty|scale-rs-kept|scale-rs-empty) rolling_run_load ;; |
| | | *) run_load ;; |
| | | esac |
| | | sampler_stop |
| | | |
| | | phase "converge" |
| | |
| | | [ "$DISTURBANCE" = none ] || settle |
| | | wait_converged $load_end |
| | | echo "converged in $CONVERGED_IN s" |
| | | after_convergence |
| | | LOAD_END_MS=$(($(date +%s) * 1000)) |
| | | |
| | | if [ "$INJECT_DIVERGENCE" = 1 ]; then |
| | |
| | | |
| | | phase "offline checks" |
| | | stop_all |
| | | check_csn_traces || checks="${checks:+$checks and }the CSN traces" |
| | | assert_offline || checks="${checks:+$checks and }the offline checks" |
| | | diagnose_csn_gaps || checks="${checks:+$checks and }the CSN trace diagnostics" |
| | | [ -z "$checks" ] || fail "$checks failed" |
| | | |
| | | timings |
| | | case $DISTURBANCE in scale-*) collect_scale_bootstrap ;; esac |
| | | summarize passed |
| | | cleanup |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # |
| | | # 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. |
| | | |
| | | """Check both fill boundaries and every intervening CSN in a streamed RS changelog.""" |
| | | |
| | | import importlib.util |
| | | from pathlib import Path |
| | | import sys |
| | | import tarfile |
| | | |
| | | sys.dont_write_bytecode = True |
| | | |
| | | |
| | | def load(name, file): |
| | | spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(file)) |
| | | module = importlib.util.module_from_spec(spec) |
| | | spec.loader.exec_module(module) |
| | | return module |
| | | |
| | | |
| | | fence = load('scale_fence', 'scale-fence.py') |
| | | gaps = load('changelog_gaps', 'changelog-gaps.py') |
| | | |
| | | |
| | | def complete(records, first, last): |
| | | first_seq, first_time = first |
| | | last_seq, last_time = last |
| | | if last_seq - first_seq < 50000 or last_time < first_time: |
| | | raise ValueError('fill boundaries do not span 50001 changes') |
| | | present = {(seq, timestamp) for seq, timestamp, _ in records |
| | | if first_seq <= seq <= last_seq and first_time <= timestamp <= last_time} |
| | | if first not in present or last not in present: |
| | | return False |
| | | return len({seq for seq, _ in present}) == last_seq - first_seq + 1 |
| | | |
| | | |
| | | def main(argv): |
| | | if len(argv) != 4: |
| | | print('usage: scale-coverage.py <base DN> <first fill LDIF> <last fill LDIF>', file=sys.stderr) |
| | | return 2 |
| | | try: |
| | | first_id, first_csn = fence.writer_position(argv[2], 'scale-1') |
| | | last_id, last_csn = fence.writer_position(argv[3], 'scale-50001') |
| | | if first_id != last_id: |
| | | raise ValueError('fill changed originating replica') |
| | | domains, changes = gaps.read_changelog(gaps.from_tar(sys.stdin.buffer)) |
| | | domain = domains.get(argv[1].lower()) |
| | | if domain is None: |
| | | raise ValueError('base DN missing from changelog') |
| | | first = (int(first_csn[20:28], 16), int(first_csn[:16], 16)) |
| | | last = (int(last_csn[20:28], 16), int(last_csn[:16], 16)) |
| | | if not complete(changes.get((domain, first_id), []), first, last): |
| | | print('fill boundary or intervening change is missing') |
| | | return 1 |
| | | print('RS changelog contains both boundaries and every intervening change') |
| | | return 0 |
| | | except (OSError, ValueError, tarfile.TarError, gaps.EncryptedChangelog) as error: |
| | | print('cannot verify RS changelog: %s' % error, file=sys.stderr) |
| | | return 2 |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | sys.exit(main(sys.argv)) |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # |
| | | # 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. |
| | | |
| | | """Run a command until an absolute UTC deadline, including its child processes.""" |
| | | |
| | | import os |
| | | import signal |
| | | import subprocess |
| | | import sys |
| | | import time |
| | | |
| | | |
| | | def main(argv): |
| | | if len(argv) < 3: |
| | | print('usage: scale-deadline.py <epoch milliseconds> <command> [arguments...]', file=sys.stderr) |
| | | return 2 |
| | | process = None |
| | | |
| | | def stop(signum, _frame): |
| | | if process is not None: |
| | | try: |
| | | os.killpg(process.pid, signal.SIGKILL) |
| | | except ProcessLookupError: |
| | | pass |
| | | process.wait() |
| | | raise SystemExit(128 + signum) |
| | | |
| | | signal.signal(signal.SIGTERM, stop) |
| | | signal.signal(signal.SIGINT, stop) |
| | | try: |
| | | remaining = int(argv[1]) / 1000 - time.time() |
| | | if remaining <= 0: |
| | | return 124 |
| | | process = subprocess.Popen(argv[2:], start_new_session=True) |
| | | try: |
| | | code = process.wait(timeout=remaining) |
| | | return code if code >= 0 else 128 - code |
| | | except subprocess.TimeoutExpired: |
| | | try: |
| | | os.killpg(process.pid, signal.SIGKILL) |
| | | except ProcessLookupError: |
| | | pass |
| | | process.wait() |
| | | return 124 |
| | | except (OSError, ValueError) as error: |
| | | print('cannot run before deadline: %s' % error, file=sys.stderr) |
| | | return 2 |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | sys.exit(main(sys.argv)) |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # |
| | | # 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. |
| | | |
| | | """Compare the last fill operation CSN with a surviving RS's changelog position.""" |
| | | |
| | | import base64 |
| | | import importlib.util |
| | | from pathlib import Path |
| | | import re |
| | | import sys |
| | | |
| | | sys.dont_write_bytecode = True |
| | | spec = importlib.util.spec_from_file_location('checkpoint', Path(__file__).with_name('changelog-checkpoint.py')) |
| | | checkpoint = importlib.util.module_from_spec(spec) |
| | | spec.loader.exec_module(checkpoint) |
| | | |
| | | |
| | | def writer_position(path, expected='scale-50001'): |
| | | lines = [] |
| | | for line in Path(path).read_text().splitlines(): |
| | | if line.startswith(' '): |
| | | if not lines or not lines[-1]: |
| | | raise ValueError('orphan LDIF continuation') |
| | | lines[-1] += line[1:] |
| | | else: |
| | | lines.append(line) |
| | | descriptions, histories, dns = [], [], 0 |
| | | for line in lines: |
| | | name, separator, value = line.partition(':') |
| | | if not separator: |
| | | continue |
| | | name = name.lower() |
| | | if name not in ('dn', 'description', 'ds-sync-hist'): |
| | | continue |
| | | if value.startswith(':'): |
| | | value = base64.b64decode(value[1:].strip(), validate=True).decode('utf-8') |
| | | else: |
| | | value = value.lstrip() |
| | | if name == 'dn': |
| | | dns += 1 |
| | | elif name == 'description': |
| | | descriptions.append(value) |
| | | else: |
| | | histories.append(value) |
| | | if dns != 1 or descriptions != [expected]: |
| | | raise ValueError('missing or ambiguous final fill entry') |
| | | matches = [] |
| | | for value in histories: |
| | | match = re.fullmatch(r'description:([0-9a-fA-F]{28}):(?:repl|add):' + re.escape(expected), value, |
| | | re.IGNORECASE) |
| | | if match: |
| | | matches.append(match[1].lower()) |
| | | if len(matches) != 1: |
| | | raise ValueError('missing or ambiguous final fill CSN') |
| | | return int(matches[0][16:20], 16), matches[0] |
| | | |
| | | |
| | | def main(argv): |
| | | if len(argv) != 4: |
| | | print('usage: scale-fence.py <base DN> <fill entry LDIF> <RS monitor LDIF>', file=sys.stderr) |
| | | return 2 |
| | | try: |
| | | server_id, wanted = writer_position(argv[2]) |
| | | current = checkpoint.changelog_positions(argv[3]).get((argv[1].lower(), server_id)) |
| | | if current is None or checkpoint.position(current) < checkpoint.position(wanted): |
| | | print('DS(%s): needs %s, RS has %s' % (server_id, wanted, current or 'no position')) |
| | | return 1 |
| | | print('DS(%s): needs %s, RS has %s (reached)' % (server_id, wanted, current)) |
| | | return 0 |
| | | except (OSError, ValueError) as error: |
| | | print('cannot read fence: %s' % error, file=sys.stderr) |
| | | return 2 |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | sys.exit(main(sys.argv)) |
| New file |
| | |
| | | # |
| | | # 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. |
| | | |
| | | # Check both complete snapshots over one authenticated LDAPS connection. A failed or |
| | | # incomplete search must not count as proof of either presence or absence. |
| | | peer_membership() { # <survivor> <peer host> <present|absent> |
| | | 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" membership "$2" "$3" |
| | | } |
| | | |
| | | peer_removed() { peer_membership "$1" "$2" absent; } |
| | | peer_present() { peer_membership "$1" "$2" present; } |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # |
| | | # 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. |
| | | |
| | | """Read changelog monitors and check membership over loopback LDAPS without a client JVM. |
| | | |
| | | This implements LDAPv3 simple bind and the searches needed for the scale checks. |
| | | A non-success result, referral, malformed response or timeout never yields a snapshot. |
| | | The caller supplies a loopback-only published administration port and an absolute deadline; |
| | | the bind password is read from standard input, not from the command line. |
| | | """ |
| | | |
| | | import base64 |
| | | import re |
| | | import socket |
| | | import ssl |
| | | import sys |
| | | import time |
| | | |
| | | MAX_FRAME = 8 * 1024 * 1024 |
| | | MAX_SNAPSHOT = 8 * 1024 * 1024 |
| | | |
| | | |
| | | class LdapError(Exception): |
| | | pass |
| | | |
| | | |
| | | def tlv(tag, value): |
| | | length = len(value) |
| | | if length < 128: |
| | | encoded = bytes([length]) |
| | | else: |
| | | raw = length.to_bytes((length.bit_length() + 7) // 8, 'big') |
| | | encoded = bytes([0x80 | len(raw)]) + raw |
| | | return bytes([tag]) + encoded + value |
| | | |
| | | |
| | | def fields(data): |
| | | position = 0 |
| | | while position < len(data): |
| | | if position + 2 > len(data): |
| | | raise LdapError('truncated BER field') |
| | | tag, length = data[position], data[position + 1] |
| | | position += 2 |
| | | if length & 0x80: |
| | | size = length & 0x7f |
| | | if not size or size > 4 or position + size > len(data): |
| | | raise LdapError('invalid BER length') |
| | | length = int.from_bytes(data[position:position + size], 'big') |
| | | position += size |
| | | if length > MAX_FRAME or position + length > len(data): |
| | | raise LdapError('truncated or oversized BER value') |
| | | yield tag, data[position:position + length] |
| | | position += length |
| | | |
| | | |
| | | def receive(sock, length, deadline): |
| | | data = bytearray() |
| | | while len(data) < length: |
| | | remaining = deadline - time.monotonic() |
| | | if remaining <= 0: |
| | | raise TimeoutError('LDAP request timed out') |
| | | sock.settimeout(remaining) |
| | | try: |
| | | chunk = sock.recv(length - len(data)) |
| | | except socket.timeout as error: |
| | | raise TimeoutError('LDAP request timed out') from error |
| | | if not chunk: |
| | | raise EOFError('LDAP connection closed before the response') |
| | | data.extend(chunk) |
| | | return bytes(data) |
| | | |
| | | |
| | | def transmit(sock, data, deadline): |
| | | remaining = deadline - time.monotonic() |
| | | if remaining <= 0: |
| | | raise TimeoutError('LDAP request timed out') |
| | | sock.settimeout(remaining) |
| | | try: |
| | | sock.sendall(data) |
| | | except socket.timeout as error: |
| | | raise TimeoutError('LDAP request timed out') from error |
| | | |
| | | |
| | | def read_frame(sock, deadline): |
| | | header = receive(sock, 2, deadline) |
| | | if header[0] != 0x30: |
| | | raise LdapError('LDAP response is not a sequence') |
| | | length = header[1] |
| | | if length & 0x80: |
| | | size = length & 0x7f |
| | | if not size or size > 4: |
| | | raise LdapError('invalid LDAP message length') |
| | | length = int.from_bytes(receive(sock, size, deadline), 'big') |
| | | if length > MAX_FRAME: |
| | | raise LdapError('LDAP message exceeds size limit') |
| | | return receive(sock, length, deadline) |
| | | |
| | | |
| | | def message(sock, wanted_id, deadline): |
| | | parts = list(fields(read_frame(sock, deadline))) |
| | | if len(parts) < 2 or parts[0][0] != 0x02 or not parts[0][1]: |
| | | raise LdapError('invalid LDAP message envelope') |
| | | if int.from_bytes(parts[0][1], 'big', signed=True) != wanted_id: |
| | | raise LdapError('unexpected LDAP message ID') |
| | | if len(parts) > 3 or (len(parts) == 3 and parts[2][0] != 0xa0): |
| | | raise LdapError('unexpected LDAP message fields') |
| | | return parts[1] |
| | | |
| | | |
| | | def require_success(value): |
| | | parts = list(fields(value)) |
| | | if len(parts) < 3 or [part[0] for part in parts[:3]] != [0x0a, 0x04, 0x04] or not parts[0][1]: |
| | | raise LdapError('invalid LDAP result') |
| | | code = int.from_bytes(parts[0][1], 'big', signed=True) |
| | | if code != 0: |
| | | raise LdapError('LDAP operation failed with result %s' % code) |
| | | |
| | | |
| | | def entry_ldif(value): |
| | | parts = list(fields(value)) |
| | | if len(parts) != 2 or parts[0][0] != 0x04 or parts[1][0] != 0x30: |
| | | raise LdapError('invalid LDAP search entry') |
| | | lines = ['dn:: ' + base64.b64encode(parts[0][1]).decode('ascii')] |
| | | for tag, attr in fields(parts[1][1]): |
| | | items = list(fields(attr)) |
| | | if tag != 0x30 or len(items) != 2 or items[0][0] != 0x04 or items[1][0] != 0x31: |
| | | raise LdapError('invalid LDAP attribute') |
| | | name = items[0][1].decode('ascii') |
| | | if not re.fullmatch(r'[A-Za-z0-9;-]+', name): |
| | | raise LdapError('invalid LDAP attribute name') |
| | | for value_tag, content in fields(items[1][1]): |
| | | if value_tag != 0x04: |
| | | raise LdapError('invalid LDAP attribute value') |
| | | lines.append(name + ':: ' + base64.b64encode(content).decode('ascii')) |
| | | 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) |
| | | tag, result = message(sock, 1, deadline) |
| | | if tag != 0x61: |
| | | raise LdapError('expected LDAP bind response') |
| | | require_success(result) |
| | | 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))) |
| | | transmit(sock, tlv(0x30, tlv(0x02, b'\x02') + tlv(0x63, query)), deadline) |
| | | entries = [] |
| | | size = 0 |
| | | while True: |
| | | tag, value = message(sock, 2, deadline) |
| | | if tag == 0x64: |
| | | entry = entry_ldif(value) |
| | | size += len(entry) |
| | | if size > MAX_SNAPSHOT: |
| | | raise LdapError('LDAP snapshot exceeds size limit') |
| | | entries.append(entry) |
| | | elif tag == 0x65: |
| | | require_success(value) |
| | | if time.monotonic() >= deadline: |
| | | raise TimeoutError('LDAP response completed after the deadline') |
| | | return 'version: 1\n\n' + ''.join(entries) |
| | | else: |
| | | raise LdapError('unexpected LDAP search response') |
| | | |
| | | |
| | | def entry_attributes(value): |
| | | parts = list(fields(value)) |
| | | if len(parts) != 2 or parts[0][0] != 0x04 or parts[1][0] != 0x30: |
| | | raise LdapError('invalid LDAP search entry') |
| | | parts[0][1].decode('utf-8') |
| | | attributes = {} |
| | | for tag, attribute in fields(parts[1][1]): |
| | | items = list(fields(attribute)) |
| | | if tag != 0x30 or len(items) != 2 or items[0][0] != 0x04 or items[1][0] != 0x31: |
| | | raise LdapError('invalid LDAP attribute') |
| | | name = items[0][1].decode('ascii').lower() |
| | | if not re.fullmatch(r'[a-z0-9;-]+', name) or name in attributes: |
| | | raise LdapError('invalid or duplicate LDAP attribute') |
| | | values = [] |
| | | for value_tag, content in fields(items[1][1]): |
| | | if value_tag != 0x04: |
| | | raise LdapError('invalid LDAP attribute value') |
| | | values.append(content.decode('utf-8')) |
| | | attributes[name] = values |
| | | return attributes |
| | | |
| | | |
| | | def membership_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))) |
| | | transmit(sock, tlv(0x30, tlv(0x02, bytes([message_id])) + tlv(0x63, query)), deadline) |
| | | entries, size = [], 0 |
| | | while True: |
| | | tag, value = message(sock, message_id, deadline) |
| | | if tag == 0x64: |
| | | size += len(value) |
| | | if size > MAX_SNAPSHOT: |
| | | raise LdapError('LDAP snapshot exceeds size limit') |
| | | entries.append(entry_attributes(value)) |
| | | elif tag == 0x65: |
| | | require_success(value) |
| | | if time.monotonic() >= deadline: |
| | | raise TimeoutError('LDAP response completed after the deadline') |
| | | return entries |
| | | else: |
| | | raise LdapError('unexpected LDAP search response') |
| | | |
| | | |
| | | def membership_matches(registry, config, peer, wanted): |
| | | if wanted not in ('present', 'absent') or not registry or not config: |
| | | return False |
| | | peer = peer.lower() |
| | | def matches(host): |
| | | host = host.lower() |
| | | return host == peer or host.split('.')[0] == peer |
| | | hosts = [host for entry in registry for host in entry.get('hostname', [])] |
| | | if not hosts or any(not host for host in hosts): |
| | | return False |
| | | found = any(matches(host) for host in hosts) |
| | | lists = [any(matches(re.sub(r':[0-9]+$', '', host)) |
| | | for host in entry.get('ds-cfg-replication-server', [])) for entry in config] |
| | | return (found and all(lists)) if wanted == 'present' else (not found and not any(lists)) |
| | | |
| | | |
| | | 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') |
| | | 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') |
| | | 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) |
| | | return 2 |
| | | try: |
| | | port, load_deadline = int(argv[1]), int(argv[2]) / 1000 |
| | | if not 1 <= port <= 65535: |
| | | raise ValueError('invalid loopback port') |
| | | password = sys.stdin.buffer.read(4097) |
| | | if not password or len(password) > 4096: |
| | | raise ValueError('invalid bind password') |
| | | remaining = min(45.0, load_deadline - time.time()) |
| | | if remaining <= 0: |
| | | raise TimeoutError('load deadline reached') |
| | | deadline = time.monotonic() + remaining |
| | | context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| | | context.check_hostname = False |
| | | 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 |
| | | if time.monotonic() >= deadline or time.time() >= load_deadline: |
| | | raise TimeoutError('LDAP response completed after the deadline') |
| | | if output is not None: |
| | | sys.stdout.write(output) |
| | | return 0 if matched else 1 |
| | | except (TimeoutError, socket.timeout): |
| | | print('timeout=' + ('load' if time.time() >= load_deadline else 'query'), file=sys.stderr) |
| | | return 124 |
| | | except (OSError, ValueError, UnicodeError, LdapError, EOFError) as error: |
| | | print('scale monitor failed: %s' % error, file=sys.stderr) |
| | | return 1 |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | sys.exit(main(sys.argv)) |
| New file |
| | |
| | | # |
| | | # 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. |
| | | |
| | | """Fixture tests of the failover changelog checkpoint, without a Docker topology.""" |
| | | |
| | | import base64 |
| | | from pathlib import Path |
| | | import subprocess |
| | | import sys |
| | | import tempfile |
| | | import unittest |
| | | |
| | | SCRIPT = Path(__file__).with_name("changelog-checkpoint.py") |
| | | BASE = "dc=example,dc=com" |
| | | CSN = "000001a1a1e836e400010000000a" |
| | | |
| | | |
| | | def entry(domain=BASE, replica=1, csn=CSN): |
| | | return ("dn: cn=Changelog for DS(%s),cn=%s,cn=monitor\n" |
| | | "replicationServer-database: %s\ndomain-name: %s\n%s\n" |
| | | % (replica, domain, replica, domain, |
| | | "last-change: " + csn + " Tue Nov 03 14:55:12 UTC 2026\n" if csn else "")) |
| | | |
| | | |
| | | class CheckpointTest(unittest.TestCase): |
| | | def run_check(self, reference, current, ids="1 d0\n"): |
| | | with tempfile.TemporaryDirectory() as directory: |
| | | paths = [Path(directory) / name for name in ("ids", "reference", "current")] |
| | | for path, contents in zip(paths, (ids, reference, current)): |
| | | path.write_text(contents) |
| | | result = subprocess.run([sys.executable, "-I", str(SCRIPT), BASE, |
| | | *map(str, paths)], capture_output=True, text=True) |
| | | return result.returncode, result.stdout + result.stderr |
| | | |
| | | def test_equal_or_newer_position_passes(self): |
| | | # Dropping equality or comparing sequence alone rejects a valid caught-up RS. |
| | | for csn in (CSN, "000001a1a1e836e400010000000b", "000001a1a1e836e5000100000000"): |
| | | with self.subTest(csn=csn): |
| | | code, output = self.run_check(entry(), entry(csn=csn)) |
| | | self.assertEqual(code, 0, output) |
| | | |
| | | def test_older_position_blocks_restart(self): |
| | | for csn in ("000001a1a1e836e4000100000009", "000001a1a1e836e300017fffffff"): |
| | | with self.subTest(csn=csn): |
| | | code, output = self.run_check(entry(), entry(csn=csn)) |
| | | self.assertEqual(code, 1, output) |
| | | self.assertIn(BASE, output) |
| | | self.assertIn(CSN, output) |
| | | |
| | | def test_every_domain_and_origin_must_reach_the_checkpoint(self): |
| | | schema = entry("cn=schema") |
| | | second = entry(replica=2, csn="000001a1a1e836e400020000000a") |
| | | reference = entry() + schema + second |
| | | for current in (entry() + second, entry() + schema, |
| | | entry() + second + entry("cn=schema", csn="000001a1a1e836e4000100000009")): |
| | | with self.subTest(current=current): |
| | | self.assertEqual(self.run_check(reference, current, "1 d0\n2 d1\n")[0], 1) |
| | | self.assertEqual(self.run_check(reference, reference, "1 d0\n2 d1\n")[0], 0) |
| | | |
| | | def test_missing_workload_origin_invalidates_reference(self): |
| | | code, output = self.run_check(entry(), entry(), "1 d0\n2 d1\n") |
| | | self.assertEqual(code, 2, output) |
| | | self.assertIn("2", output) |
| | | |
| | | def test_empty_or_incomplete_reads_never_pass(self): |
| | | for reference, current in (("", entry()), (entry(), ""), |
| | | (entry(csn=None), entry()), (entry(), entry(csn=None))): |
| | | with self.subTest(reference=reference, current=current): |
| | | self.assertNotEqual(self.run_check(reference, current)[0], 0) |
| | | |
| | | def test_unused_empty_logs_do_not_block(self): |
| | | reference = entry() + entry("cn=schema", 2, None) |
| | | self.assertEqual(self.run_check(reference, entry())[0], 0) |
| | | |
| | | def test_malformed_or_duplicate_positions_are_rejected(self): |
| | | bad = [entry(csn="bad"), entry(csn="000001a1a1e836e400020000000a"), |
| | | entry().replace("domain-name: " + BASE + "\n", ""), |
| | | entry() + entry(), entry().replace("last-change:", "last-change:<"), |
| | | entry().replace("replicationServer-database: 1", "replicationServer-database: nope"), |
| | | entry().replace("domain-name: " + BASE, "domain-name:: invalid!"), |
| | | entry() + "ldapsearch failed\n"] |
| | | for malformed in bad: |
| | | for reference, current in ((malformed, entry()), (entry(), malformed)): |
| | | with self.subTest(reference=reference, current=current): |
| | | self.assertEqual(self.run_check(reference, current)[0], 2) |
| | | |
| | | def test_ldif_folding_base64_and_case_are_supported(self): |
| | | encoded = base64.b64encode(BASE.upper().encode()).decode() |
| | | reference = entry().replace("domain-name: " + BASE, "DOMAIN-NAME:: " + encoded) |
| | | reference = reference.replace(CSN, CSN[:12] + "\n " + CSN[12:]) |
| | | self.assertEqual(self.run_check(reference, entry())[0], 0) |
| | | |
| | | def test_empty_origin_list_is_invalid(self): |
| | | self.assertEqual(self.run_check(entry(), entry(), "")[0], 2) |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | unittest.main() |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # 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. |
| | | |
| | | import io |
| | | from pathlib import Path |
| | | import subprocess |
| | | import sys |
| | | import tarfile |
| | | import tempfile |
| | | import unittest |
| | | import base64 |
| | | import zlib |
| | | |
| | | |
| | | SCRIPT = Path(__file__).with_name('changelog-gaps.py') |
| | | |
| | | |
| | | def changelog(records=((1, 1000000), (3, 1000010))): |
| | | stream = bytearray() |
| | | for sequence, timestamp in records: |
| | | csn = '%016x%04x%08x' % (timestamp, 1, sequence) |
| | | message = b'\x16\x00' + csn.encode('ascii') |
| | | stream += len(message).to_bytes(4, 'big') + message |
| | | result = io.BytesIO() |
| | | with tarfile.open(fileobj=result, mode='w') as tar: |
| | | for name, data in [('changelogDb/domains.state', b'1:dc=example,dc=com\n'), |
| | | ('changelogDb/1.dom/1.server/head.log', bytes(stream))]: |
| | | info = tarfile.TarInfo(name) |
| | | info.size = len(data) |
| | | tar.addfile(info, io.BytesIO(data)) |
| | | return result.getvalue() |
| | | |
| | | |
| | | class ChangelogGapTest(unittest.TestCase): |
| | | def setUp(self): |
| | | self.tmp = tempfile.TemporaryDirectory() |
| | | self.addCleanup(self.tmp.cleanup) |
| | | self.root = Path(self.tmp.name) |
| | | self.snapshots = self.root / 'snapshots' |
| | | self.snapshots.mkdir() |
| | | |
| | | def snapshot(self, sequence=2, timestamp=1000005, server=1, domain='dc=example,dc=com', |
| | | captured=1010000): |
| | | csn = '%016x%04x%08x' % (timestamp, server, sequence) |
| | | (self.snapshots / 'offline-return-r0.txt').write_text( |
| | | 'capture-start-ms %d\ndomains.state\n1:%s\n1.dom/1.server/offline.state %s\n' |
| | | % (captured, domain, csn)) |
| | | |
| | | def allocation_trace(self, events, token='first', node='d0'): |
| | | directory = self.root / 'traces' / node |
| | | directory.mkdir(parents=True, exist_ok=True) |
| | | body = b''.join(('%s %s %016x%04x%08x\n' % |
| | | (kind, base64.b64encode(domain.encode()).decode(), time, sid, seq)).encode() |
| | | for kind, domain, time, sid, seq in events) |
| | | (directory / (token + '.txt')).write_bytes( |
| | | ('START 1 %s\n' % token).encode() + body |
| | | + ('END %d %08x\n' % (len(events), zlib.crc32(body))).encode()) |
| | | with (self.root / 'expected.txt').open('a') as manifest: |
| | | manifest.write('%s %s\n' % (node, token)) |
| | | |
| | | def run_check(self, evidence=True, records=((1, 1000000), (3, 1000010)), traces=False): |
| | | args = [sys.executable, str(SCRIPT), 'dc=example,dc=com', '900000', '1100000'] |
| | | if evidence: |
| | | args += ['--offline-snapshots', str(self.snapshots)] |
| | | if traces: |
| | | args += ['--csn-traces', str(self.root / 'traces'), |
| | | '--csn-manifest', str(self.root / 'expected.txt')] |
| | | return subprocess.run(args, input=changelog(records), capture_output=True, text=False, timeout=10) |
| | | |
| | | def test_complete_offline_only_allocation_is_not_a_missing_update(self): |
| | | self.allocation_trace([('O', 'dc=example,dc=com', 1000005, 1, 2)]) |
| | | result = self.run_check(traces=True) |
| | | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) |
| | | self.assertIn(b'0 missing', result.stdout) |
| | | self.assertIn(b'offline-only 2:', result.stdout) |
| | | self.assertEqual(self.run_check().returncode, 1) |
| | | |
| | | def test_reuse_in_another_generation_or_node_blocks_classification(self): |
| | | self.allocation_trace([('O', 'dc=example,dc=com', 1000005, 1, 2)]) |
| | | self.allocation_trace([('L', 'dc=example,dc=com', 1100010, 1, 2)], 'second', 'd1') |
| | | result = self.run_check(traces=True) |
| | | self.assertEqual(result.returncode, 1, result.stdout + result.stderr) |
| | | self.assertIn(b'missing 2,', result.stdout) |
| | | |
| | | def test_offline_other_domain_does_not_cover_gap(self): |
| | | self.allocation_trace([('O', 'cn=other', 1000005, 1, 2)]) |
| | | self.assertEqual(self.run_check(traces=True).returncode, 1) |
| | | |
| | | def test_offline_only_does_not_hide_other_missing_updates(self): |
| | | self.allocation_trace([('O', 'dc=example,dc=com', 1000005, 1, 2)]) |
| | | result = self.run_check(traces=True, records=((1, 1000000), (3, 1000010), (5, 1000020))) |
| | | self.assertEqual(result.returncode, 1, result.stdout + result.stderr) |
| | | self.assertIn(b'missing 4,', result.stdout) |
| | | |
| | | def test_incomplete_trace_never_excuses_offline_gap(self): |
| | | self.allocation_trace([('O', 'dc=example,dc=com', 1000005, 1, 2)]) |
| | | path = self.root / 'traces/d0/first.txt' |
| | | path.write_bytes(path.read_bytes()[:-2]) |
| | | result = self.run_check(traces=True) |
| | | self.assertEqual(result.returncode, 2, result.stdout + result.stderr) |
| | | self.assertIn(b'incomplete CSN allocation trace', result.stdout) |
| | | |
| | | def test_reports_an_exact_offline_csn_without_waiving_the_gap(self): |
| | | self.assertEqual(self.run_check().returncode, 1) |
| | | self.snapshot() |
| | | result = self.run_check() |
| | | self.assertEqual(result.returncode, 1, result.stdout.decode() + result.stderr.decode()) |
| | | self.assertIn(b'offline 2: captured CSN', result.stdout) |
| | | self.assertIn(b'missing 2,', result.stdout) |
| | | self.assertEqual(self.run_check(evidence=False).returncode, 1) |
| | | |
| | | def test_a_confirmed_marker_does_not_hide_another_missing_change(self): |
| | | self.snapshot() |
| | | result = self.run_check(records=((1, 1000000), (3, 1000010), (5, 1000020))) |
| | | self.assertEqual(result.returncode, 1) |
| | | self.assertIn(b'offline 2:', result.stdout) |
| | | self.assertIn(b'missing 4,', result.stdout) |
| | | |
| | | def test_does_not_excuse_a_different_number_domain_id_or_time(self): |
| | | for kwargs in ({'sequence': 4}, {'server': 2}, {'domain': 'cn=other'}, |
| | | {'timestamp': 1000020}, {'captured': 1000006}): |
| | | with self.subTest(kwargs=kwargs): |
| | | self.snapshot(**kwargs) |
| | | result = self.run_check() |
| | | self.assertEqual(result.returncode, 1) |
| | | self.assertNotIn(b'offline 2:', result.stdout) |
| | | |
| | | def test_reused_or_future_logical_time_never_suppresses_a_gap(self): |
| | | self.snapshot() |
| | | result = self.run_check() |
| | | self.assertEqual(result.returncode, 1) |
| | | self.assertIn(b'a restart may have reused the sequence', result.stdout) |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | unittest.main() |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | NETWORK=test ROOT_PASSWORD=password SERVER_JAVA_ARGS=-Xmx1g IMAGE=test PEERS=d0,r0 DISTURBANCE=empty-rs |
| | | CSN_TRACE=1 DS_NODES=d0 RS_NODES=r0 |
| | | . "$HERE/topology-up.sh" |
| | | . "$HERE/collect.sh" |
| | | docker() { |
| | | printf '%s\n' "$*" >>"$OUT/docker-calls" |
| | | [ "${FAIL_RUN:-0}" != 1 ] || [ "$1" != run ] |
| | | } |
| | | start_server d0 directory |
| | | token=$(cat "$OUT/csn-trace-tokens/d0") |
| | | grep -F -- "-Dorg.opends.server.replication.csnTraceToken=$token" "$OUT/docker-calls" >/dev/null |
| | | grep -Fx "d0 $token" "$OUT/csn-trace-expected.txt" >/dev/null |
| | | expect_csn_trace_restart d0 |
| | | restart_token=$(tail -1 "$OUT/csn-trace-expected.txt" | awk '{print $2}') |
| | | [ "$restart_token" != "$token" ] || { echo 'restart reused the previous generation token' >&2; exit 1; } |
| | | grep -F "/opt/opendj/data/csn-trace-token-$token" "$OUT/docker-calls" >/dev/null \ |
| | | || { echo 'restart token was not copied to the stopped container' >&2; exit 1; } |
| | | start_server r0 replication |
| | | [ ! -f "$OUT/csn-trace-tokens/r0" ] |
| | | if (FAIL_RUN=1; start_server d1 directory); then |
| | | echo 'a failed Docker start was accepted' >&2; exit 1 |
| | | fi |
| | | [ ! -f "$OUT/csn-trace-tokens/d1" ] |
| | | mkdir -p "$OUT/changelog" |
| | | printf 'CSN allocation traces complete; local allocations may be uncommitted\n' >"$OUT/csn-trace-validation.txt" |
| | | cat >"$OUT/changelog/r0.txt" <<'GAPS' |
| | | replica 14800 (d0): 2 changes in the load, sequence numbers 18021 to 18023, 1 missing |
| | | missing 18022, between the add 18021 (1) and the modify 18023 (2) |
| | | replica 14900: 2 changes in the load, sequence numbers 18031 to 18033, 1 missing |
| | | missing 18032, between the add 18031 (1) and the modify 18033 (2) |
| | | GAPS |
| | | python3() { printf '%s\n' "$*" >"$OUT/diagnosis-call"; } |
| | | diagnose_csn_gaps |
| | | grep -F '14800:18022' "$OUT/diagnosis-call" >/dev/null || { echo 'gap was not looked up in the trace' >&2; exit 1; } |
| | | grep -F '14900:18032' "$OUT/diagnosis-call" >/dev/null || { echo 'unannotated gap was not looked up in the trace' >&2; exit 1; } |
| | | rm "$OUT/diagnosis-call" |
| | | printf 'incomplete\n' >"$OUT/csn-trace-validation.txt" |
| | | diagnose_csn_gaps |
| | | [ ! -e "$OUT/diagnosis-call" ] || { echo 'incomplete trace was used as evidence' >&2; exit 1; } |
| | | docker() { [ "$1" != cp ]; } |
| | | python3() { echo 'CSN allocation traces complete; local allocations may be uncommitted'; } |
| | | CSN_TRACES_COMPLETE=1 |
| | | if check_csn_traces >/dev/null 2>&1; then |
| | | echo 'failed trace copy was accepted' >&2; exit 1 |
| | | fi |
| | | [ "$CSN_TRACES_COMPLETE" = 0 ] || { echo 'failed copy retained permission to classify gaps' >&2; exit 1; } |
| | | if grep -Fx 'CSN allocation traces complete; local allocations may be uncommitted' "$OUT/csn-trace-validation.txt" >/dev/null; then |
| | | echo 'failed trace copy left a complete validation marker' >&2; exit 1 |
| | | fi |
| | | DS_NODES='d0 d1' |
| | | docker() { |
| | | case $1 in |
| | | inspect) return 0 ;; |
| | | stop) printf '%s\n' "$4" >>"$OUT/stopped" ;; |
| | | esac |
| | | } |
| | | check_csn_traces() { |
| | | [ "${KEEP:-0}" = 1 ] || [ "$(wc -l <"$OUT/stopped")" -eq 2 ] \ |
| | | || { echo 'traces checked before all servers stopped' >&2; return 1; } |
| | | echo checked >>"$OUT/trace-checks" |
| | | } |
| | | KEEP=0 |
| | | finalize_failure_csn_traces |
| | | [ "$(wc -l <"$OUT/stopped")" -eq 2 ] || { echo 'not all DS were stopped' >&2; exit 1; } |
| | | rm "$OUT/stopped" |
| | | KEEP=1 |
| | | finalize_failure_csn_traces |
| | | [ ! -e "$OUT/stopped" ] || { echo 'KEEP=1 stopped a DS' >&2; exit 1; } |
| | | [ "$(wc -l <"$OUT/trace-checks")" -eq 2 ] || { echo 'traces were not checked' >&2; exit 1; } |
| | | echo 'CSN trace generations and Docker failures passed' |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # 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. |
| | | |
| | | import importlib.util |
| | | import sys |
| | | import tempfile |
| | | import unittest |
| | | import zlib |
| | | from pathlib import Path |
| | | |
| | | sys.dont_write_bytecode = True |
| | | spec = importlib.util.spec_from_file_location('csn_trace', Path(__file__).with_name('csn-trace.py')) |
| | | trace = importlib.util.module_from_spec(spec) |
| | | spec.loader.exec_module(trace) |
| | | |
| | | |
| | | class TraceTest(unittest.TestCase): |
| | | def setUp(self): |
| | | self.tmp = tempfile.TemporaryDirectory() |
| | | self.root = Path(self.tmp.name) |
| | | self.addCleanup(self.tmp.cleanup) |
| | | self.manifest = self.root / 'expected.txt' |
| | | self.manifest.write_text('d0 token0\n') |
| | | self.file = self.root / 'd0' / 'trace-1.txt' |
| | | self.file.parent.mkdir() |
| | | self.events = [b'O ZGM9ZXhhbXBsZQ== 000001a1d4733f4439d000004666\n', |
| | | b'L ZGM9ZXhhbXBsZQ== 000001a1d474069539d000004666\n'] |
| | | self.write_trace() |
| | | |
| | | def write_trace(self): |
| | | body = b''.join(self.events) |
| | | self.file.write_bytes(b'START 1 token0\n' + body |
| | | + ('END %d %08x\n' % (len(self.events), zlib.crc32(body))).encode()) |
| | | |
| | | def test_reused_sequence_reports_local_and_offline_allocations(self): |
| | | events = trace.read_traces(self.root, self.manifest, {(14800, 18022)}) |
| | | self.assertEqual([e[0] for e in events], ['O', 'L']) |
| | | self.assertNotEqual(events[0][2], events[1][2]) |
| | | |
| | | def test_truncated_and_modified_traces_fail_closed(self): |
| | | data = self.file.read_bytes() |
| | | for bad in (data[:-2], data.replace(b'L ', b'O '), data + b'L bad\n'): |
| | | self.file.write_bytes(bad) |
| | | with self.assertRaises(ValueError): |
| | | trace.read_traces(self.root, self.manifest, set()) |
| | | |
| | | def test_missing_generation_and_missing_file_fail_closed(self): |
| | | self.manifest.write_text('d0 token0\nd0 token1\n') |
| | | with self.assertRaises(ValueError): |
| | | trace.read_traces(self.root, self.manifest, set()) |
| | | self.file.unlink() |
| | | with self.assertRaises(ValueError): |
| | | trace.read_traces(self.root, self.manifest, set()) |
| | | |
| | | def test_repeated_expected_token_fails_even_if_two_files_exist(self): |
| | | self.manifest.write_text('d0 token0\nd0 token0\n') |
| | | (self.file.parent / 'trace-2.txt').write_bytes(self.file.read_bytes()) |
| | | with self.assertRaises(ValueError): |
| | | trace.read_traces(self.root, self.manifest, set()) |
| | | |
| | | def test_unknown_generation_fails_closed(self): |
| | | self.manifest.write_text('d0 other\n') |
| | | with self.assertRaises(ValueError): |
| | | trace.read_traces(self.root, self.manifest, set()) |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | unittest.main() |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # |
| | | # 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. |
| | | |
| | | set -eE -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d) |
| | | trap 'rm -rf "$OUT"' EXIT |
| | | mkdir -p "$OUT/logs" |
| | | if [ ! -f "$HERE/disturb-empty-rs.sh" ]; then |
| | | echo '::error::empty-rs disturbance is missing' |
| | | exit 1 |
| | | fi |
| | | DS_NODES='d0 d1 d2 d3' RS_ONLY='r0 r1' RS_NODES=$RS_ONLY ALL_NODES="$DS_NODES $RS_ONLY" |
| | | DISTURB_TIMEOUT=900 QUIESCE_TIMEOUT=4500 DURATION=1800 LOAD_START_MS=100000 STAT_INTERVAL=10 CONVERGED_IN=10 NETWORK=fixture |
| | | . "$HERE/disturb-empty-rs.sh" |
| | | record() { printf '%s\n' "$*" >>"$OUT/calls"; } |
| | | docker() { |
| | | record "docker $*" |
| | | case $1 in cp) printf 'old log\n' >"$3" ;; inspect) echo 172.18.0.9 ;; esac |
| | | } |
| | | start_server() { record "start_server $*"; } |
| | | window_open() { record "window_open $*"; } |
| | | window_close() { record window_close; } |
| | | errors_lines() { echo 2; } |
| | | wait_until() { |
| | | record "wait $2: ${*:3}" |
| | | [ "${FAIL_WAIT:-}" != "${3:-}" ] |
| | | } |
| | | wait_converged() { record convergence; } |
| | | sleep() { :; } |
| | | date() { echo 400; } |
| | | fail() { echo "::error::$1"; return 1; } |
| | | |
| | | disturb |
| | | settle |
| | | after_convergence |
| | | cat >"$OUT/want" <<'WANT' |
| | | window_open dns:r1 cert:d1:r1 180 |
| | | stop d1 |
| | | stop r1 |
| | | archive r1 |
| | | remove r1 |
| | | remove-volume r1 |
| | | start r1 |
| | | rs-ready r1 |
| | | start d1 |
| | | ds-ready d1 |
| | | window_close |
| | | settle d1 |
| | | settle r1 |
| | | checkpoint r1 r0 |
| | | window_open dns:r0 180 |
| | | stop r0 |
| | | connected d0 r1 |
| | | connected d1 r1 |
| | | connected d2 r1 |
| | | connected d3 r1 |
| | | start r0 |
| | | rs-ready r0 |
| | | settle r0 |
| | | window_close |
| | | convergence |
| | | checkpoint r0 r1 |
| | | window_open dns:r1 180 |
| | | stop r1 |
| | | connected d0 r0 |
| | | connected d1 r0 |
| | | connected d2 r0 |
| | | connected d3 r0 |
| | | start r1 |
| | | rs-ready r1 |
| | | settle r1 |
| | | window_close |
| | | convergence |
| | | WANT |
| | | # Normalize only timings and wait descriptions; preserve operation order and targets. |
| | | awk ' |
| | | /^window_open/ {print; next} |
| | | /^window_close$/ {print; next} |
| | | /^docker stop/ {print "stop", $NF; next} |
| | | /^docker start/ {print "start", $NF; next} |
| | | /^docker cp/ {print "archive", substr($3,1,index($3,":")-1); next} |
| | | /^docker rm/ {print "remove", $NF; next} |
| | | /^docker volume rm/ {sub(/^vol-/,"",$NF); print "remove-volume",$NF; next} |
| | | /^start_server/ {print "start",$2; next} |
| | | /^wait .*rs_serves_since/ {print "rs-ready",$(NF-1); next} |
| | | /^wait .*started_since/ {print "ds-ready",$(NF-1); next} |
| | | /^wait .*bootstrap_ended/ {print "settle",$NF; next} |
| | | /^wait .*rs_caught_up/ {print "checkpoint",$(NF-1),$NF; next} |
| | | /^wait .*connected_to/ {print "connected",$(NF-1),$NF; next} |
| | | /^convergence$/ {print} |
| | | ' "$OUT/calls" >"$OUT/got" |
| | | diff -u "$OUT/want" "$OUT/got" |
| | | [ -s "$OUT/logs/r1.previous" ] || { echo '::error::old RS log was not retained'; exit 1; } |
| | | grep -Fx '2 2 cert-peer:r1:172.18.0.9' "$OUT/logs/r1.windows" >/dev/null \ |
| | | || { echo '::error::DS address missing from RS certificate window'; exit 1; } |
| | | # A failed checkpoint must not stop the only other RS. |
| | | : >"$OUT/calls" |
| | | set +e |
| | | (set -e; FAIL_WAIT=rs_caught_up; after_convergence) >"$OUT/failure" 2>&1 |
| | | code=$? |
| | | set -e |
| | | if [ "$code" -eq 0 ]; then |
| | | echo '::error::failed checkpoint was accepted'; exit 1 |
| | | fi |
| | | if grep '^docker stop' "$OUT/calls" >/dev/null; then |
| | | echo '::error::RS stopped before its peer caught up'; exit 1 |
| | | fi |
| | | # Exercise the real monitor predicate: a missing address, failed search or another RS must |
| | | # never count as the DS having connected to the intended peer. |
| | | NETWORK=fixture MONITOR_DOMAIN='cn=dc_example_dc_com,cn=Replication,cn=monitor' |
| | | docker() { [ "$1" = inspect ] || return 1; [ "${NO_ADDRESS:-0}" = 1 ] || echo 172.18.0.9; } |
| | | admin_search() { [ "${SEARCH_FAILED:-0}" = 0 ] || return 1; printf '%s\n' "${MONITOR_LINE:-connected-to: 172.18.0.9:8989}"; } |
| | | connected_to d0 r1 || { echo '::error::matching RS was rejected'; exit 1; } |
| | | if (NO_ADDRESS=1; connected_to d0 r1) || (SEARCH_FAILED=1; connected_to d0 r1) || \ |
| | | (MONITOR_LINE='connected-to: 172.18.0.10:8989'; connected_to d0 r1) || \ |
| | | (MONITOR_LINE='connected-to: 172.18.0.9:8990'; connected_to d0 r1); then |
| | | echo '::error::an absent or different RS was accepted'; exit 1 |
| | | fi |
| | | # Check the actual monitor-to-comparator wiring, including failed and stale reads. |
| | | BASE_DN=dc=example,dc=com |
| | | printf '1 d0\n' >"$OUT/server-ids.txt" |
| | | cat >"$OUT/reference.ldif" <<'LDIF' |
| | | dn: cn=changelog,cn=monitor |
| | | replicationServer-database: 1 |
| | | domain-name: dc=example,dc=com |
| | | last-change: 000001a1a1e836e400010000000a |
| | | LDIF |
| | | cp "$OUT/reference.ldif" "$OUT/current.ldif" |
| | | admin_search() { |
| | | [ "${SEARCH_FAILED:-}" != "$1" ] || return 1 |
| | | if [ "$1" = r0 ]; then cat "$OUT/reference.ldif"; else cat "$OUT/current.ldif"; fi |
| | | } |
| | | bootstrap_ended() { [ "${NOT_JOINED:-}" != "$1" ]; } |
| | | rs_caught_up r1 r0 || { echo '::error::matching checkpoint was rejected'; exit 1; } |
| | | sed 's/0000000a/00000009/' "$OUT/reference.ldif" >"$OUT/current.ldif" |
| | | if rs_caught_up r1 r0; then echo '::error::lagging RS was accepted'; exit 1; fi |
| | | cp "$OUT/reference.ldif" "$OUT/current.ldif" |
| | | if (SEARCH_FAILED=r0; rs_caught_up r1 r0) || (NOT_JOINED=r1; rs_caught_up r1 r0); then |
| | | echo '::error::failed checkpoint read or incomplete join was accepted'; exit 1 |
| | | fi |
| | | echo 'empty-rs lifecycle: passed' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d) |
| | | trap 'rm -rf "$OUT"' EXIT |
| | | if [ ! -f "$HERE/disturb-scale.sh" ]; then |
| | | echo 'scale disturbance is missing' >&2 |
| | | exit 1 |
| | | fi |
| | | |
| | | run_case() ( |
| | | local topology=$1 mode=$2 new_id=${3:-0} target n mappings |
| | | OUT="$OUT/$topology-$mode-$new_id" |
| | | mkdir -p "$OUT/logs" "$OUT/scale-checkpoint" |
| | | if [ "$topology" = combined ]; then |
| | | DS_NODES='d0 d1 d2 d3'; RS_ONLY=; RS_NODES=$DS_NODES; target=d3 |
| | | else |
| | | DS_NODES='d0 d1 d2 d3'; RS_ONLY='r0 r1 r2'; RS_NODES=$RS_ONLY; target=r2 |
| | | fi |
| | | 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)) |
| | | BASE_DN=dc=example,dc=com ROOT_PASSWORD=password |
| | | . "$HERE/disturb-scale.sh" |
| | | record() { printf '%s\n' "$*" >>"$OUT/calls"; } |
| | | docker() { |
| | | record "docker $*" |
| | | if [ "$1" = stop ] && [ "${*: -1}" = "${FAIL_STOP:-}" ]; then return 1; fi |
| | | case $1 in |
| | | cp) |
| | | if [ "$3" = - ]; then |
| | | [ "${FAIL_CHANGELOG_COPY:-0}" = 0 ] || return 1 |
| | | [ "$2" != "${FAIL_CHANGELOG_SOURCE:-none}:/opt/opendj/data/changelogDb" ] || return 1 |
| | | printf 'old changelog\n' |
| | | else |
| | | printf 'old log\n' >"$3" |
| | | fi |
| | | ;; |
| | | logs) echo 'old container log' ;; |
| | | inspect) |
| | | case ${*: -1} in |
| | | d0) echo 172.18.0.9 ;; |
| | | d1) echo 172.18.0.10 ;; |
| | | d2) echo 172.18.0.11 ;; |
| | | d3) echo 172.18.0.12 ;; |
| | | r0) echo 172.18.0.18 ;; |
| | | r1) echo 172.18.0.19 ;; |
| | | r2) echo 172.18.0.20 ;; |
| | | *) return 1 ;; |
| | | esac ;; |
| | | exec) |
| | | if [ "${3:-}" = sh ]; then |
| | | [ "${FAIL_OFFLINE_SNAPSHOT:-0}" = 0 ] || return 1 |
| | | printf 'domains.state\n1: dc=example,dc=com\n1.dom/1.server/offline.state 0000000000000001000100000001\n' |
| | | else cat >"$OUT/probe.ldif"; [ "${FAIL_PROBE:-0}" = 0 ]; fi ;; |
| | | esac |
| | | } |
| | | 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'; } |
| | | window_open() { record "window $*"; }; window_close() { :; } |
| | | window_open_key() { record "key-open $1"; shift; record "window $*"; } |
| | | window_close_key() { record "window-close $1"; } |
| | | dns_window_open() { record "dns-open $*"; }; dns_window_close() { record dns-close; } |
| | | errors_lines() { echo 10; } |
| | | scale_record_certificate_recoveries() { record "certificate-proof $*"; } |
| | | rolling_request_pause() { record "request-pause $1"; } |
| | | rolling_pause() { record "pause $1"; [ "$1" != "${FAIL_PAUSE:-}" ]; } |
| | | rolling_resume() { record "resume $1"; } |
| | | record_rejoined_id() { REJOINED_WITH_NEW_ID=$new_id; record "identity $1"; } |
| | | scale_backlog() { record "fill $REMOVED"; } |
| | | wait_until() { |
| | | 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 |
| | | [ "${FAIL_JOIN:-0}" != 1 ] || [ "${3:-}" != bootstrap_ended ] || return 1 |
| | | [ "${FAIL_RS:-0}" != 1 ] || [ "${3:-} ${4:-} ${5:-}" != 'scale_caught_up r1 r0' ] || return 1 |
| | | [ "${FAIL_PAIR_PROBE:-0}" != 1 ] || { [ "${3:-}" != scale_probe ] && [ "${3:-}" != scale_probe_batch ]; } || return 1 |
| | | [ "${FAIL_ACTIVE:-0}" != 1 ] || [ "${3:-}" != rolling_clients_running ] || return 1 |
| | | if [ "${3:-}" = record_rejoined_id ]; then record_rejoined_id "$4"; fi |
| | | if [ "${3:-} ${4:-} ${5:-} ${6:-}" = 'scale_probe d3 d3 rejoined' ]; then |
| | | FAIL_PROBE=${FAIL_REJOINED_WRITE:-0} scale_probe "$4" "$5" "$6" || return 1 |
| | | record 'rejoined write confirmed' |
| | | fi |
| | | return 0 |
| | | } |
| | | date() { echo 400; } |
| | | sleep() { record "sleep $*"; } |
| | | fail() { echo "$*" >&2; return 1; } |
| | | # 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 |
| | | fi |
| | | if grep '^docker stop' "$OUT/calls" >/dev/null; then |
| | | echo 'stopped a node without a checkpoint' >&2; exit 1 |
| | | fi |
| | | : >"$OUT/calls" |
| | | if [ "$topology" = rs534 ] && [ "$mode" = empty ]; then |
| | | if (FAIL_RETURN_HISTORY=1; disturb) >/dev/null 2>&1; then |
| | | echo 'incomplete returned RS history was accepted' >&2; exit 1 |
| | | fi |
| | | if grep -Fx 'key-open up-r0' "$OUT/calls" >/dev/null; then |
| | | echo 'writers exposed to the returned RS before its history caught up' >&2; exit 1 |
| | | fi |
| | | : >"$OUT/calls" |
| | | rm -f "$OUT/logs/$target.offline" "$OUT/logs/$target.previous" |
| | | fi |
| | | # A failed stop must abort the roll rather than recreate that still-running node. |
| | | if (FAIL_STOP=d0; disturb) >/dev/null 2>&1; then |
| | | echo 'failed node stop was accepted' >&2; exit 1 |
| | | fi |
| | | if grep '^start d0 ' "$OUT/calls" >/dev/null; then |
| | | echo 'recreated a node whose stop failed' >&2; exit 1 |
| | | fi |
| | | : >"$OUT/calls" |
| | | rm -f "$OUT/logs/$target.offline" "$OUT/logs/$target.previous" |
| | | if [ "$topology" = rs534 ] && [ "$mode" = empty ]; then |
| | | if (FAIL_CHANGELOG_COPY=1; disturb) >/dev/null 2>&1; then |
| | | echo 'failed original changelog snapshot was accepted' >&2; exit 1 |
| | | fi |
| | | if grep -Fx 'docker rm r2' "$OUT/calls" >/dev/null; then |
| | | echo 'removed RS container after its changelog snapshot failed' >&2; exit 1 |
| | | fi |
| | | : >"$OUT/calls" |
| | | rm -f "$OUT/logs/$target.offline" "$OUT/logs/$target.previous" |
| | | if (FAIL_CHANGELOG_SOURCE=r1; disturb) >/dev/null 2>&1; then |
| | | echo 'failed survivor changelog snapshot was accepted' >&2; exit 1 |
| | | fi |
| | | if grep -Fx 'docker rm r1' "$OUT/calls" >/dev/null; then |
| | | echo 'removed surviving RS container after its changelog snapshot failed' >&2; exit 1 |
| | | fi |
| | | : >"$OUT/calls" |
| | | rm -f "$OUT/logs/$target.offline" "$OUT/logs/$target.previous" |
| | | if (FAIL_OFFLINE_SNAPSHOT=1; disturb) >/dev/null 2>&1; then |
| | | echo 'failed offline-state snapshot was accepted' >&2; exit 1 |
| | | fi |
| | | if grep '^fill ' "$OUT/calls" >/dev/null; then |
| | | echo 'continued after a failed offline-state snapshot' >&2; exit 1 |
| | | fi |
| | | : >"$OUT/calls" |
| | | rm -f "$OUT/logs/$target.offline" "$OUT/logs/$target.previous" |
| | | fi |
| | | if [ "$topology" = rs534 ]; then |
| | | # Do not stop either DS of a pair without a responding replication server. |
| | | if (FAIL_RS=1; disturb) >/dev/null 2>&1; then echo 'unavailable RS accepted' >&2; exit 1; fi |
| | | if grep -E '^docker stop .* (d[01]|r0)$' "$OUT/calls" >/dev/null; then echo 'group stopped without an RS' >&2; exit 1; fi |
| | | : >"$OUT/calls" |
| | | rm -f "$OUT/logs/$target.offline" "$OUT/logs/$target.previous" |
| | | # A failed RS stop cannot be followed by any restart in the affected group. |
| | | if (FAIL_STOP=r0; disturb) >/dev/null 2>&1; then echo 'failed RS stop accepted' >&2; exit 1; fi |
| | | if grep -E '^start (d[01]|r0) ' "$OUT/calls" >/dev/null; then echo 'group restarted after failed RS stop' >&2; exit 1; fi |
| | | : >"$OUT/calls" |
| | | rm -f "$OUT/logs/$target.offline" "$OUT/logs/$target.previous" |
| | | # A failed surviving-DS write cannot be followed by a pair restart. |
| | | if (FAIL_PAIR_PROBE=1; disturb) >/dev/null 2>&1; then echo 'failed pair write accepted' >&2; exit 1; fi |
| | | if grep -E '^start d[01] ' "$OUT/calls" >/dev/null; then echo 'pair restarted after failed write' >&2; exit 1; fi |
| | | : >"$OUT/calls" |
| | | rm -f "$OUT/logs/$target.offline" "$OUT/logs/$target.previous" |
| | | fi |
| | | if [ "$topology" = combined ]; then |
| | | # Do not remove the node if the observer has no running load clients. |
| | | if (FAIL_ACTIVE=1; disturb) >/dev/null 2>&1; then echo 'inactive observer accepted' >&2; exit 1; fi |
| | | if grep '^docker stop' "$OUT/calls" >/dev/null; then echo 'stopped node without an active writer' >&2; exit 1; fi |
| | | grep -Fx 'resume d1' "$OUT/calls" >/dev/null || { echo 'first held writer not resumed on failure' >&2; exit 1; } |
| | | grep -Fx 'resume d2' "$OUT/calls" >/dev/null || { echo 'second held writer not resumed on failure' >&2; exit 1; } |
| | | : >"$OUT/calls" |
| | | # A failed drain also releases the surviving writers whose pauses were already requested. |
| | | if (FAIL_PAUSE="$target"; disturb) >/dev/null 2>&1; then |
| | | echo 'failed combined pause accepted' >&2; exit 1 |
| | | fi |
| | | if grep '^docker stop' "$OUT/calls" >/dev/null; then echo 'stopped a node after a failed pause' >&2; exit 1; fi |
| | | for n in d1 d2; do |
| | | grep -Fx "resume $n" "$OUT/calls" >/dev/null || { echo "$n not resumed after a failed pause" >&2; exit 1; } |
| | | done |
| | | : >"$OUT/calls" |
| | | fi |
| | | # A failed join must prevent membership assertions and backlog creation. |
| | | if (FAIL_JOIN=1; disturb) >/dev/null 2>&1; then |
| | | echo 'failed join was accepted' >&2; exit 1 |
| | | fi |
| | | if grep -E '^wait peer_removed |^fill ' "$OUT/calls" >/dev/null; then |
| | | echo 'proceeded after a failed join' >&2; exit 1 |
| | | fi |
| | | : >"$OUT/calls" |
| | | rm -f "$OUT/logs/$target.offline" "$OUT/logs/$target.previous" |
| | | if [ "$topology" = combined ] && { [ "$mode" = empty ] || [ "$new_id" = 1 ]; }; then |
| | | if (FAIL_REJOINED_WRITE=1; disturb) >/dev/null 2>&1; then |
| | | echo 'failed write from the rebuilt DS was accepted' >&2; exit 1 |
| | | fi |
| | | if sed -n '/^start d3 /,$p' "$OUT/calls" | grep -Fx 'request-pause d3' >/dev/null; then |
| | | echo 'rebuilt writer was held before its first write' >&2; exit 1 |
| | | fi |
| | | : >"$OUT/calls" |
| | | rm -f "$OUT/logs/$target.offline" "$OUT/logs/$target.previous" |
| | | fi |
| | | disturb |
| | | # A recreated container loses its log: retain both rolling generations as well as |
| | | # the final logs that a successful run will otherwise remove during cleanup. |
| | | for n in $SURVIVORS; do |
| | | [ -s "$OUT/bootstrap/down-$n.log" ] && [ -s "$OUT/bootstrap/up-$n.log" ] || { echo "missing saved bootstrap logs for $n" >&2; exit 1; } |
| | | done |
| | | [ -s "$OUT/bootstrap/removed-$target.log" ] || { echo 'missing removed node bootstrap log' >&2; exit 1; } |
| | | collect_scale_bootstrap |
| | | for n in $ALL_NODES; do [ -s "$OUT/bootstrap/final-$n.log" ] || { echo "missing final bootstrap log for $n" >&2; exit 1; }; done |
| | | for phase in down return up; do |
| | | for n in $RS_NODES; do |
| | | [ "$phase" != down ] || [ "$n" != "$target" ] || continue |
| | | [ -s "$OUT/scale-checkpoint/offline-$phase-$n.txt" ] || { echo "missing $phase offline state of $n" >&2; exit 1; } |
| | | grep -q '^capture-start-ms [0-9]' "$OUT/scale-checkpoint/offline-$phase-$n.txt" || { echo 'missing snapshot capture time' >&2; exit 1; } |
| | | done |
| | | done |
| | | if [ "$topology" = rs534 ] && [ "$mode" = empty ]; then |
| | | for phase in down return up; do |
| | | for n in r0 r1; do |
| | | [ -s "$OUT/scale-checkpoint/offline-$phase-$n.txt" ] || { echo "missing $phase offline state of $n" >&2; exit 1; } |
| | | done |
| | | done |
| | | # Exercise the real filter with the allowances passed by disturb() for the return. |
| | | ( |
| | | . "$HERE/assert-converged.sh" |
| | | local allowances warning recovery unexpected |
| | | allowances=$(sed -n 's/^window \(.* scale-cert-return\)$/\1/p' "$OUT/calls") |
| | | warning='[t] category=SYNC severity=WARNING msgID=312 msg=Replication server RS(31897) could not connect to replication server r2:8989 for domain "cn=admin data": SSLHandshakeException((bad_certificate) PKIX path validation failed)' |
| | | recovery='[t] category=SYNC severity=NOTICE msgID=313 msg=Replication server RS(31897) connected to replication server r2:8989 for domain "cn=admin data", which it had reported it had no replication session with' |
| | | since_mark() { printf '%s\n' "$warning" "$recovery"; } |
| | | for n in r0 r1; do |
| | | printf '0\n' >"$OUT/logs/$n.mark" |
| | | printf '0 2 %s\n' "$allowances" >"$OUT/logs/$n.windows" |
| | | unexpected=$(replication_errors "$n") |
| | | if [ -n "$unexpected" ] || ! grep -Fxq "$warning" "$OUT/logs/$n.expected"; then |
| | | echo "$n: recovered RS312 rejected by the scale return window" >&2 |
| | | exit 1 |
| | | fi |
| | | done |
| | | ) |
| | | [ -s "$OUT/scale-checkpoint/offline-return-r2.txt" ] || { echo 'missing return offline state of r2' >&2; exit 1; } |
| | | [ -s "$OUT/scale-checkpoint/removed-r2-changelog.tar" ] || { echo 'missing original removed RS changelog' >&2; exit 1; } |
| | | awk ' |
| | | $0 == "docker stop -t 120 r2" { stopped=NR } |
| | | $0 == "docker cp r2:/opt/opendj/data/changelogDb -" { saved=NR } |
| | | $0 == "docker rm r2" { removed=NR } |
| | | END { if (!stopped || !saved || !removed || !(stopped < saved && saved < removed)) exit 1 } |
| | | ' "$OUT/calls" || { echo 'removed RS changelog was not saved before container removal' >&2; exit 1; } |
| | | for n in r0 r1; do |
| | | [ -s "$OUT/scale-checkpoint/down-$n-changelog.tar" ] || { echo "missing $n changelog before restart" >&2; exit 1; } |
| | | awk -v n="$n" ' |
| | | $0 == "docker stop -t 120 " n && !stopped { stopped=NR } |
| | | $0 == "docker cp " n ":/opt/opendj/data/changelogDb -" && !saved { saved=NR } |
| | | $0 == "docker rm " n && !removed { removed=NR } |
| | | END { if (!stopped || !saved || !removed || !(stopped < saved && saved < removed)) exit 1 } |
| | | ' "$OUT/calls" || { echo "$n changelog was not saved before restart" >&2; exit 1; } |
| | | done |
| | | fi |
| | | # Every restarted directory server completes its join before measured load resumes. |
| | | awk ' |
| | | $1 == "start" { started[$2]=1; joined[$2]=0 } |
| | | $1 == "wait" && $2 == "bootstrap_ended" { joined[$3]=1 } |
| | | $1 == "resume" && started[$2] && !joined[$2] { exit 1 } |
| | | END { for (node in started) if (!joined[node]) exit 1 } |
| | | ' "$OUT/calls" || { echo 'restarted writer resumed before bootstrap completed' >&2; exit 1; } |
| | | if [ "$topology" = combined ]; then |
| | | # Each checkpoint drains all present writers except its observer. Request their |
| | | # pauses before waiting on any one of them so the segment ends can overlap. |
| | | awk -v nodes="$DS_NODES" -v target="$target" ' |
| | | BEGIN { count=split(nodes, writers, " ") } |
| | | $1 == "start" && $2 == target { returned=1 } |
| | | $1 == "request-pause" { if (waiting) exit 1; requested[$2]=1 } |
| | | $1 == "pause" { if (!requested[$2]) exit 1; waiting=1; drained[$2]=1 } |
| | | $1 == "wait" && $2 == "rolling_clients_running" { |
| | | for (i=1; i<=count; i++) { |
| | | node=writers[i] |
| | | needed=node != $3 && (node != target || !removed || returned) |
| | | if (needed != (node in drained) || needed != (node in requested)) exit 1 |
| | | } |
| | | observed=1 |
| | | } |
| | | $1 == "wait" && $2 == "scale_caught_up" { |
| | | if (!observed) exit 1 |
| | | checked=1 |
| | | } |
| | | $1 == "docker" && $2 == "stop" { |
| | | if (!checked || !drained[$NF]) exit 1 |
| | | if ($NF == target) removed=1 |
| | | for (node in requested) delete requested[node] |
| | | for (node in drained) delete drained[node] |
| | | waiting=observed=checked=0 |
| | | } |
| | | ' "$OUT/calls" || { echo 'combined pauses were not requested together before draining checkpoint writers' >&2; exit 1; } |
| | | # A combined node must serve again before another is stopped. |
| | | awk -v target="$target" ' |
| | | $1 == "docker" && $2 == "stop" && $NF != target { if (down) exit 1; down=$NF } |
| | | $1 == "wait" && $2 == "started_since" && $3 == down { down="" } |
| | | END { if (down) exit 1 } |
| | | ' "$OUT/calls" || { echo 'more than one combined survivor stopped at a time' >&2; exit 1; } |
| | | else |
| | | # Finish a whole group before resuming either writer or starting the next group. |
| | | awk ' |
| | | $1 == "start" && $2 == "r0" { joined=0 } |
| | | $1 == "wait" && $2 == "bootstrap_ended" && $3 ~ /^(d0|d1|r0)$/ { joined++ } |
| | | $1 == "resume" && $2 ~ /^d[01]$/ && joined != 3 { exit 1 } |
| | | $1 == "docker" && $2 == "stop" && $NF ~ /^(d2|d3|r1)$/ && joined != 3 { exit 1 } |
| | | ' "$OUT/calls" || { echo 'next rolling group or load resumed before the first group joined' >&2; exit 1; } |
| | | # The first pair and one RS overlap; the other RS must remain up until the first serves. |
| | | awk ' |
| | | $1 == "docker" && $2 == "stop" && $NF == "d0" && !first {first=NR} |
| | | $1 == "docker" && $2 == "stop" && $NF == "d1" && !second {second=NR} |
| | | $1 == "docker" && $2 == "stop" && $NF == "r0" && !rs {rs=NR; rsdown=1} |
| | | $1 == "wait" && $2 == "started_since" && $3 == "r0" {rsdown=0} |
| | | $1 == "docker" && $2 == "stop" && $NF == "r1" && rsdown {exit 1} |
| | | $1 == "start" && $2 == "d0" && first && !started {started=NR} |
| | | END {if (!first || !second || !rs || !started || !(first < started && second < started && rs < started)) exit 1} |
| | | ' "$OUT/calls" || { echo 'DS and RS transitions did not overlap safely' >&2; exit 1; } |
| | | grep -Fx 'request-pause d0' "$OUT/calls" >/dev/null || { echo 'first pair pause not requested' >&2; exit 1; } |
| | | grep -Fx 'request-pause d1' "$OUT/calls" >/dev/null || { echo 'second pair pause not requested' >&2; exit 1; } |
| | | awk ' |
| | | $0 == "request-pause d0" && !a {a=NR} |
| | | $0 == "request-pause d1" && !b {b=NR} |
| | | $0 == "pause d0" && !c {c=NR} |
| | | END {if (!a || !b || !c || !(a < c && b < c)) exit 1} |
| | | ' "$OUT/calls" || { echo 'pair pauses were not requested together' >&2; exit 1; } |
| | | grep -Fx 'wait scale_probe_batch d2 down d0 d1 r0' "$OUT/calls" >/dev/null || { echo 'group write used no surviving DS' >&2; exit 1; } |
| | | awk ' |
| | | $0 == "key-open down-r0" && !opened {opened=NR} |
| | | $0 == "wait scale_caught_up r1 r0" && !checked {checked=NR} |
| | | $0 == "docker stop -t 120 d0" && !stopped {stopped=NR} |
| | | END {if (!opened || !checked || !stopped || !(opened < checked && checked < stopped)) exit 1} |
| | | ' "$OUT/calls" || { echo 'RS checkpoint was not taken after preparing log windows' >&2; exit 1; } |
| | | awk ' |
| | | $0 == "key-open down-d0" && !a {a=NR} |
| | | $0 == "key-open down-d1" && !b {b=NR} |
| | | $1 == "docker" && $2 == "stop" && $NF == "d0" && !c {c=NR} |
| | | $1 == "docker" && $2 == "stop" && $NF == "d1" && !d {d=NR} |
| | | $0 == "wait scale_probe_batch d2 down d0 d1 r0" && !p {p=NR} |
| | | END {if (!a || !b || !c || !d || !p || !(a < c && b < c && c < p && d < p)) exit 1} |
| | | ' "$OUT/calls" || { echo 'pair windows or write probe occurred in the wrong order' >&2; exit 1; } |
| | | fi |
| | | expected_windows=4 |
| | | [ "$(grep -c '^sleep 10$' "$OUT/calls")" -eq "$expected_windows" ] || { echo 'missing handshake grace after a transition' >&2; exit 1; } |
| | | expected_checkpoints=$((1 + 2 * ($(echo "$RS_NODES" | wc -w) - 1))) |
| | | if [ "$topology" = rs534 ] && [ "$mode" = empty ]; then |
| | | expected_checkpoints=$((expected_checkpoints + 1)) |
| | | grep -Fx 'start-options r2 -e REPLICATION_RECOVER_FROM_RS=1' "$OUT/calls" >/dev/null || { echo 'empty RS returned without recovery-only bootstrap' >&2; exit 1; } |
| | | awk ' |
| | | $0 == "wait bootstrap_ended r2" { joined=NR } |
| | | $0 == "wait scale_caught_up r2 r0" { copied=NR } |
| | | $0 == "key-open up-r0" { exposed=NR } |
| | | END { if (!joined || !copied || !exposed || !(joined < copied && copied < exposed)) exit 1 } |
| | | ' "$OUT/calls" || { echo 'returned RS was exposed before retained history catch-up' >&2; exit 1; } |
| | | fi |
| | | if [ "$topology" != rs534 ] || [ "$mode" != empty ]; then |
| | | if grep -q 'REPLICATION_RECOVER_FROM_RS' "$OUT/calls"; then echo 'recovery-only bootstrap changed another scale variant' >&2; exit 1; fi |
| | | fi |
| | | [ "$(grep -c '^wait scale_caught_up ' "$OUT/calls")" -eq "$expected_checkpoints" ] || { echo 'a rolling RS lacked a checkpoint' >&2; exit 1; } |
| | | grep -F 'wait scale_probe' "$OUT/calls" >/dev/null || { echo 'no confirmed write required while nodes are stopped' >&2; exit 1; } |
| | | grep -Fx "dns-open $target" "$OUT/calls" >/dev/null || { echo 'absence DNS window not opened' >&2; exit 1; } |
| | | grep -Fx 'dns-close' "$OUT/calls" >/dev/null || { echo 'absence DNS window not closed' >&2; exit 1; } |
| | | grep -Fx "fill $target" "$OUT/calls" >/dev/null || { echo "backlog was not generated" >&2; exit 1; } |
| | | awk -v target="$target" -v survivor="${RS_NODES%% *}" ' |
| | | $1 == "docker" && $2 == "stop" && $NF == target { stopped = 1 } |
| | | $1 == "search" && $2 == survivor { if (!stopped) exit 1; baseline = 1 } |
| | | END { if (!baseline) exit 1 }' "$OUT/calls" || { echo 'backlog baseline was not captured after stop' >&2; exit 1; } |
| | | [ -s "$OUT/scale-checkpoint/absent-start.ldif" ] || { echo 'backlog baseline missing' >&2; exit 1; } |
| | | awk -v target="$target" -v full="$FULL_PEERS" ' |
| | | $1 == "start" && $2 == target { returned = 1 } |
| | | $1 == "start" && $2 != target && $4 == full && !returned { exit 1 } |
| | | END { if (!returned) exit 1 }' "$OUT/calls" || { echo 'survivor rolled before the node returned' >&2; exit 1; } |
| | | [ "$(grep -c '^wait peer_removed ' "$OUT/calls")" -eq "$(($(echo "$ALL_NODES" | wc -w) - 1))" ] |
| | | [ "$(grep -c '^wait peer_present ' "$OUT/calls")" -eq "$(($(echo "$ALL_NODES" | wc -w) - 1))" ] || { echo 'return not checked on every survivor' >&2; exit 1; } |
| | | for n in $ALL_NODES; do |
| | | [ "$n" = "$target" ] && continue |
| | | grep -Fx "window-close down-$n" "$OUT/calls" >/dev/null || { echo "down window for $n left open" >&2; exit 1; } |
| | | grep -Fx "window-close up-$n" "$OUT/calls" >/dev/null || { echo "up window for $n left open" >&2; exit 1; } |
| | | [ "$(grep -c "^start $n " "$OUT/calls")" -eq 2 ] || { echo "$n was not rolled twice" >&2; exit 1; } |
| | | done |
| | | if [ "$mode" = empty ]; then |
| | | grep -Fx "docker volume rm vol-$target" "$OUT/calls" >/dev/null |
| | | [ -s "$OUT/logs/$target.previous" ] |
| | | grep -F "cert:d0:$target" "$OUT/calls" >/dev/null || { echo 'missing exact certificate window' >&2; exit 1; } |
| | | grep -E '^window .* scale-cert-return$' "$OUT/calls" >/dev/null || { echo 'missing scale certificate window' >&2; exit 1; } |
| | | mappings='172.18.0.12 d0=172.18.0.9 d1=172.18.0.10 d2=172.18.0.11' |
| | | if [ "$topology" = rs534 ]; then |
| | | mappings="172.18.0.20 ${mappings#* } d3=172.18.0.12 r0=172.18.0.18 r1=172.18.0.19" |
| | | fi |
| | | grep -Fx "certificate-proof $mappings" "$OUT/calls" >/dev/null || { echo 'wrong certificate proof addresses' >&2; exit 1; } |
| | | awk ' |
| | | /^wait peer_present / { checked=NR } |
| | | /^certificate-proof / { proof=NR } |
| | | END { if (!checked || !proof || checked >= proof) exit 1 } |
| | | ' "$OUT/calls" || { echo 'certificate recovery checked before scale-out membership settled' >&2; exit 1; } |
| | | else |
| | | if grep -E 'docker volume rm|scale-cert-return|certificate-proof' "$OUT/calls" >/dev/null; then |
| | | echo 'kept volume was treated as a rebuild' >&2; exit 1 |
| | | fi |
| | | fi |
| | | if [ "$topology" = combined ]; then |
| | | grep -Fx "identity $target" "$OUT/calls" >/dev/null |
| | | grep -Fx "window dns:$target dns:d0" "$OUT/calls" >/dev/null || { echo 'rolling combined node lacks its DNS allowance' >&2; exit 1; } |
| | | grep -Fx "pause $target" "$OUT/calls" >/dev/null |
| | | grep -Fx "resume $target" "$OUT/calls" >/dev/null |
| | | grep -Fx 'wait rolling_clients_running d0' "$OUT/calls" >/dev/null || { echo 'checkpoint writer was not checked' >&2; exit 1; } |
| | | grep -Fx 'wait scale_probe d0 d3 checkpoint-down' "$OUT/calls" >/dev/null || { echo 'checkpoint write was not confirmed' >&2; exit 1; } |
| | | awk ' |
| | | $0 == "request-pause d1" && !a {a=NR} |
| | | $0 == "request-pause d2" && !b {b=NR} |
| | | $0 == "docker stop -t 120 d3" && !c {c=NR} |
| | | $0 == "resume d1" && !d {d=NR} |
| | | $0 == "resume d2" && !e {e=NR} |
| | | END {if (!a || !b || !c || !d || !e || !(a < c && b < c && c < d && c < e)) exit 1} |
| | | ' "$OUT/calls" || { echo 'other writers were not held until the node stopped' >&2; exit 1; } |
| | | awk ' |
| | | $1 == "start" && $2 == "d3" && !returned {returned=NR} |
| | | returned && $0 == "request-pause d3" && !held {held=NR} |
| | | held && $0 == "docker stop -t 120 d0" && !stopped {stopped=NR} |
| | | stopped && $0 == "resume d3" && !released {released=NR} |
| | | END {if (!returned || !held || !stopped || !released || !(returned < held && held < stopped && stopped < released)) exit 1} |
| | | ' "$OUT/calls" || { echo 'returned writer was not held during scale-out checkpoint' >&2; exit 1; } |
| | | if [ "$mode" = empty ] || [ "$new_id" = 1 ]; then |
| | | awk ' |
| | | /^start d3 / { returned=1 } |
| | | /^identity d3$/ { identity=NR } |
| | | identity && /^resume d3$/ && !resumed { resumed=NR } |
| | | /^rejoined write confirmed$/ { written=NR } |
| | | returned && /^request-pause d3$/ && !held { held=NR } |
| | | END { if (!(identity && identity < resumed && resumed < written && written < held)) exit 1 } |
| | | ' "$OUT/calls" || { echo 'rebuilt DS did not write after recording its ID and before being held' >&2; exit 1; } |
| | | grep -Fx 'dn: uid=scale-rejoined-d3,ou=People,dc=example,dc=com' "$OUT/probe.ldif" >/dev/null |
| | | elif grep -Fxq 'rejoined write confirmed' "$OUT/calls"; then |
| | | echo 'kept replica with the same ID ran a rejoin write probe' >&2; exit 1 |
| | | fi |
| | | fi |
| | | [ ! -e "$OUT/logs/$target.offline" ] |
| | | # A failed observer query identifies the node and status in the checkpoint diagnostic. |
| | | ( |
| | | 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 |
| | | grep -F 'observer' "$OUT/scale-checkpoint/check.txt" >/dev/null || { echo 'checkpoint diagnostic omitted observer' >&2; exit 1; } |
| | | grep -F '124' "$OUT/scale-checkpoint/check.txt" >/dev/null || { echo 'checkpoint diagnostic omitted failure status' >&2; exit 1; } |
| | | ) |
| | | backlog_ldif "scale-backlog-$target" "$BASE_DN" 1 3 >"$OUT/fill.ldif" |
| | | [ "$(grep -c '^changetype: modify$' "$OUT/fill.ldif")" -eq 3 ] || { echo 'wrong number of fill writes' >&2; exit 1; } |
| | | grep -Fx 'description: scale-3' "$OUT/fill.ldif" >/dev/null || { echo 'fill values are not distinct' >&2; exit 1; } |
| | | scale_probe d0 d1 down || { echo 'confirmed probe was rejected' >&2; exit 1; } |
| | | grep -Fx 'dn: uid=scale-down-d1,ou=People,dc=example,dc=com' "$OUT/probe.ldif" >/dev/null |
| | | if (FAIL_PROBE=1; scale_probe d0 d1 up); then echo 'failed LDAP write accepted' >&2; exit 1; fi |
| | | if [ "$topology" = rs534 ]; then |
| | | scale_probe_batch d2 down d0 d1 r0 || { echo 'confirmed batch probe was rejected' >&2; exit 1; } |
| | | [ "$(grep -c '^dn: uid=scale-down-' "$OUT/probe.ldif")" -eq 3 ] || { echo 'batch lacks a write per stopped node' >&2; exit 1; } |
| | | grep -Fx 'dn: uid=scale-down-r0,ou=People,dc=example,dc=com' "$OUT/probe.ldif" >/dev/null || { echo 'batch lacks the RS write' >&2; exit 1; } |
| | | if (FAIL_PROBE=1; scale_probe_batch d2 up d0 d1 r0); then echo 'failed batch accepted' >&2; exit 1; fi |
| | | fi |
| | | ) |
| | | for topology in rs534 combined; do |
| | | for mode in kept empty; do run_case "$topology" "$mode"; done |
| | | done |
| | | run_case combined kept 1 |
| | | # The fast monitor connects only to a numeric port published on IPv4 loopback. |
| | | ( |
| | | OUT="$OUT/loopback"; mkdir -p "$OUT/scale-checkpoint" |
| | | TOPOLOGY=combined SCALE_VOLUME=kept DS_NODES='d0 d1 d2' RS_NODES=$DS_NODES RS_ONLY= |
| | | ALL_NODES=$DS_NODES PEERS=d0,d1,d2 ROOT_PASSWORD=secret ROLLING_END_MS=2000000000000 |
| | | . "$HERE/disturb-scale.sh" |
| | | docker() { [ "$1" = port ] || return 1; printf '%s\n' "$MAPPING"; } |
| | | python3() { printf '%s\n' "$*" >"$OUT/arguments"; cat >/dev/null; printf 'snapshot\n'; } |
| | | MAPPING='127.0.0.1:12345' |
| | | [ "$(scale_monitor_search d0)" = snapshot ] || { echo 'loopback monitor rejected' >&2; exit 1; } |
| | | grep -F '12345 2000000000000' "$OUT/arguments" >/dev/null || { echo 'port or deadline not passed' >&2; exit 1; } |
| | | if grep -F 'secret' "$OUT/arguments" >/dev/null; then echo 'password appeared in process arguments' >&2; exit 1; fi |
| | | for MAPPING in '0.0.0.0:12345' '127.0.0.1:not-a-port' '127.0.0.1:12345 extra'; do |
| | | if scale_monitor_search d0 >/dev/null 2>&1; then echo "unsafe port mapping accepted: $MAPPING" >&2; exit 1; fi |
| | | done |
| | | ) |
| | | # Repeated comparisons must use one immutable reference, and retain every result. |
| | | ( |
| | | OUT="$OUT/checkpoint-history"; mkdir -p "$OUT/scale-checkpoint" |
| | | TOPOLOGY=combined SCALE_VOLUME=kept DS_NODES='d0 d1 d2' RS_NODES=$DS_NODES RS_ONLY= |
| | | ALL_NODES=$DS_NODES PEERS=d0,d1,d2 BASE_DN=dc=example,dc=com |
| | | DISTURB_TIMEOUT=900 ROLLING_END=$((SECONDS + 900)) |
| | | . "$HERE/disturb-scale.sh" |
| | | echo '1 d0' >"$OUT/server-ids.txt" |
| | | scale_monitor_search() { |
| | | echo "$1" >>"$OUT/queries" |
| | | local csn=000001a1a1e836e400010000000a |
| | | if [ "$1" = observer ] && [ ! -f "$OUT/first-observer" ]; then |
| | | csn=000001a1a1e836e4000100000009; touch "$OUT/first-observer" |
| | | fi |
| | | printf 'dn: cn=one,cn=monitor\ndomain-name: %s\nreplicationServer-database: 1\nlast-change: %s\n\n' "$BASE_DN" "$csn" |
| | | } |
| | | scale_checkpoint_init observer departing |
| | | if scale_caught_up observer departing; then echo 'older position accepted' >&2; exit 1; fi |
| | | scale_caught_up observer departing || { echo 'caught-up position rejected' >&2; exit 1; } |
| | | [ "$(grep -c '^departing$' "$OUT/queries")" -eq 2 ] || { echo 'reference was resampled before catch-up or not refreshed after it' >&2; exit 1; } |
| | | [ "$(grep -c '^observer$' "$OUT/queries")" -eq 3 ] || { echo 'missing observer retry or fresh confirmation' >&2; exit 1; } |
| | | grep -F 'needs' "$SCALE_CHECKPOINT_DIR/attempt-0001.compare" >/dev/null || { echo 'first comparison was not retained' >&2; exit 1; } |
| | | [ -f "$SCALE_CHECKPOINT_DIR/attempt-0002.compare" ] || { echo 'second comparison was not retained' >&2; exit 1; } |
| | | [ "$(grep -c 'observer' "$SCALE_CHECKPOINT_DIR/history.txt")" -ge 2 ] || { echo 'query history missing' >&2; exit 1; } |
| | | scale_monitor_search() { echo 'timeout=query' >&2; return 124; } |
| | | if scale_caught_up observer departing; then echo 'timed-out query accepted' >&2; exit 1; fi |
| | | grep -F 'timeout=query' "$SCALE_CHECKPOINT_DIR/history.txt" >/dev/null || { echo 'query timeout not distinguished' >&2; exit 1; } |
| | | scale_monitor_search() { echo 'timeout=load' >&2; return 124; } |
| | | if scale_caught_up observer departing; then echo 'reported load deadline accepted' >&2; exit 1; fi |
| | | grep -F 'timeout=load' "$SCALE_CHECKPOINT_DIR/history.txt" >/dev/null || { echo 'reported load deadline not distinguished' >&2; exit 1; } |
| | | scale_monitor_search() { return 124; } |
| | | ROLLING_END=$SECONDS |
| | | if scale_caught_up observer departing; then echo 'load deadline accepted' >&2; exit 1; fi |
| | | grep -F 'timeout=load' "$SCALE_CHECKPOINT_DIR/history.txt" >/dev/null || { echo 'load deadline not distinguished' >&2; exit 1; } |
| | | ) |
| | | # A new origin can be absent on both RSs when a checkpoint first samples them. |
| | | ( |
| | | OUT="$OUT/checkpoint-new-origin"; mkdir -p "$OUT/scale-checkpoint" |
| | | TOPOLOGY=combined SCALE_VOLUME=empty DS_NODES='d0 d1 d2' RS_NODES=$DS_NODES RS_ONLY= |
| | | ALL_NODES=$DS_NODES PEERS=d0,d1,d2 BASE_DN=dc=example,dc=com |
| | | DISTURB_TIMEOUT=900 ROLLING_END=$((SECONDS + 900)) |
| | | . "$HERE/disturb-scale.sh" |
| | | printf '1 d0\n9 d2\n' >"$OUT/server-ids.txt" |
| | | scale_monitor_search() { |
| | | printf 'dn: cn=one,cn=monitor\ndomain-name: %s\nreplicationServer-database: 1\nlast-change: 000001a1a1e836e400010000000a\n\n' "$BASE_DN" |
| | | if [ -f "$OUT/$1-new-origin" ]; then |
| | | printf 'dn: cn=nine,cn=monitor\ndomain-name: %s\nreplicationServer-database: 9\nlast-change: 000001a1a1e836e4000900000001\n\n' "$BASE_DN" |
| | | fi |
| | | } |
| | | scale_checkpoint_init observer departing |
| | | if scale_caught_up observer departing; then echo 'missing new origin was accepted' >&2; exit 1; fi |
| | | touch "$OUT/departing-new-origin" |
| | | if scale_caught_up observer departing; then echo 'observer without new origin was accepted' >&2; exit 1; fi |
| | | grep -F 'DS(9): needs' "$SCALE_CHECKPOINT_DIR/attempt-0002.compare" >/dev/null || { echo 'departing node was not resampled for the new origin' >&2; exit 1; } |
| | | touch "$OUT/observer-new-origin" |
| | | scale_caught_up observer departing || { echo 'checkpoint did not recover when both new positions appeared' >&2; exit 1; } |
| | | ) |
| | | # A caught-up old checkpoint cannot authorize stopping a server whose current position advanced. |
| | | ( |
| | | OUT="$OUT/checkpoint-freshness"; mkdir -p "$OUT/scale-checkpoint" |
| | | TOPOLOGY=combined SCALE_VOLUME=kept DS_NODES='d0 d1 d2' RS_NODES=$DS_NODES RS_ONLY= |
| | | ALL_NODES=$DS_NODES PEERS=d0,d1,d2 BASE_DN=dc=example,dc=com |
| | | DISTURB_TIMEOUT=900 ROLLING_END=$((SECONDS + 900)) |
| | | . "$HERE/disturb-scale.sh" |
| | | echo '1 d0' >"$OUT/server-ids.txt" |
| | | scale_monitor_search() { |
| | | local csn=000001a1a1e836e400010000000a |
| | | if [ "$1" = departing ]; then |
| | | if [ -f "$OUT/reference-read" ]; then csn=000001a1a1e836e400010000000b; else touch "$OUT/reference-read"; fi |
| | | elif [ ! -f "$OUT/observer-read" ]; then csn=000001a1a1e836e4000100000009; touch "$OUT/observer-read" |
| | | elif [ -f "$OUT/observer-caught-up" ]; then csn=000001a1a1e836e400010000000b |
| | | fi |
| | | printf 'dn: cn=one,cn=monitor\ndomain-name: %s\nreplicationServer-database: 1\nlast-change: %s\n\n' "$BASE_DN" "$csn" |
| | | } |
| | | scale_checkpoint_init observer departing |
| | | if scale_caught_up observer departing; then echo 'lagging observer accepted' >&2; exit 1; fi |
| | | if scale_caught_up observer departing; then echo 'stale checkpoint accepted' >&2; exit 1; fi |
| | | touch "$OUT/observer-caught-up" |
| | | scale_caught_up observer departing || { echo 'fresh checkpoint rejected' >&2; exit 1; } |
| | | # If the first two searches already match, the reference is fresh and must not be queried twice. |
| | | scale_monitor_search() { |
| | | echo "$1" >>"$OUT/fast-queries" |
| | | printf 'dn: cn=one,cn=monitor\ndomain-name: %s\nreplicationServer-database: 1\nlast-change: 000001a1a1e836e400010000000b\n\n' "$BASE_DN" |
| | | } |
| | | scale_checkpoint_init observer departing |
| | | scale_caught_up observer departing || { echo 'fresh fast checkpoint rejected' >&2; exit 1; } |
| | | [ "$(wc -l <"$OUT/fast-queries")" -eq 2 ] || { echo 'fresh checkpoint made redundant searches' >&2; exit 1; } |
| | | ) |
| | | # All group stops start before any returns, and any failed stop fails the group. |
| | | ( |
| | | OUT="$OUT/parallel-stops"; mkdir -p "$OUT" |
| | | TOPOLOGY=rs534 SCALE_VOLUME=kept DS_NODES='d0 d1 d2' RS_ONLY='r0 r1 r2' RS_NODES=$RS_ONLY |
| | | ALL_NODES="$DS_NODES $RS_ONLY" PEERS=d0,d1,d2,r0,r1,r2 |
| | | . "$HERE/disturb-scale.sh" |
| | | docker() { |
| | | printf '%s\n' "$4" >>"$OUT/started" |
| | | local end=$((SECONDS + 5)) |
| | | while [ "$(wc -l <"$OUT/started")" -lt 3 ]; do [ "$SECONDS" -lt "$end" ] || return 1; sleep 0.05; done |
| | | [ "$4" != "${FAIL_NODE:-}" ] |
| | | } |
| | | scale_stop_group d0 d1 r0 || { echo 'group stops were not concurrent' >&2; exit 1; } |
| | | : >"$OUT/started" |
| | | if (FAIL_NODE=d1; scale_stop_group d0 d1 r0); then echo 'failed group stop was accepted' >&2; exit 1; fi |
| | | [ "$(wc -l <"$OUT/started")" -eq 3 ] || { echo 'failed stop abandoned another operation' >&2; exit 1; } |
| | | ) |
| | | # Exercise the real fill pipeline: all 50,001 records reach one client, and a failed |
| | | # client must not produce a successful backlog report. |
| | | ( |
| | | OUT="$OUT/fill-test"; mkdir -p "$OUT/scale-progress" "$OUT/scale-checkpoint" "$OUT/load" |
| | | TOPOLOGY=combined SCALE_VOLUME=kept DS_NODES='d0 d1 d2 d3' RS_NODES=$DS_NODES RS_ONLY= |
| | | ALL_NODES=$DS_NODES PEERS=d0,d1,d2,d3 NETWORK=fixture IMAGE=fixture |
| | | BASE_DN=dc=example,dc=com ROOT_PASSWORD=password CLIENT_JAVA_ARGS=-Xmx128m |
| | | DISTURB_TIMEOUT=900 ROLLING_END=$((SECONDS + 900)) ROLLING_END_MS=2000000000000 |
| | | . "$HERE/disturb-scale.sh" |
| | | scale_wait() { shift; "$@"; } |
| | | scale_wait_fence() { shift; "$@"; } |
| | | admin_search() { echo writer; } |
| | | ldaps_search() { printf '%s\n' "$2" >"$OUT/writer-dn"; echo writer; } |
| | | scale_fence() { [ "${FAIL_FENCE:-0}" = 0 ]; } |
| | | scale_coverage() { [ "${FAIL_COVERAGE:-0}" = 0 ]; } |
| | | rolling_kill_active() { :; } |
| | | docker() { |
| | | case $1 in |
| | | exec) cat >/dev/null ;; |
| | | run) cat >"$OUT/fill.ldif"; [ "${FAIL_FILL:-0}" = 0 ] ;; |
| | | *) return 1 ;; |
| | | esac |
| | | } |
| | | scale_backlog |
| | | grep -Fx 'uid=scale-backlog-d3,ou=People,dc=example,dc=com' "$OUT/writer-dn" >/dev/null || { echo 'final fill entry was not read' >&2; exit 1; } |
| | | [ "$(grep -c '^changetype: modify$' "$OUT/fill.ldif")" -eq 50000 ] |
| | | grep -Fx 'description: scale-50001' "$OUT/fill.ldif" >/dev/null |
| | | grep -Fx '50001 changes while the server was absent' "$OUT/scale-checkpoint/backlog.txt" >/dev/null |
| | | rm "$OUT/scale-checkpoint/backlog.txt" |
| | | if (FAIL_FILL=1; scale_backlog); then echo 'failed fill was accepted' >&2; exit 1; fi |
| | | [ ! -e "$OUT/scale-checkpoint/backlog.txt" ] || { echo 'failed fill wrote a success report' >&2; exit 1; } |
| | | if (FAIL_FENCE=1; scale_backlog); then echo 'lagging RS fence was accepted' >&2; exit 1; fi |
| | | [ ! -e "$OUT/scale-checkpoint/backlog.txt" ] || { echo 'lagging RS wrote a success report' >&2; exit 1; } |
| | | if (FAIL_COVERAGE=1; scale_backlog); then echo 'incomplete RS changelog was accepted' >&2; exit 1; fi |
| | | [ ! -e "$OUT/scale-checkpoint/backlog.txt" ] || { echo 'missing changes wrote a success report' >&2; exit 1; } |
| | | ) |
| | | # The fence receives the remaining load time; other waits retain their individual cap. |
| | | ( |
| | | OUT="$OUT/fence-wait"; mkdir -p "$OUT" |
| | | TOPOLOGY=combined SCALE_VOLUME=kept DS_NODES='d0 d1 d2' RS_NODES=$DS_NODES RS_ONLY= |
| | | ALL_NODES=$DS_NODES PEERS=d0,d1,d2 DISTURB_TIMEOUT=900 ROLLING_END=$((SECONDS + 1800)) |
| | | . "$HERE/disturb-scale.sh" |
| | | wait_until() { printf '%s\n' "$1" >"$OUT/timeout"; } |
| | | scale_wait_fence 'fence' true |
| | | [ "$(cat "$OUT/timeout")" -gt 900 ] || { echo 'fence still capped at 900 seconds' >&2; exit 1; } |
| | | scale_wait 'other wait' true |
| | | [ "$(cat "$OUT/timeout")" -eq 900 ] || { echo 'unrelated wait cap changed' >&2; exit 1; } |
| | | fail() { return 1; } |
| | | ROLLING_END=$SECONDS |
| | | if scale_wait_fence 'expired fence' true; then echo 'expired fence was accepted' >&2; exit 1; fi |
| | | ) |
| | | # Each fence attempt retains its query and comparison, including failures and both CSNs. |
| | | ( |
| | | OUT="$OUT/fence-history"; mkdir -p "$OUT/scale-checkpoint" |
| | | TOPOLOGY=combined SCALE_VOLUME=kept DS_NODES='d0 d1 d2' RS_NODES=$DS_NODES RS_ONLY= |
| | | ALL_NODES=$DS_NODES PEERS=d0,d1,d2 BASE_DN=dc=example,dc=com ROLLING_END=$((SECONDS + 1800)) |
| | | . "$HERE/disturb-scale.sh" |
| | | cat >"$OUT/scale-checkpoint/writer.ldif" <<'LDIF' |
| | | dn: cn=writer |
| | | description: scale-50001 |
| | | ds-sync-hist: description:000000000000000100010000000a:repl:scale-50001 |
| | | LDIF |
| | | scale_monitor_search() { |
| | | if [ "${QUERY_FAIL:-0}" = 1 ]; then echo 'timeout=query' >&2; return 124; fi |
| | | printf 'dn: cn=changelog\ndomain-name: dc=example,dc=com\nreplicationServer-database: 1\nlast-change: %s\n' "$CURRENT" |
| | | } |
| | | CURRENT=0000000000000001000100000009 |
| | | if scale_fence d1; then echo 'lagging fence passed' >&2; exit 1; fi |
| | | CURRENT=000000000000000100010000000a |
| | | scale_fence d1 || { echo 'caught-up fence failed' >&2; exit 1; } |
| | | if (QUERY_FAIL=1; scale_fence d1); then echo 'failed query passed' >&2; exit 1; fi |
| | | history="$OUT/scale-checkpoint/fence-d1/history.txt" |
| | | grep -F '0000000000000001000100000009' "$history" >/dev/null || { echo 'lagging CSN missing from history' >&2; exit 1; } |
| | | grep -F '000000000000000100010000000a' "$history" >/dev/null || { echo 'target CSN missing from history' >&2; exit 1; } |
| | | grep -F 'timeout=query' "$history" >/dev/null || { echo 'query error missing from history' >&2; exit 1; } |
| | | [ "$(grep -c 'phase=start' "$history")" -eq 3 ] && [ "$(grep -c 'phase=end' "$history")" -eq 3 ] || { echo 'fence attempt history is incomplete' >&2; exit 1; } |
| | | grep -F 'query_exit=124 compare_exit=not-run' "$history" >/dev/null || { echo 'fence failure status missing' >&2; exit 1; } |
| | | [ -s "$OUT/scale-checkpoint/fence-d1/attempt-0001.ldif" ] && [ -s "$OUT/scale-checkpoint/fence-d1/attempt-0002.ldif" ] || { echo 'fence snapshots overwritten' >&2; exit 1; } |
| | | ) |
| | | echo 'scale lifecycle cases passed' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | HELPER="$HERE/../../../opendj-packages/opendj-docker/bootstrap/join-batch.sh" |
| | | [ -f "$HELPER" ] || { echo 'missing join batch helper' >&2; exit 1; } |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | . "$HELPER" |
| | | dsconfig_local() { [ "$1" = --batch ] || return 1; cat >"$OUT/batch"; return "${BATCH_RESULT:-0}"; } |
| | | change_replication_servers() { printf '%s\n' "$*" >>"$OUT/individual"; [ "${INDIVIDUAL_FAIL:-}" != "$2" ]; } |
| | | join_batch_changes domain 'cn=a b' --remove "rs'o:8989" server ignored --remove rs2:8989 |
| | | [ ! -e "$OUT/individual" ] || { echo 'successful batch fell back to individual commands' >&2; exit 1; } |
| | | python3 - "$OUT/batch" <<'PY' |
| | | import pathlib,shlex,sys |
| | | lines=[line for line in pathlib.Path(sys.argv[1]).read_text().splitlines() if line.strip()] |
| | | a,b=map(shlex.split,lines) |
| | | assert a==['set-replication-domain-prop','--provider-name','Multimaster Synchronization','--domain-name','cn=a b','--remove',"replication-server:rs'o:8989"],a |
| | | assert b==['set-replication-server-prop','--provider-name','Multimaster Synchronization','--remove','replication-server:rs2:8989'],b |
| | | PY |
| | | BATCH_RESULT=1 INDIVIDUAL_FAIL='cn=a b' |
| | | join_batch_changes domain 'cn=a b' --remove rs1:8989 domain cn=other --remove rs2:8989 |
| | | [ "$(wc -l <"$OUT/individual" | tr -d ' ')" = 2 ] || { echo 'batch failure did not attempt every individual command' >&2; exit 1; } |
| | | grep -F 'domain cn=other --remove rs2:8989' "$OUT/individual" >/dev/null || exit 1 |
| | | rm -f "$OUT/batch" "$OUT/individual" |
| | | BATCH_RESULT=0 INDIVIDUAL_FAIL= |
| | | join_batch_changes domain $'unsafe\nname' --remove rs1:8989 server ignored --remove rs2:8989 |
| | | [ ! -e "$OUT/batch" ] || { echo 'newline allowed in batch command' >&2; exit 1; } |
| | | grep -F 'server ignored --remove rs2:8989' "$OUT/individual" >/dev/null || exit 1 |
| | | # Exercise the production cleanup function, including collecting multiple removals. |
| | | sed -n '/^cleanup_departed() {/,/^}/p' "$HERE/../../../opendj-packages/opendj-docker/bootstrap/join.sh" >"$OUT/cleanup.sh" |
| | | . "$OUT/cleanup.sh" |
| | | PEERS_ARE_EXPLICIT=yes |
| | | registrations() { :; } |
| | | replication_server_lists() { printf 'domain\tcn=one\trs1:8989\nserver\tprovider\trs1:8989\n'; } |
| | | is_address() { return 1; }; in_peers() { return 1; }; is_self() { return 1; } |
| | | rm -f "$OUT/batch" "$OUT/individual" |
| | | cleanup_departed >/dev/null |
| | | [ "$(grep -c '^set-replication-' "$OUT/batch")" -eq 2 ] || { echo 'cleanup did not batch both removals' >&2; exit 1; } |
| | | [ ! -e "$OUT/individual" ] || { echo 'cleanup used separate commands after batch success' >&2; exit 1; } |
| | | # Exercise the production repair function, including collecting additions for distinct lists. |
| | | sed -n '/^repair_replication_servers() {/,/^}/p' "$HERE/../../../opendj-packages/opendj-docker/bootstrap/join.sh" >"$OUT/repair.sh" |
| | | . "$OUT/repair.sh" |
| | | PEERS=(rs1); REPLICATION_RETRY_COUNT=1 REPLICATION_RETRY_INTERVAL=0 REPLICATION_PORT=8989 |
| | | registered_hosts() { echo query >>"$OUT/host-queries"; echo rs1; } |
| | | replication_server_lists() { printf 'domain\tcn=one\nserver\tprovider\n'; } |
| | | in_peers() { return 0; }; names_match() { [ "$1" = "$2" ]; }; lower() { printf '%s' "$1"; } |
| | | lacked_by_a_list() { return 0; }; list_holds() { return 1; }; replication_config() { echo server; } |
| | | rm -f "$OUT/batch" "$OUT/individual" |
| | | repair_replication_servers >/dev/null |
| | | [ "$(grep -c '^set-replication-' "$OUT/batch")" -eq 2 ] || { echo 'repair did not batch both additions' >&2; exit 1; } |
| | | [ ! -e "$OUT/individual" ] || { echo 'repair used separate commands after batch success' >&2; exit 1; } |
| | | [ "$(wc -l <"$OUT/host-queries" | tr -d ' ')" = 1 ] || { echo 'repair repeated a successful registration search' >&2; exit 1; } |
| | | # If retries expire with a peer still missing, refresh once: it may register just |
| | | # after the last wait, and its replication-server list entry must not be missed. |
| | | rm -f "$OUT/host-queries" "$OUT/batch" "$OUT/individual" |
| | | PEERS=(rs1 rs2) |
| | | registered_hosts() { |
| | | echo query >>"$OUT/host-queries" |
| | | echo rs1 |
| | | [ "$(wc -l <"$OUT/host-queries" | tr -d ' ')" -lt 2 ] || echo rs2 |
| | | } |
| | | repair_replication_servers >/dev/null |
| | | [ "$(wc -l <"$OUT/host-queries" | tr -d ' ')" = 2 ] || { echo 'repair did not refresh after the last wait' >&2; exit 1; } |
| | | grep -F 'replication-server:rs2:8989' "$OUT/batch" >/dev/null || { echo 'repair missed a peer registered after the last wait' >&2; exit 1; } |
| | | # A successful reset check already established both parts of membership. Reuse it |
| | | # once, but never reuse a failed, unknown, or reset result on the next check. |
| | | sed -n '/^reset_if_unregistered() {/,/^}/p' "$HERE/../../../opendj-packages/opendj-docker/bootstrap/join.sh" >"$OUT/reset.sh" |
| | | sed -n '/^is_member() {/,/^}/p' "$HERE/../../../opendj-packages/opendj-docker/bootstrap/join.sh" >"$OUT/member.sh" |
| | | . "$OUT/reset.sh"; . "$OUT/member.sh" |
| | | holds_own_part() { echo own >>"$OUT/member-queries"; return "${OWN_RESULT:-0}"; } |
| | | registered_with_peers() { return "${PEERS_RESULT:-0}"; } |
| | | registered_here() { echo here >>"$OUT/member-queries"; return "${HERE_RESULT:-0}"; } |
| | | registered_hosts() { echo hosts >>"$OUT/member-queries"; echo self; } |
| | | is_self() { [ "$1" = self ]; } |
| | | reset_replication() { echo reset >>"$OUT/member-queries"; } |
| | | reset_if_unregistered pending |
| | | is_member || { echo 'confirmed membership rejected' >&2; exit 1; } |
| | | [ "$(wc -l <"$OUT/member-queries" | tr -d ' ')" = 2 ] || { echo 'confirmed membership was queried twice' >&2; exit 1; } |
| | | is_member || { echo 'one-use membership was not refreshed' >&2; exit 1; } |
| | | grep -Fx hosts "$OUT/member-queries" >/dev/null || { echo 'membership cache was used more than once' >&2; exit 1; } |
| | | HERE_RESULT=2 |
| | | reset_if_unregistered pending |
| | | is_member || { echo 'unknown local registration was not rechecked' >&2; exit 1; } |
| | | HERE_RESULT=1 |
| | | reset_if_unregistered pending |
| | | [ "$(tail -1 "$OUT/member-queries")" = reset ] || { echo 'missing registration did not trigger reset' >&2; exit 1; } |
| | | is_member || { echo 'membership after reset was not rechecked' >&2; exit 1; } |
| | | # The local membership search already read the registrations. When it confirms |
| | | # membership and is consumed by is_member, cleanup can use that snapshot once. |
| | | sed -n '/^registered_here() {/,/^}/p' "$HERE/../../../opendj-packages/opendj-docker/bootstrap/join.sh" >"$OUT/here.sh" |
| | | . "$OUT/here.sh" |
| | | search() { |
| | | echo search >>"$OUT/registration-queries" |
| | | printf 'dn: cn=self,cn=Servers,cn=admin data\nhostname: self\n\ndn: cn=gone,cn=Servers,cn=admin data\nhostname: gone\n' |
| | | return "${SEARCH_RESULT:-0}" |
| | | } |
| | | unregister() { printf '%s\n' "$1" >>"$OUT/unregistered"; } |
| | | replication_server_lists() { :; } |
| | | registrations() { echo fallback >>"$OUT/registration-queries"; printf 'cn=other,cn=Servers,cn=admin data\tother\n'; } |
| | | in_peers() { return 1; }; is_address() { return 1; } |
| | | HERE_RESULT=0 |
| | | reset_if_unregistered pending |
| | | is_member |
| | | cleanup_departed >/dev/null |
| | | grep -Fx 'cn=gone,cn=Servers,cn=admin data' "$OUT/unregistered" >/dev/null || { echo 'cached cleanup missed a departed server' >&2; exit 1; } |
| | | [ "$(wc -l <"$OUT/registration-queries" | tr -d ' ')" = 1 ] || { echo 'cleanup repeated the successful membership search' >&2; exit 1; } |
| | | cleanup_departed >/dev/null |
| | | grep -Fx fallback "$OUT/registration-queries" >/dev/null || { echo 'cleanup reused a snapshot twice' >&2; exit 1; } |
| | | rm -f "$OUT/registration-queries" "$OUT/unregistered" |
| | | SEARCH_RESULT=2 |
| | | reset_if_unregistered pending |
| | | cleanup_departed >/dev/null |
| | | grep -Fx fallback "$OUT/registration-queries" >/dev/null || { echo 'cleanup used a failed membership search' >&2; exit 1; } |
| | | # The peer which just confirmed membership also reported its replication shape. |
| | | # Use that result only for the immediate generation-ID check and only once. |
| | | sed -n '/^registered_with_peers() {/,/^}/p' "$HERE/../../../opendj-packages/opendj-docker/bootstrap/join.sh" >"$OUT/peer-check.sh" |
| | | sed -n '/^replicates_base_dn_after_membership() {/,/^}/p' "$HERE/../../../opendj-packages/opendj-docker/bootstrap/join.sh" >>"$OUT/peer-check.sh" |
| | | . "$OUT/peer-check.sh" |
| | | PEERS=(self p1) |
| | | replication_config() { echo "$1" >>"$OUT/config-queries"; printf 'server\ndomain\n'; } |
| | | config_shape() { echo combined; } |
| | | registered_hosts() { echo self; } |
| | | replicates_base_dn() { replication_config "$1" | grep -qx domain; } |
| | | registered_with_peers |
| | | replicates_base_dn_after_membership p1 || { echo 'confirmed domain was lost' >&2; exit 1; } |
| | | [ "$(wc -l <"$OUT/config-queries")" -eq 1 ] || { echo 'peer configuration queried again' >&2; exit 1; } |
| | | replicates_base_dn_after_membership p1 |
| | | [ "$(wc -l <"$OUT/config-queries")" -eq 2 ] || { echo 'peer configuration was reused twice' >&2; exit 1; } |
| | | registered_with_peers |
| | | replicates_base_dn_after_membership p2 |
| | | [ "$(tail -1 "$OUT/config-queries")" = p2 ] || { echo 'configuration from another peer was used' >&2; exit 1; } |
| | | registered_with_peers |
| | | registered_hosts() { return 1; } |
| | | registered_with_peers |
| | | before=$(wc -l <"$OUT/config-queries") |
| | | replicates_base_dn_after_membership p1 |
| | | [ "$(wc -l <"$OUT/config-queries")" -eq "$((before + 1))" ] || { echo 'stale peer configuration was used' >&2; exit 1; } |
| | | echo 'join batch quoting and failure fallback passed' |
| | | |
| | | # Recovery is explicit: ordinary joins must retain their peer order and update |
| | | # the DS endpoint lists. Recovery must never fall back to a DS on unknown RS state. |
| | | SOURCE="$HERE/../../../opendj-packages/opendj-docker/bootstrap/join.sh" |
| | | sed -n '/^join_candidates() {/,/^}/p; /^trusted() {/,/^}/p' "$SOURCE" >"$OUT/candidates.sh" |
| | | . "$OUT/candidates.sh" |
| | | ROLE=replication PEERS=(self d0 r0 r1) REPLICATION_RECOVER_FROM_RS=1 |
| | | is_self() { [ "$1" = self ]; } |
| | | peer_state() { |
| | | case " ${STATE_FAIL:-} " in *" $1 "*) return 1 ;; esac |
| | | if [ "${STATE_ABSENT:-}" = "$1" ]; then echo absent; else echo ready; fi |
| | | } |
| | | replication_config() { |
| | | case " ${CONFIG_FAIL:-} " in *" $1 "*) return 1 ;; esac |
| | | case $1 in r0|r1) printf 'server\npublished replication\n' ;; *) echo domain ;; esac |
| | | } |
| | | join_failures=0 |
| | | expect_candidates() { |
| | | local actual |
| | | actual=$(join_candidates) |
| | | if [ "$actual" != "$2" ]; then |
| | | echo "::error::$1: candidates [$actual], expected [$2]" >&2 |
| | | join_failures=$((join_failures + 1)) |
| | | fi |
| | | } |
| | | expect_candidates retained-rs $'r0\nr1' |
| | | CONFIG_FAIL='r0 r1' |
| | | expect_candidates unknown-rs-config '' |
| | | CONFIG_FAIL= STATE_FAIL='r0 r1' |
| | | expect_candidates unknown-rs-state '' |
| | | STATE_FAIL= |
| | | PEERS=(self d0) |
| | | expect_candidates no-retained-rs '' |
| | | REPLICATION_RECOVER_FROM_RS=0 |
| | | expect_candidates ordinary-first-rs d0 |
| | | PEERS=(self d0 r0 r1) |
| | | expect_candidates ordinary-rs-order $'d0\nr0\nr1' |
| | | ROLE=directory REPLICATION_RECOVER_FROM_RS=1 |
| | | expect_candidates directory-order $'d0\nr0\nr1' |
| | | # MASTER_SERVER alone preserves legacy trust for an ordinary join only. |
| | | ROLE=replication MASTER_SERVER=r0 PEERS_ARE_EXPLICIT= STATE_ABSENT=r0 |
| | | PEERS=("$MASTER_SERVER") |
| | | expect_candidates recovery-master-without-state '' |
| | | REPLICATION_RECOVER_FROM_RS=0 |
| | | expect_candidates ordinary-master-without-state r0 |
| | | trusted absent || { echo 'ordinary MASTER_SERVER join rejected an older peer' >&2; exit 1; } |
| | | STATE_ABSENT= |
| | | |
| | | sed -n '/^enable_through() {/,/^}/p; /^role_arguments() {/,/^}/p' "$SOURCE" >"$OUT/enable.sh" |
| | | . "$OUT/enable.sh" |
| | | # The image uses Bash 4+; keep this harness usable with macOS Bash 3 too. |
| | | if ! type mapfile >/dev/null 2>&1; then |
| | | mapfile() { local value; local -a values=(); while IFS= read -r value; do values+=("$value"); done; eval "$2=(\"\${values[@]}\")"; } |
| | | fi |
| | | ROLE=replication BASE_DN=dc=example,dc=com REPLICATION_PORT=8989 |
| | | take_join_lock() { |
| | | JOIN_LOCK_VALUE=lock |
| | | if [ "${STATE_LOST_ON_LOCK:-}" = "$1" ]; then STATE_ABSENT=$1; fi |
| | | } |
| | | release_join_lock() { :; } |
| | | peer_role() { case $1 in *server*) echo replication ;; *) echo directory ;; esac; } |
| | | bounded() { printf '%s\n' "$@" >"$OUT/enable-args"; } |
| | | expect_enable_args() { |
| | | local actual schema_flag=no |
| | | enable_through "$1" |
| | | actual=$(awk 'previous=="--baseDN" {print;exit} {previous=$0}' "$OUT/enable-args") |
| | | if [ "$actual" != "$2" ]; then |
| | | echo "::error::enable $1 used [$actual], expected [$2]" >&2 |
| | | join_failures=$((join_failures + 1)) |
| | | fi |
| | | if grep -Fxq -- --noSchemaReplication "$OUT/enable-args"; then schema_flag=yes; fi |
| | | if [ "$schema_flag" != "$3" ]; then |
| | | echo "::error::enable $1: --noSchemaReplication present [$schema_flag], expected [$3]" >&2 |
| | | join_failures=$((join_failures + 1)) |
| | | fi |
| | | } |
| | | REPLICATION_RECOVER_FROM_RS=1 |
| | | expect_enable_args r0 'cn=admin data' yes |
| | | REPLICATION_RECOVER_FROM_RS=0 |
| | | STATE_ABSENT=r0 |
| | | expect_enable_args r0 "$BASE_DN" no |
| | | expect_enable_args d0 "$BASE_DN" no |
| | | STATE_ABSENT= |
| | | REPLICATION_RECOVER_FROM_RS=1 |
| | | expect_candidates recovery-master-ready-before-lock r0 |
| | | for unavailable in changed-role changed-state absent-state-under-lock; do |
| | | rm -f "$OUT/enable-args" |
| | | peer=r0 STATE_FAIL= STATE_LOST_ON_LOCK= rc=0 |
| | | case $unavailable in |
| | | changed-role) peer=d0 ;; |
| | | changed-state) STATE_FAIL=r0 ;; |
| | | absent-state-under-lock) STATE_LOST_ON_LOCK=r0 ;; |
| | | esac |
| | | enable_through "$peer" || rc=$? |
| | | if [ "$rc" -ne 75 ]; then |
| | | echo "::error::recovery returned $rc through $unavailable, expected 75" >&2 |
| | | join_failures=$((join_failures + 1)) |
| | | fi |
| | | if [ -e "$OUT/enable-args" ]; then |
| | | echo "::error::recovery changed topology through $unavailable" >&2 |
| | | join_failures=$((join_failures + 1)) |
| | | fi |
| | | done |
| | | [ "$join_failures" = 0 ] || exit 1 |
| | | echo 'ordinary joins and fail-closed RS recovery selection passed' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | SOURCE="$HERE/../../../opendj-packages/opendj-docker/bootstrap/join.sh" |
| | | sed -n '/^reset_replication() {/,/^}/p' "$SOURCE" >"$OUT/reset.sh" |
| | | sed -n '/^reset_if_unregistered() {/,/^}/p' "$SOURCE" >>"$OUT/reset.sh" |
| | | . "$OUT/reset.sh" |
| | | ROLE=combined ROOT_USER_DN='cn=Directory Manager' MYHOSTNAME=d1 ADMIN_PORT=4444 |
| | | REPLICATION_ATTEMPT_TIMEOUT=120 PASSWORD_FILE="$OUT/password" |
| | | REJOIN_PENDING="$OUT/rejoin" BOOTSTRAP_COMPLETE="$OUT/ready" RESET_PENDING="$OUT/reset-pending" |
| | | publish_state() { printf '%s\n' "$1" >"$OUT/state"; } |
| | | take_join_lock() { JOIN_LOCK_VALUE=ours; } |
| | | release_join_lock() { printf '%s\n' "$*" >>"$OUT/releases"; return "${RELEASE_RC:-0}"; } |
| | | hold_writes() { touch "$OUT/read-only"; } |
| | | registrations() { :; } |
| | | bounded() { |
| | | printf '%s\n' "$@" >"$OUT/disable-arguments" |
| | | return "${DISABLE_RC:-0}" |
| | | } |
| | | search() { printf '%s' "${REMAINING_CONFIG:-}"; return "${SEARCH_RC:-0}"; } |
| | | assert_reset_fails() { |
| | | local rc=0 |
| | | touch "$BOOTSTRAP_COMPLETE" |
| | | : >"$OUT/releases" |
| | | reset_replication pending fixture >"$OUT/result" || rc=$? |
| | | [ "$rc" -ne 0 ] || { echo 'failed reset reported success' >&2; exit 1; } |
| | | [ -f "$REJOIN_PENDING" ] && [ -f "$OUT/read-only" ] && [ ! -f "$BOOTSTRAP_COMPLETE" ] |
| | | [ "$(cat "$OUT/releases")" = 'localhost ours' ] || { echo 'reset did not release its lock' >&2; exit 1; } |
| | | } |
| | | DISABLE_RC=8 |
| | | assert_reset_fails |
| | | DISABLE_RC=0 REMAINING_CONFIG=$'dn: cn=admin data,cn=domains,cn=Multimaster Synchronization,cn=Synchronization Providers,cn=config\n' |
| | | assert_reset_fails |
| | | REMAINING_CONFIG= SEARCH_RC=81 |
| | | assert_reset_fails |
| | | SEARCH_RC=0 RELEASE_RC=1 |
| | | assert_reset_fails |
| | | RELEASE_RC=0 |
| | | reset_replication pending fixture >/dev/null |
| | | # The supported local bind must work before a replicated global admin exists. |
| | | grep -Fx -- --bindDN "$OUT/disable-arguments" >/dev/null |
| | | grep -Fx -- "$ROOT_USER_DN" "$OUT/disable-arguments" >/dev/null |
| | | ! grep -Fx -- --adminUID "$OUT/disable-arguments" >/dev/null |
| | | [ ! -f "$BOOTSTRAP_COMPLETE" ] && [ -f "$OUT/read-only" ] |
| | | # The caller must not enable after a failed reset, on either membership road. |
| | | holds_own_part() { return 0; } |
| | | registered_with_peers() { return "${PEER_RC:-0}"; } |
| | | registered_here() { return 1; } |
| | | DISABLE_RC=8 |
| | | for PEER_RC in 0 1; do |
| | | if reset_if_unregistered pending >"$OUT/result"; then |
| | | echo 'failed reset admitted enable' >&2; exit 1 |
| | | fi |
| | | done |
| | | DISABLE_RC=0 |
| | | reset_if_unregistered pending >/dev/null |
| | | reset_if_unregistered pending >/dev/null |
| | | # A failed reset may already have removed BASE_DN. The next round must finish |
| | | # that cleanup rather than concluding there is no replication left to reset. |
| | | RESET_PENDING="$OUT/reset-pending" |
| | | DISABLE_RC=11 |
| | | assert_reset_fails |
| | | holds_own_part() { return 1; } |
| | | if reset_if_unregistered pending >"$OUT/result"; then |
| | | echo 'partial reset was forgotten after its data domain disappeared' >&2; exit 1 |
| | | fi |
| | | DISABLE_RC=0 |
| | | reset_if_unregistered pending >/dev/null |
| | | [ ! -f "$RESET_PENDING" ] || { echo 'completed reset stayed pending' >&2; exit 1; } |
| | | echo 'join reset preserves errors, authenticates locally, verifies cleanup and keeps writes gated' |
| | | |
| | | # The actual background-join wrapper publishes a terminal result while preserving |
| | | # the child status. Stub only the external child executable. |
| | | sed -n '/^run_join() {/,/^}/p' "$HERE/../../../opendj-packages/opendj-docker/run.sh" >"$OUT/run-join.sh" |
| | | . "$OUT/run-join.sh" |
| | | function /opt/opendj/bootstrap/join.sh { return "$JOIN_RESULT"; } |
| | | BOOTSTRAP_FAILED="$OUT/bootstrap-failed" BOOTSTRAP_FINISHED="$OUT/bootstrap-finished" JOIN_RESULT=8 |
| | | rc=0; run_join || rc=$? |
| | | [ "$rc" -eq 8 ] || { echo "failed join returned $rc, expected 8" >&2; exit 1; } |
| | | [ "$(cat "$BOOTSTRAP_FAILED")" = join:8 ] || { echo 'failed join did not publish join:8' >&2; exit 1; } |
| | | [ ! -f "$BOOTSTRAP_FINISHED" ] || { echo 'failed join published completion' >&2; exit 1; } |
| | | rm "$BOOTSTRAP_FAILED" |
| | | JOIN_RESULT=0 |
| | | run_join |
| | | [ -f "$BOOTSTRAP_FINISHED" ] || { echo 'successful join did not publish completion' >&2; exit 1; } |
| | | [ ! -f "$BOOTSTRAP_FAILED" ] |
| | | echo 'background join preserves its exit status and publishes failure' |
| | | |
| | | # Exercise the production release helper too: a diagnostic echo must not turn a |
| | | # failed LDAP delete into success and erase the persistent reset marker. |
| | | sed -n '/^release_join_lock() {/,/^}/p' "$SOURCE" >"$OUT/release.sh" |
| | | . "$OUT/release.sh" |
| | | JOIN_LOCK_DN='cn=join-lock,cn=config' JOIN_LOCK_TTL=120 |
| | | ldapmodify_on() { cat >"$OUT/lock-delete.ldif"; return "$LOCK_DELETE_RC"; } |
| | | LOCK_DELETE_RC=8 |
| | | rc=0; reset_replication pending fixture >"$OUT/result" || rc=$? |
| | | [ "$rc" -ne 0 ] || { echo 'failed real lock release reported success' >&2; exit 1; } |
| | | [ -f "$RESET_PENDING" ] || { echo 'failed real lock release erased reset marker' >&2; exit 1; } |
| | | LOCK_DELETE_RC=0 |
| | | reset_if_unregistered pending >/dev/null |
| | | [ ! -f "$RESET_PENDING" ] |
| | | echo 'real lock release preserves LDAP failure and permits a later successful retry' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d) |
| | | trap 'join_search_close; rm -rf "$OUT"' EXIT |
| | | . "$HERE/../../../opendj-packages/opendj-docker/bootstrap/join-search.sh" |
| | | mkdir -p "$OUT/lib" |
| | | cat >"$OUT/lib/_script-util.sh" <<'UTIL' |
| | | printf 'start\n' >>"$INSTALL_ROOT/starts" |
| | | OPENDJ_JAVA_BIN="$INSTALL_ROOT/worker" |
| | | UTIL |
| | | cat >"$OUT/worker" <<'WORKER' |
| | | #!/usr/bin/env python3 |
| | | import sys, base64, time |
| | | for line in sys.stdin: |
| | | args = base64.b64decode(line).decode().split('\0')[:-1] |
| | | if args == ['die']: |
| | | sys.exit(1) |
| | | if args == ['hang']: |
| | | time.sleep(30) |
| | | if args == ['bad-frame']: |
| | | print('0 cGFydGlhbA==!', flush=True) |
| | | continue |
| | | status = 0 |
| | | output = '|'.join(args) |
| | | if args == ['size-limited']: |
| | | status = 4 |
| | | output = 'dn: cn=partial,dc=example\ncn: partial\n\n' |
| | | print(str(status) + ' ' + base64.b64encode(output.encode()).decode(), flush=True) |
| | | WORKER |
| | | chmod +x "$OUT/worker" |
| | | JOIN_INSTALL_ROOT=$OUT |
| | | # OpenDJ itself has a different base64 CLI at the front of the bootstrap PATH. |
| | | mkdir -p "$OUT/bin" |
| | | printf '#!/bin/sh\nexit 42\n' >"$OUT/bin/base64" |
| | | chmod +x "$OUT/bin/base64" |
| | | PATH="$OUT/bin:$PATH" |
| | | join_search_init |
| | | ldapsearch() { printf 'fallback'; } |
| | | [ "$(join_search 'a b' '' $'unicode-тест\nnext')" = $'a b||unicode-тест\nnext' ] |
| | | rc=0 |
| | | join_search size-limited >"$OUT/partial.ldif" || rc=$? |
| | | [ "$rc" = 4 ] |
| | | printf 'dn: cn=partial,dc=example\ncn: partial\n\n' >"$OUT/expected.ldif" |
| | | cmp "$OUT/expected.ldif" "$OUT/partial.ldif" |
| | | [ "$(join_search next)" = next ] |
| | | [ "$(wc -l <"$OUT/starts" | tr -d ' ')" = 1 ] || { echo 'worker started more than once' >&2; exit 1; } |
| | | [ "$(join_search die)" = fallback ] |
| | | [ "$(join_search after-death)" = fallback ] |
| | | join_search_close |
| | | [ ! -d "${JOIN_SEARCH_DIR:-/path-which-must-not-exist}" ] |
| | | for failure in hang bad-frame; do |
| | | join_search_init |
| | | REPLICATION_ATTEMPT_TIMEOUT=1 |
| | | [ "$(join_search "$failure" 2>/dev/null)" = fallback ] |
| | | [ "$(join_search after-failure)" = fallback ] |
| | | join_search_close |
| | | done |
| | | printf '#!/bin/sh\nexit 1\n' >"$OUT/worker" |
| | | join_search_init |
| | | [ "$(join_search after-startup-failure 2>/dev/null)" = fallback ] |
| | | join_search_close |
| | | echo 'join search reuses the process, preserves statuses and falls back after worker death' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | TIMING="$HERE/../../../opendj-packages/opendj-docker/bootstrap/join-timing.sh" |
| | | [ -f "$TIMING" ] || { echo 'missing bootstrap timing helper' >&2; exit 1; } |
| | | OUT=$(mktemp -d) |
| | | trap 'rm -rf "$OUT"' EXIT |
| | | ( |
| | | JOIN_TIMING=1 |
| | | . "$TIMING" |
| | | join_timing_init 2>"$OUT/timing" |
| | | command_that_reads_stdin() { read -r value; printf '%s\n' "$value"; return 7; } |
| | | rc=0 |
| | | output=$(printf 'stdin-value\n' | join_timed probe command_that_reads_stdin secret-argument 2>/dev/null) || rc=$? |
| | | [ "$rc" -eq 7 ] && [ "$output" = stdin-value ] || exit 1 |
| | | grep -E 'join-timing event=start .*step=probe' "$OUT/timing" >/dev/null |
| | | grep -E 'join-timing event=end .*step=probe .*status=7' "$OUT/timing" >/dev/null |
| | | if grep -F 'secret-argument' "$OUT/timing" >/dev/null; then echo 'timing leaks command arguments' >&2; exit 1; fi |
| | | join_timed success true |
| | | grep -E 'join-timing event=end .*step=success .*status=0' "$OUT/timing" >/dev/null |
| | | ) |
| | | ( |
| | | JOIN_TIMING=0 |
| | | . "$TIMING" |
| | | join_timing_init 2>"$OUT/disabled" |
| | | [ "$(join_timed disabled printf '%s' result)" = result ] |
| | | [ ! -s "$OUT/disabled" ] |
| | | ) |
| | | # Starting a join needs the real config search to succeed; a separate root-DSE |
| | | # search adds a JVM but provides no readiness guarantee beyond that search. |
| | | sed -n '/^echo "join: waiting for the server on the administration connector"/,/^done$/p' \ |
| | | "$HERE/../../../opendj-packages/opendj-docker/bootstrap/join.sh" >"$OUT/wait-config.sh" |
| | | ( |
| | | calls="$OUT/config-calls"; sleeps="$OUT/config-sleeps"; extra="$OUT/extra-root-search" |
| | | server_up() { echo called >>"$extra"; return 0; } |
| | | replication_config() { |
| | | echo called >>"$calls" |
| | | [ "$(wc -l <"$calls" | tr -d ' ')" -gt "${FAIL_SEARCHES:-0}" ] || return 1 |
| | | printf 'server\ndomain\n' |
| | | } |
| | | sleep() { echo sleep >>"$sleeps"; } |
| | | FAIL_SEARCHES=0 |
| | | . "$OUT/wait-config.sh" >/dev/null |
| | | [ "$own_config" = $'server\ndomain' ] || { echo 'join lost its initial configuration' >&2; exit 1; } |
| | | [ "$(wc -l <"$calls" | tr -d ' ')" = 1 ] || { echo 'join repeated an already successful config search' >&2; exit 1; } |
| | | [ ! -e "$extra" ] || { echo 'join made an extra readiness search' >&2; exit 1; } |
| | | rm -f "$calls" "$sleeps" "$extra" |
| | | FAIL_SEARCHES=2 |
| | | . "$OUT/wait-config.sh" >/dev/null |
| | | [ "$(wc -l <"$calls" | tr -d ' ')" = 3 ] && [ "$(wc -l <"$sleeps" | tr -d ' ')" = 2 ] || { echo 'join did not retry a failed config search' >&2; exit 1; } |
| | | rm -f "$calls" "$sleeps" "$extra" |
| | | FAIL_SEARCHES=150 |
| | | if ( . "$OUT/wait-config.sh" ) >/dev/null 2>&1; then echo 'join accepted unavailable configuration' >&2; exit 1; fi |
| | | [ "$(wc -l <"$calls" | tr -d ' ')" = 150 ] || { echo 'join changed the retry bound' >&2; exit 1; } |
| | | ) |
| | | echo 'join timing preserves input, output and exit status' |
| | |
| | | E66='[t] category=SYNC severity=ERROR msgID=66 msg=monitor reply failed' |
| | | E108='[t] category=SYNC severity=ERROR msgID=108 msg=monitor request failed' |
| | | E51='[05/Nov/2026:19:18:17 +0000] category=SYNC severity=ERROR msgID=51 msg=The hostname cv-r0 could not be resolved as an IP address' |
| | | BASE_DN=dc=example,dc=com |
| | | E212='[t] category=SYNC severity=ERROR msgID=212 msg=Directory server DS(23874) timed out while connecting to replication server cv-r1:8989 for domain "dc=example,dc=com"' |
| | | E18='[t] category=SYNC severity=ERROR msgID=18 msg=an id that starts the first one a window lists' |
| | | E80='[t] category=SYNC severity=ERROR msgID=80 msg=an id that ends the first one a window lists' |
| | | E106KILL='[t] category=SYNC severity=ERROR msgID=106 msg=an id a window lists, 181, in the message' |
| | |
| | | case_ ds-disconnect-before-after 2 1 "$E211" '[ 211' "$E211" ']' "$E211" |
| | | case_ monitors-in-combined-kill 2 0 '[ dns:cv-c1 180 181 211 284' "$E66" "$E108" ']' |
| | | |
| | | # Only the restarted DS may temporarily reject the new RS certificate during its window. |
| | | WBAD_RS='[t] category=SYNC severity=WARNING msgID=119 msg=Directory server DS(1) encountered an unexpected error while connecting to replication server cv-r1:8989 for domain "dc=example,dc=com": SSLHandshakeException((bad_certificate) PKIX path validation failed)' |
| | | case_ new-cert-exact 0 1 '[ cert:n0:cv-r1' "$WBAD_RS" ']' |
| | | case_ new-cert-wrong-rs 1 0 '[ cert:n0:cv-r0' "$WBAD_RS" ']' |
| | | case_ new-cert-wrong-ds 1 0 '[ cert:n1:cv-r1' "$WBAD_RS" ']' |
| | | case_ new-cert-outside 2 1 "$WBAD_RS" '[ cert:n0:cv-r1' "$WBAD_RS" ']' "$WBAD_RS" |
| | | case_ new-cert-unknown 1 0 '[ cert:n0:cv-r1' "${WBAD_RS/bad_certificate/other_error}" ']' |
| | | case_ new-cert-other-category 1 0 '[ cert:n0:cv-r1' "${WBAD_RS/category=SYNC/category=CORE}" ']' |
| | | # An RS-to-RS certificate warning requires a later recovery of that exact session |
| | | # in the same rebuild window, including its RS id and domain (which may contain spaces). |
| | | WRSCERT='[t] category=SYNC severity=WARNING msgID=312 msg=Replication server RS(31897) could not connect to replication server cv-c3:8989 for domain "cn=admin data": SSLHandshakeException((bad_certificate) PKIX path validation failed). This is reported once: the next message comes when it can be reached again' |
| | | NRSCERT='[t] category=SYNC severity=NOTICE msgID=313 msg=Replication server RS(31897) connected to replication server cv-c3:8989 for domain "cn=admin data", which it had reported it had no replication session with' |
| | | case_ rs-cert-recovered 0 1 '[ cert:n0:cv-c3' "$WRSCERT" "$NRSCERT" ']' |
| | | case_ scale-rs-cert-recovered 0 1 '[ cert:n0:cv-c3 scale-cert-return' "$WRSCERT" "$NRSCERT" ']' |
| | | case_ rs-cert-not-recovered 1 0 '[ cert:n0:cv-c3' "$WRSCERT" ']' |
| | | case_ rs-cert-recovered-before 1 0 '[ cert:n0:cv-c3' "$NRSCERT" "$WRSCERT" ']' |
| | | case_ rs-cert-recovered-after 1 0 '[ cert:n0:cv-c3' "$WRSCERT" ']' "$NRSCERT" |
| | | case_ rs-cert-outside 1 0 "$WRSCERT" '[ cert:n0:cv-c3' "$NRSCERT" ']' |
| | | case_ rs-cert-wrong-node 1 0 '[ cert:n1:cv-c3' "$WRSCERT" "$NRSCERT" ']' |
| | | case_ rs-cert-unknown-peer 1 0 '[ cert:n0:cv-c2' "$WRSCERT" "$NRSCERT" ']' |
| | | for notice in "${NRSCERT/RS(31897)/RS(31898)}" "${NRSCERT/cv-c3/cv-c2}" "${NRSCERT/cn=admin data/cn=schema}" "${NRSCERT/msgID=313/msgID=62}"; do |
| | | case_ rs-cert-wrong-recovery 1 0 '[ cert:n0:cv-c3' "$WRSCERT" "$notice" ']' |
| | | done |
| | | case_ rs-cert-other-error 1 0 '[ cert:n0:cv-c3' "${WRSCERT/bad_certificate/certificate_unknown}" "$NRSCERT" ']' |
| | | case_ rs-cert-next-window 1 0 '[ cert:n0:cv-c3' "$WRSCERT" ']' '[ cert:n0:cv-c3' "$NRSCERT" ']' |
| | | |
| | | # The RS also reports the rejected handshake, identifying the remote DS by IP and port. |
| | | WBAD_PEER='[t] category=SYNC severity=WARNING msgID=105 msg=Replication server accepted a connection from /172.18.0.9:43210 to local address /172.18.0.2:8989 but the SSL handshake failed. The error was: Received fatal alert: bad_certificate' |
| | | case_ new-cert-rs-side 0 1 '[ cert-peer:n0:172.18.0.9' "$WBAD_PEER" ']' |
| | | case_ new-cert-rs-jdk-prefix 0 1 '[ cert-peer:n0:172.18.0.9' "${WBAD_PEER/The error was: Received/The error was: (bad_certificate) Received}" ']' |
| | | case_ new-cert-rs-other-ip 1 0 '[ cert-peer:n0:172.18.0.8' "$WBAD_PEER" ']' |
| | | case_ new-cert-rs-other-node 1 0 '[ cert-peer:n1:172.18.0.9' "$WBAD_PEER" ']' |
| | | case_ new-cert-rs-outside 1 0 "$WBAD_PEER" '[ cert-peer:n0:172.18.0.9' ']' |
| | | case_ new-cert-rs-other-fault 1 0 '[ cert-peer:n0:172.18.0.9' "${WBAD_PEER/Received fatal alert: bad_certificate/unexpected bad_certificate}" ']' |
| | | # Scale may verify recovery during the roll after the narrow return window closes. |
| | | # A WARN105 must match the client-side TLS failure on the same TCP connection. |
| | | SCALE_WARNING="[18/Nov/2026:12:00:01 +0000]${WBAD_RS:3}" |
| | | SCALE_PEER="[18/Nov/2026:12:00:01 +0000]${WBAD_PEER:3}" |
| | | SCALE_CONNECTED='[18/Nov/2026:12:00:02 +0000] category=SYNC severity=NOTICE msgID=62 msg=Directory server DS(1) has connected to replication server RS(42) for domain "dc=example,dc=com" at 172.18.0.2:8989 with generation ID 3' |
| | | SCALE_SCHEMA_WARNING=${SCALE_WARNING/dc=example,dc=com/cn=schema} |
| | | SCALE_ADMIN_WARNING=${SCALE_WARNING/dc=example,dc=com/cn=admin data} |
| | | SCALE_ADMIN_CONNECTED=${SCALE_CONNECTED/dc=example,dc=com/cn=admin data} |
| | | SCALE_SAME_SECOND=${SCALE_CONNECTED/12:00:02/12:00:01} |
| | | SCALE_RS_WARNING="[18/Nov/2026:12:00:01 +0000]${WRSCERT:3}" |
| | | SCALE_RS_WARNING=${SCALE_RS_WARNING/cv-c3/cv-r1} |
| | | SCALE_RS_RECOVERY="[18/Nov/2026:12:00:02 +0000]${NRSCERT:3}" |
| | | SCALE_RS_RECOVERY=${SCALE_RS_RECOVERY/cv-c3/cv-r1} |
| | | SCALE_RS_ACCEPTOR=${SCALE_PEER/172.18.0.9/172.18.0.7} |
| | | |
| | | scale_tls_attempt() { # <second> <role and ID> <domain> <source IP:port> [<destination IP:port>] |
| | | printf '[18/Nov/2026:12:00:%s +0000] category=SYNC severity=NOTICE msgID=341 msg=Replication TLS client handshake failed for %s for domain "%s" from /%s to cv-r1/%s' \ |
| | | "$1" "$2" "$3" "$4" "${5:-172.18.0.2:8989}" |
| | | } |
| | | |
| | | SCALE_DS_ATTEMPT=$(scale_tls_attempt 01 'DS(1)' dc=example,dc=com 172.18.0.9:43210) |
| | | SCALE_DS_FAILURE="$SCALE_DS_ATTEMPT"$'\n'"$SCALE_WARNING" |
| | | SCALE_ADMIN_FAILURE="${SCALE_DS_ATTEMPT/dc=example,dc=com/cn=admin data}"$'\n'"$SCALE_ADMIN_WARNING" |
| | | SCALE_SCHEMA_FAILURE=$(scale_tls_attempt 01 'DS(1)' cn=schema 172.18.0.9:43212) |
| | | SCALE_SCHEMA_FAILURE="$SCALE_SCHEMA_FAILURE"$'\n'"$SCALE_SCHEMA_WARNING" |
| | | SCALE_RS_ATTEMPT=$(scale_tls_attempt 01 'RS(31897)' 'cn=admin data' 172.18.0.7:43210) |
| | | SCALE_RS_FAILURE="$SCALE_RS_ATTEMPT"$'\n'"$SCALE_RS_WARNING" |
| | | SCALE_RS_NEXT_SECOND=${SCALE_RS_ACCEPTOR/12:00:01/12:00:02} |
| | | SCALE_RS_RECOVERED_ON_RETRY=${SCALE_RS_RECOVERY/12:00:02/12:00:03} |
| | | |
| | | # <return DS log> <acceptor log> <scale-out DS log> [<post-scale DS log>] |
| | | # [<window change>] [<in-window RS caller log>] [<scale-out RS caller log>] |
| | | scale_cert_result() ( |
| | | rm -rf "$OUT/logs" |
| | | ALL_NODES='n0 n1 cv-r0 cv-r1' |
| | | DS_NODES='n0 n1' RS_ONLY='cv-r0 cv-r1' TOPOLOGY=rs534 SCALE_VOLUME=empty |
| | | RS_NODES=$RS_ONLY PEERS=n0,n1,cv-r0,cv-r1 |
| | | local caller=cv-r0 |
| | | if [ "${5:-}" = combined-peer ]; then |
| | | TOPOLOGY=combined DS_NODES=$ALL_NODES RS_ONLY= RS_NODES=$ALL_NODES |
| | | caller=n0 |
| | | fi |
| | | . "$HERE/disturb-scale.sh" |
| | | docker() { |
| | | case "$1 $3" in |
| | | "exec sh") wc -l <"$OUT/errors-$2" ;; |
| | | "exec tail") tail -n "$5" "$OUT/errors-$2" ;; |
| | | *) return 1 ;; |
| | | esac |
| | | } |
| | | printf '%s\n' "$E106" >"$OUT/errors-n0" |
| | | printf '%s\n' "$E106" >"$OUT/errors-cv-r1" |
| | | printf '%s\n' "$E106" >"$OUT/errors-n1" |
| | | printf '%s\n' "$E106" >"$OUT/errors-cv-r0" |
| | | mark_logs |
| | | window_open dns:cv-r1 cert:n0:cv-r1 cert:cv-r0:cv-r1 cert-peer:cv-r1:172.18.0.9 scale-cert-return |
| | | [ -z "$1" ] || printf '%s\n' "$1" >>"$OUT/errors-n0" |
| | | [ -z "$2" ] || printf '%s\n' "$2" >>"$OUT/errors-cv-r1" |
| | | [ -z "${6:-}" ] || printf '%s\n' "$6" >>"$OUT/errors-$caller" |
| | | window_close |
| | | [ -z "$3" ] || printf '%s\n' "$3" >>"$OUT/errors-n0" |
| | | [ -z "${7:-}" ] || printf '%s\n' "$7" >>"$OUT/errors-$caller" |
| | | printf '%s\n' "$SCALE_CONNECTED" >>"$OUT/errors-n1" |
| | | scale_record_certificate_recoveries 172.18.0.2 n0=172.18.0.9 n1=172.18.0.8 cv-r0=172.18.0.7 || exit 1 |
| | | [ -z "${4:-}" ] || printf '%s\n' "$4" >>"$OUT/errors-n0" |
| | | case ${5:-} in |
| | | move-window) |
| | | printf '1 1 scale-cert-return\n' >"$OUT/logs/n0.windows" |
| | | printf '1 1 scale-cert-return\n' >"$OUT/logs/cv-r1.windows" |
| | | ;; |
| | | ordinary-window) |
| | | printf '1 3 dns:cv-r1\n' >"$OUT/logs/n0.windows" |
| | | printf '1 2 dns:cv-r1\n' >"$OUT/logs/cv-r1.windows" |
| | | ;; |
| | | esac |
| | | [ -z "$(sort "$OUT/logs/scale-certificates" | uniq -d)" ] || { echo 'duplicate certificate proof' >&2; exit 1; } |
| | | local caller_errors acceptor_errors |
| | | caller_errors=$(replication_errors "${SCALE_CERT_CALLER:-n0}") || exit 1 |
| | | acceptor_errors=$(replication_errors cv-r1) || exit 1 |
| | | for errors in "$caller_errors" "$acceptor_errors"; do |
| | | if [ -n "$errors" ]; then printf '%s\n' "$errors"; fi |
| | | printf '%s\n' --- |
| | | done |
| | | ) |
| | | |
| | | scale_cert_case() { # <name> <unexpected caller lines> <unexpected acceptor lines> <logs...> |
| | | local name=$1 want_caller=$2 want_acceptor=$3 result |
| | | shift 3 |
| | | if result=$(scale_cert_result "$@") && [ "$result" = "$(for errors in "$want_caller" "$want_acceptor"; do |
| | | if [ -n "$errors" ]; then printf '%s\n' "$errors"; fi |
| | | printf '%s\n' --- |
| | | done)" ]; then |
| | | passed=$((passed + 1)) |
| | | else |
| | | failed=$((failed + 1)) |
| | | echo "::error::$name: unexpected certificate classification" |
| | | printf '%s\n' "$result" |
| | | fi |
| | | } |
| | | |
| | | scale_rs_cert_case() { |
| | | SCALE_CERT_CALLER=cv-r0 scale_cert_case "$@" |
| | | } |
| | | |
| | | scale_cert_case scale-cert-no-recovery "$SCALE_WARNING" "$SCALE_PEER" "$SCALE_DS_FAILURE" "$SCALE_PEER" '' |
| | | scale_cert_case scale-cert-recovered '' '' "$SCALE_DS_FAILURE"$'\n'"$SCALE_CONNECTED" "$SCALE_PEER" '' |
| | | scale_cert_case scale-cert-peer-jdk-prefix '' '' "$SCALE_DS_FAILURE" "${SCALE_PEER/The error was: Received/The error was: (bad_certificate) Received}" "$SCALE_CONNECTED" |
| | | scale_cert_case scale-cert-recovered-on-roll '' '' "$SCALE_DS_FAILURE" "$SCALE_PEER" "$SCALE_CONNECTED" |
| | | scale_cert_case scale-cert-admin-domain '' '' "$SCALE_ADMIN_FAILURE" "$SCALE_PEER" "$SCALE_ADMIN_CONNECTED" |
| | | scale_cert_case scale-cert-recovery-after-roll "$SCALE_WARNING" "$SCALE_PEER" "$SCALE_DS_FAILURE" "$SCALE_PEER" '' "$SCALE_CONNECTED" |
| | | scale_cert_case scale-cert-repeated-after-roll "$SCALE_WARNING" '' "$SCALE_DS_FAILURE" "$SCALE_PEER" "$SCALE_CONNECTED" "$SCALE_WARNING" |
| | | scale_cert_case scale-cert-warnings-after-return "$SCALE_WARNING" '' '' '' "$SCALE_DS_FAILURE"$'\n'"$SCALE_CONNECTED" |
| | | scale_cert_case scale-cert-before-warning "$SCALE_WARNING" "$SCALE_PEER" "$SCALE_CONNECTED"$'\n'"$SCALE_DS_FAILURE" "$SCALE_PEER" '' |
| | | scale_cert_case scale-cert-peer-same-second '' '' "$SCALE_DS_FAILURE" "$SCALE_PEER" "$SCALE_SAME_SECOND" |
| | | scale_cert_case scale-cert-peer-two-notices '' '' "$SCALE_DS_FAILURE" "$SCALE_PEER" "$SCALE_SAME_SECOND"$'\n'"$SCALE_CONNECTED" |
| | | scale_cert_case scale-cert-warning-without-attempt '' "$SCALE_PEER" "$SCALE_WARNING" "$SCALE_PEER" "$SCALE_CONNECTED" |
| | | |
| | | # Assert both logs. The acceptor's rejected handshake and the caller's outage are separate records. |
| | | scale_rs_cert_case scale-rs-peer-recovered '' '' '' "$SCALE_RS_ACCEPTOR" '' '' '' "$SCALE_RS_FAILURE"$'\n'"$SCALE_RS_RECOVERY" |
| | | scale_rs_cert_case scale-rs-peer-adjacent-seconds '' '' '' "$SCALE_RS_NEXT_SECOND" '' '' '' \ |
| | | "$SCALE_RS_FAILURE"$'\n'"$SCALE_RS_RECOVERED_ON_RETRY" |
| | | scale_rs_cert_case scale-rs-peer-retry-without-warn312 '' '' '' "$SCALE_RS_NEXT_SECOND" '' '' '' \ |
| | | "$SCALE_RS_ATTEMPT"$'\n'"$SCALE_RS_RECOVERED_ON_RETRY" |
| | | scale_rs_cert_case scale-rs-peer-without-attempt '' "$SCALE_RS_ACCEPTOR" '' "$SCALE_RS_ACCEPTOR" '' '' '' \ |
| | | "$SCALE_RS_WARNING"$'\n'"$SCALE_RS_RECOVERY" |
| | | scale_rs_cert_case scale-rs-peer-without-recovery "$SCALE_RS_WARNING" "$SCALE_RS_ACCEPTOR" '' "$SCALE_RS_ACCEPTOR" '' '' '' "$SCALE_RS_FAILURE" |
| | | scale_rs_cert_case scale-rs-peer-late-recovery "$SCALE_RS_WARNING" "$SCALE_RS_ACCEPTOR" '' "$SCALE_RS_ACCEPTOR" '' '' '' \ |
| | | "$SCALE_RS_FAILURE" "$SCALE_RS_RECOVERY" |
| | | scale_rs_cert_case scale-rs-peer-recovery-before-attempt "$SCALE_RS_WARNING" "$SCALE_RS_ACCEPTOR" '' "$SCALE_RS_ACCEPTOR" '' '' '' \ |
| | | "$SCALE_RS_RECOVERY"$'\n'"$SCALE_RS_FAILURE" |
| | | for notice in "${SCALE_RS_RECOVERY/RS(31897)/RS(31898)}" "${SCALE_RS_RECOVERY/cv-r1/cv-r2}" \ |
| | | "${SCALE_RS_RECOVERY/cn=admin data/cn=schema}"; do |
| | | scale_rs_cert_case scale-rs-peer-wrong-recovery "$SCALE_RS_WARNING" "$SCALE_RS_ACCEPTOR" '' "$SCALE_RS_ACCEPTOR" '' '' '' \ |
| | | "$SCALE_RS_FAILURE"$'\n'"$notice" |
| | | done |
| | | for attempt in "${SCALE_RS_ATTEMPT/43210/43211}" "${SCALE_RS_ATTEMPT/172.18.0.7/172.18.0.8}" \ |
| | | "${SCALE_RS_ATTEMPT/172.18.0.2/172.18.0.3}" "${SCALE_RS_ATTEMPT/8989/8990}" \ |
| | | "${SCALE_RS_ATTEMPT/RS(31897)/DS(31897)}"; do |
| | | scale_rs_cert_case scale-rs-peer-wrong-attempt '' "$SCALE_RS_ACCEPTOR" '' "$SCALE_RS_ACCEPTOR" '' '' '' \ |
| | | "$attempt"$'\n'"$SCALE_RS_WARNING"$'\n'"$SCALE_RS_RECOVERY" |
| | | done |
| | | scale_rs_cert_case scale-rs-peer-ambiguous-attempt '' "$SCALE_RS_ACCEPTOR" '' "$SCALE_RS_ACCEPTOR" '' '' '' \ |
| | | "$SCALE_RS_FAILURE"$'\n'"${SCALE_RS_ATTEMPT/cn=admin data/cn=schema}"$'\n'"$SCALE_RS_RECOVERY" |
| | | scale_rs_cert_case scale-rs-peer-attempt-after-window '' "$SCALE_RS_ACCEPTOR" '' "$SCALE_RS_ACCEPTOR" '' '' '' \ |
| | | "$SCALE_RS_WARNING"$'\n'"$SCALE_RS_RECOVERY" "$SCALE_RS_ATTEMPT" |
| | | |
| | | # A combined node can fail as both DS and RS, even with the same ID and domain. |
| | | # Their accepted sockets have different source ports and each needs its own recovery. |
| | | SCALE_COMBINED_RS_WARNING=${SCALE_RS_WARNING/RS(31897)/RS(1)} |
| | | SCALE_COMBINED_RS_RECOVERY=${SCALE_RS_RECOVERY/RS(31897)/RS(1)} |
| | | SCALE_COMBINED_RS_ATTEMPT=$(scale_tls_attempt 01 'RS(1)' 'cn=admin data' 172.18.0.9:43211) |
| | | SCALE_COMBINED_RS_FAILURE="$SCALE_COMBINED_RS_ATTEMPT"$'\n'"$SCALE_COMBINED_RS_WARNING" |
| | | SCALE_COMBINED_RS_ACCEPTOR=${SCALE_PEER/43210/43211} |
| | | scale_cert_case scale-combined-peer-unrecovered-rs "$SCALE_COMBINED_RS_WARNING" "$SCALE_COMBINED_RS_ACCEPTOR" \ |
| | | "$SCALE_ADMIN_FAILURE" "$SCALE_PEER"$'\n'"$SCALE_COMBINED_RS_ACCEPTOR" "$SCALE_ADMIN_CONNECTED" '' combined-peer "$SCALE_COMBINED_RS_FAILURE" |
| | | scale_cert_case scale-combined-peer-unrecovered-ds "$SCALE_ADMIN_WARNING" "$SCALE_PEER" \ |
| | | "$SCALE_ADMIN_FAILURE" "$SCALE_PEER"$'\n'"$SCALE_COMBINED_RS_ACCEPTOR" \ |
| | | '' '' combined-peer "$SCALE_COMBINED_RS_FAILURE"$'\n'"$SCALE_COMBINED_RS_RECOVERY" |
| | | scale_cert_case scale-combined-peer-recovered '' '' "$SCALE_ADMIN_FAILURE" "$SCALE_PEER"$'\n'"$SCALE_COMBINED_RS_ACCEPTOR" \ |
| | | "$SCALE_ADMIN_CONNECTED" '' combined-peer "$SCALE_COMBINED_RS_FAILURE"$'\n'"$SCALE_COMBINED_RS_RECOVERY" |
| | | |
| | | scale_cert_case scale-cert-proof-outside-window "$SCALE_WARNING" "$SCALE_PEER" "$SCALE_DS_FAILURE" "$SCALE_PEER" "$SCALE_CONNECTED" '' move-window |
| | | scale_cert_case scale-cert-proof-in-ordinary-window "$SCALE_WARNING" "$SCALE_PEER" "$SCALE_DS_FAILURE" "$SCALE_PEER" "$SCALE_CONNECTED" '' ordinary-window |
| | | scale_cert_case scale-cert-peer-without-ds-warning '' '' "$SCALE_DS_ATTEMPT" "$SCALE_PEER" "$SCALE_CONNECTED" |
| | | scale_cert_case scale-cert-unrelated-domain "$SCALE_SCHEMA_WARNING" '' "$SCALE_DS_FAILURE"$'\n'"$SCALE_SCHEMA_FAILURE" "$SCALE_PEER" "$SCALE_CONNECTED" |
| | | scale_cert_case scale-cert-all-domains-recovered '' '' "$SCALE_DS_FAILURE"$'\n'"$SCALE_SCHEMA_FAILURE" \ |
| | | "$SCALE_PEER"$'\n'"${SCALE_PEER/43210/43212}" \ |
| | | "$SCALE_CONNECTED"$'\n'"${SCALE_CONNECTED/dc=example,dc=com/cn=schema}" |
| | | for notice in "${SCALE_CONNECTED/172.18.0.2/172.18.0.3}" "${SCALE_CONNECTED/dc=example,dc=com/cn=schema}" \ |
| | | "${SCALE_CONNECTED/DS(1)/DS(2)}" "${SCALE_CONNECTED/msgID=62/msgID=96}"; do |
| | | scale_cert_case scale-cert-wrong-recovery "$SCALE_WARNING" "$SCALE_PEER" "$SCALE_DS_FAILURE" "$SCALE_PEER" "$notice" |
| | | done |
| | | for peer in "${SCALE_PEER/172.18.0.9/172.18.0.8}" "${SCALE_PEER/172.18.0.2/172.18.0.3}"; do |
| | | scale_cert_case scale-cert-wrong-ip '' "$peer" "$SCALE_DS_FAILURE" "$peer" "$SCALE_CONNECTED" |
| | | done |
| | | case_ startup-timeout-exact 0 1 '[ timeout:n0:cv-r1' "$E212" ']' |
| | | case_ startup-timeout-other-ds 1 0 '[ timeout:n1:cv-r1' "$E212" ']' |
| | | case_ startup-timeout-other-rs 1 0 '[ timeout:n0:cv-r0' "$E212" ']' |
| | | case_ startup-timeout-domain 1 0 '[ timeout:n0:cv-r1' "${E212/dc=example,dc=com/cn=schema}" ']' |
| | | case_ startup-timeout-outside 1 0 "$E212" '[ timeout:n0:cv-r1' ']' |
| | | |
| | | # A long DNS-only window must not also hide the normally expected handshake errors. |
| | | case_ dns-only-name 0 1 '[ dns-only dns:cv-r0' "$E51" ']' |
| | | case_ dns-only-handshake 1 0 '[ dns-only dns:cv-r0' "$E178" ']' |
| | | |
| | | # Real long DNS window overlapping no ordinary restart window. |
| | | rm -rf "$OUT/logs" |
| | | printf '%s\n' "$E106" >"$LOG" |
| | | mark_logs |
| | | dns_window_open cv-r0 |
| | | printf '%s\n' "$E51" "$E178" >>"$LOG" |
| | | dns_window_close |
| | | errors=$(replication_errors n0 | grep -c . || true) |
| | | expected=$(grep -c . "$OUT/logs/n0.expected" || true) |
| | | if [ "$errors" = 1 ] && [ "$expected" = 1 ]; then |
| | | passed=$((passed + 1)) |
| | | else |
| | | failed=$((failed + 1)); echo '::error::DNS-only window accepted unrelated handshake or missed DNS error' |
| | | fi |
| | | |
| | | # A log that cannot be read stops window_open, which would otherwise open a window from its first |
| | | # line. In the background: errexit is off in a subshell on the left of ||, and on in a job |
| | | code=0 |
| | |
| | | echo "::error::window_open went on over an errors log that cannot be read" |
| | | fi |
| | | |
| | | # The same failure must be fatal when the caller handles the return code itself: Bash |
| | | # disables errexit throughout a function called from an if/|| condition. |
| | | if window_open 180 >/dev/null 2>&1; then |
| | | failed=$((failed + 1)); echo '::error::conditional window_open accepted an unreadable log' |
| | | else |
| | | passed=$((passed + 1)) |
| | | fi |
| | | printf '0 180\n' >"$OUT/logs/n0.window" |
| | | if window_close >/dev/null 2>&1; then |
| | | failed=$((failed + 1)); echo '::error::conditional window_close accepted an unreadable log' |
| | | else |
| | | passed=$((passed + 1)) |
| | | fi |
| | | |
| | | # A replaced server has a new errors file. Preserve the old file as a prefix so marks and |
| | | # window boundaries cover records on both volumes without accepting errors outside the window. |
| | | rm -rf "$OUT/logs" |
| | | printf '%s\n' "$E178" "$E106" >"$LOG" |
| | | mark_logs |
| | | printf '%s\n' "$E106" >>"$LOG" |
| | | window_open 180 |
| | | printf '%s\n' "$E180" >>"$LOG" |
| | | cp "$LOG" "$OUT/logs/n0.previous" |
| | | printf '%s\n' "$E180" >"$LOG" |
| | | window_close |
| | | printf '%s\n' "$E106" >>"$LOG" |
| | | errors=$(replication_errors n0 | grep -c . || true) |
| | | expected=$(grep -c . "$OUT/logs/n0.expected" || true) |
| | | if [ "$errors" = 2 ] && [ "$expected" = 2 ]; then |
| | | passed=$((passed + 1)) |
| | | else |
| | | failed=$((failed + 1)) |
| | | echo "::error::replacement logs: $errors errors and $expected expected, wanted 2 each" |
| | | fi |
| | | |
| | | # While a scaled-down container is absent, its captured line count keeps later windows |
| | | # aligned; a different unreadable node still fails. |
| | | printf '7\n' >"$OUT/logs/n0.offline" |
| | | rm -f "$LOG" |
| | | if [ "$(errors_lines n0 2>/dev/null || :)" = 7 ]; then |
| | | passed=$((passed + 1)) |
| | | else |
| | | failed=$((failed + 1)); echo '::error::offline node lost its captured line count' |
| | | fi |
| | | rm "$OUT/logs/n0.offline" |
| | | if errors_lines n0 >/dev/null 2>&1; then |
| | | failed=$((failed + 1)); echo '::error::unreadable online log was accepted' |
| | | else |
| | | passed=$((passed + 1)) |
| | | fi |
| | | |
| | | # Overlapping transitions retain separate bounds and exact hostname allowances. |
| | | rm -rf "$OUT/logs" |
| | | printf '%s\n' "$N62" >"$LOG" |
| | | mark_logs |
| | | window_open_key first dns:first |
| | | printf '%s\n' "$E178" >>"$LOG" |
| | | window_open_key second dns:second |
| | | printf '%s\n' "$E180" >>"$LOG" |
| | | window_close_key first |
| | | printf '%s\n' "$E179" >>"$LOG" |
| | | window_close_key second |
| | | printf '%s\n' "$E178" >>"$LOG" |
| | | errors=$(replication_errors n0 | grep -c . || true) |
| | | expected=$(grep -c . "$OUT/logs/n0.expected" || true) |
| | | [ "$errors" = 2 ] && [ "$expected" = 2 ] || { echo "overlapping windows misclassified records: $errors/$expected" >&2; exit 1; } |
| | | [ ! -e "$OUT/logs/n0.window-first" ] && [ ! -e "$OUT/logs/n0.window-second" ] || { echo 'overlapping window left open' >&2; exit 1; } |
| | | |
| | | # DNS allowances stay scoped to their own overlapping node windows. |
| | | rm -rf "$OUT/logs" |
| | | printf '%s\n' "$N62" >"$LOG" |
| | | mark_logs |
| | | E51R1=${E51//cv-r0/cv-r1} |
| | | window_open_key first dns:cv-r0 |
| | | printf '%s\n' "$E51" >>"$LOG" |
| | | window_open_key second dns:cv-r1 |
| | | printf '%s\n' "$E51R1" >>"$LOG" |
| | | window_close_key first |
| | | printf '%s\n' "$E51" "$E51R1" >>"$LOG" |
| | | window_close_key second |
| | | printf '%s\n' "$E51R1" >>"$LOG" |
| | | errors=$(replication_errors n0 | grep -c . || true) |
| | | expected=$(grep -c . "$OUT/logs/n0.expected" || true) |
| | | [ "$errors" = 2 ] && [ "$expected" = 3 ] || { echo "overlapping DNS windows misclassified records: $errors/$expected" >&2; exit 1; } |
| | | |
| | | D180=${E180/cv-r0/172.18.0.8} |
| | | case_ scoped-failover 0 1 '[ disconnect:n0:172.18.0.8' "$D180" ']' |
| | | case_ failover-outside-window 2 1 "$D180" '[ disconnect:n0:172.18.0.8' "$D180" ']' "$D180" |
| | | case_ failover-wrong-node 1 0 '[ disconnect:n1:172.18.0.8' "$D180" ']' |
| | | case_ failover-wrong-peer 1 0 '[ disconnect:n0:172.18.0.9' "$D180" ']' |
| | | case_ failover-wrong-domain 1 0 '[ disconnect:n0:172.18.0.8' "${D180/dc=example,dc=com/cn=schema}" ']' |
| | | case_ failover-wrong-id 1 0 '[ disconnect:n0:172.18.0.8' "${D180/msgID=180 /msgID=1800 }" ']' |
| | | |
| | | echo "replication_errors: $passed cases passed, $failed failed" |
| | | [ "$failed" -eq 0 ] |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d) |
| | | trap 'rm -rf "$OUT"' EXIT |
| | | mkdir -p "$OUT/load" |
| | | if [ ! -f "$HERE/rolling-load.sh" ]; then |
| | | echo 'rolling load support is missing' >&2 |
| | | exit 1 |
| | | fi |
| | | . "$HERE/rolling-load.sh" |
| | | |
| | | # Only a segment started after scale-out and checked successfully proves that the |
| | | # corresponding replica continued to take writes after the topology changed. |
| | | for scenario in before after failed; do |
| | | ( |
| | | OUT="$OUT/post-$scenario"; mkdir -p "$OUT/load" |
| | | unset ROLLING_END ROLLING_END_MS |
| | | [ "$scenario" != after ] || touch "$OUT/load/post-start" |
| | | [ "$scenario" != failed ] || touch "$OUT/load/post-start" |
| | | start_clients() { [ "$scenario" != before ] || touch "$OUT/load/post-start"; touch "$OUT/load/stop"; } |
| | | docker() { case $1 in wait|rm) : ;; logs) echo csv ;; inspect) echo '0 false' ;; exec) : ;; *) return 1 ;; esac; } |
| | | check_client() { [ "$scenario" != failed ]; } |
| | | if rolling_worker d0; then [ "$scenario" != failed ]; else [ "$scenario" = failed ]; fi |
| | | if [ "$scenario" = after ]; then |
| | | [ -e "$OUT/load/d0.post-verified" ] || { echo 'post-scale segment was not recorded' >&2; exit 1; } |
| | | else |
| | | [ ! -e "$OUT/load/d0.post-verified" ] || { echo 'pre-scale or failed segment counted as post-scale' >&2; exit 1; } |
| | | fi |
| | | ) |
| | | done |
| | | ( |
| | | OUT="$OUT/post-completion"; mkdir -p "$OUT/load"; DS_NODES='d0 d1' |
| | | touch "$OUT/load/d0.post-verified" |
| | | if rolling_post_segments_complete; then echo 'missing post-scale writer accepted' >&2; exit 1; fi |
| | | touch "$OUT/load/d1.post-verified" |
| | | rolling_post_segments_complete || { echo 'verified post-scale writers rejected' >&2; exit 1; } |
| | | touch "$OUT/load/deadline" |
| | | if rolling_post_segments_complete; then echo 'post-scale completion after deadline accepted' >&2; exit 1; fi |
| | | rm "$OUT/load/deadline" |
| | | touch "$OUT/load/d0.done" |
| | | if rolling_post_segments_complete; then echo 'stopped post-scale worker accepted' >&2; exit 1; fi |
| | | ) |
| | | # The load ends after every post-scale segment, without waiting for the hard limit. |
| | | ( |
| | | OUT="$OUT/post-lifecycle"; mkdir -p "$OUT/load"; DS_NODES='d0 d1' |
| | | DURATION=60 DISTURB_AT=0 STAT_INTERVAL=0 |
| | | fail() { echo "$*" >&2; return 1; } |
| | | wait_until() { local end=$((SECONDS + $1)); shift 2; until "$@"; do [ "$SECONDS" -lt "$end" ] || return 1; command sleep 0.01; done; } |
| | | rolling_worker() { |
| | | while [ ! -e "$OUT/load/post-start" ]; do command sleep 0.01; done |
| | | touch "$OUT/load/$1.post-verified" |
| | | while [ ! -e "$OUT/load/stop" ]; do command sleep 0.01; done |
| | | } |
| | | disturb() { :; } |
| | | rolling_run_load |
| | | [ ! -e "$OUT/load/deadline" ] || { echo 'successful load waited for its deadline' >&2; exit 1; } |
| | | [ -e "$OUT/load/d0.post-verified" ] && [ -e "$OUT/load/d1.post-verified" ] || exit 1 |
| | | ) |
| | | # A worker which exits before its post-scale segment aborts the run. |
| | | if ( |
| | | OUT="$OUT/post-stopped"; mkdir -p "$OUT/load"; DS_NODES=d0 |
| | | DURATION=60 DISTURB_AT=0 STAT_INTERVAL=0 |
| | | fail() { return 1; } |
| | | wait_until() { local end=$((SECONDS + $1)); shift 2; until "$@"; do [ "$SECONDS" -lt "$end" ] || return 1; command sleep 0.01; done; } |
| | | rolling_worker() { :; } |
| | | disturb() { command sleep 0.1; } |
| | | rolling_run_load |
| | | ) >/dev/null 2>&1; then |
| | | echo 'a stopped worker passed the post-scale check' >&2; exit 1 |
| | | fi |
| | | |
| | | # The scale deadline must fit the per-DS index budget with the default segment size. |
| | | ( |
| | | DURATION=2700; unset ROLLING_SEGMENT |
| | | . "$HERE/rolling-load.sh" |
| | | [ "$ROLLING_SEGMENT" -eq 50 ] && rolling_index_budget || { echo '2700-second load exceeds the index budget' >&2; exit 1; } |
| | | ) |
| | | |
| | | # Three shards permit 50-second segments for a one-hour load. |
| | | ( |
| | | DURATION=3600; unset ROLLING_SEGMENT |
| | | . "$HERE/rolling-load.sh" |
| | | [ "$ROLLING_SEGMENT" -eq 50 ] && rolling_index_budget || { echo 'one-hour load exceeds the index budget' >&2; exit 1; } |
| | | ROLLING_SEGMENT=20; . "$HERE/rolling-load.sh" |
| | | [ "$ROLLING_SEGMENT" -eq 20 ] || { echo 'explicit segment override changed' >&2; exit 1; } |
| | | if rolling_index_budget; then echo 'unsafe one-hour index budget accepted' >&2; exit 1; fi |
| | | ) |
| | | |
| | | # The sampler runs in a subshell: it must inherit the deadline before it is started. |
| | | ( |
| | | DURATION=60; unset ROLLING_END ROLLING_END_MS SCALE_DEADLINE_ACTIVE |
| | | prepare_rolling_deadline |
| | | ( [ "$SCALE_DEADLINE_ACTIVE" = 1 ] && [ "$ROLLING_END_MS" -gt 0 ] ) || { echo 'sampler cannot inherit deadline' >&2; exit 1; } |
| | | ) |
| | | |
| | | # Docker reports the process exit in nanoseconds: a client ending beyond the wall-clock |
| | | # deadline is an error even when its own --maxDuration was within it. |
| | | finished_before_deadline '1970-01-01T00:00:10.000000000Z' 10000 || exit 1 |
| | | if finished_before_deadline '1970-01-01T00:00:10.000000001Z' 10000; then |
| | | echo 'late client was accepted' >&2; exit 1 |
| | | fi |
| | | if finished_before_deadline invalid 10000; then |
| | | echo 'invalid client finish time was accepted' >&2; exit 1 |
| | | fi |
| | | |
| | | # A segment has two clients; a pause may stop the node only once both have ended. The |
| | | # other node must continue to write while this node is paused. |
| | | start_clients() { printf 'start %s %s\n' "$1" "$2" >>"$OUT/events"; } |
| | | docker() { |
| | | case $1 in |
| | | wait) sleep 0.1 ;; |
| | | logs) echo 'csv' ;; |
| | | inspect) echo '0 false' ;; |
| | | rm) : ;; |
| | | *) return 1 ;; |
| | | esac |
| | | } |
| | | check_client() { printf 'checked %s\n' "$1" >>"$OUT/events"; } |
| | | fail() { echo "$*" >&2; return 1; } |
| | | wait_until() { |
| | | local deadline=$((SECONDS + $1)); shift 2 |
| | | until "$@"; do [ "$SECONDS" -lt "$deadline" ] || return 1; sleep 0.1; done |
| | | } |
| | | ROLLING_SEGMENT=1 STAT_INTERVAL=0 |
| | | rolling_worker d0 & a=$! |
| | | rolling_worker d1 & b=$! |
| | | sleep 0.2 |
| | | rolling_pause d0 |
| | | before=$(grep -c '^start d1 ' "$OUT/events") |
| | | sleep 0.4 |
| | | after=$(grep -c '^start d1 ' "$OUT/events") |
| | | [ "$after" -gt "$before" ] || { echo 'other node stopped writing' >&2; exit 1; } |
| | | count=$(grep -c '^start d0 ' "$OUT/events") |
| | | sleep 0.3 |
| | | [ "$(grep -c '^start d0 ' "$OUT/events")" -eq "$count" ] || { echo 'paused node started another segment' >&2; exit 1; } |
| | | rolling_resume d0 |
| | | resumed() { [ "$(grep -c '^start d0 ' "$OUT/events")" -gt "$count" ]; } |
| | | wait_until 3 'node resumes' resumed || { echo 'node did not resume' >&2; exit 1; } |
| | | touch "$OUT/load/stop" |
| | | wait "$a" |
| | | wait "$b" |
| | | [ "$(grep -c '^checked ' "$OUT/events")" -eq "$((2 * $(grep -c '^start ' "$OUT/events")))" ] || { echo 'not all clients checked' >&2; exit 1; } |
| | | # A failed worker must wake a pause immediately instead of consuming the disturbance timeout. |
| | | ( |
| | | mkdir -p "$OUT/failed-pause/load"; OUT="$OUT/failed-pause"; DISTURB_TIMEOUT=1; unset ROLLING_END |
| | | touch "$OUT/load/d0.failed" |
| | | start=$SECONDS |
| | | if rolling_pause d0 2>"$OUT/error"; then echo 'failed worker accepted as parked' >&2; exit 1; fi |
| | | grep -F "worker d0 failed" "$OUT/error" >/dev/null || { echo 'pause did not report the worker failure' >&2; exit 1; } |
| | | ) |
| | | # Even if the first client failed, collect and check the second before exiting. |
| | | ( |
| | | mkdir -p "$OUT/failed-pair/load"; OUT="$OUT/failed-pair"; unset ROLLING_END ROLLING_END_MS |
| | | start_clients() { :; } |
| | | docker() { case $1 in wait|rm) : ;; logs) echo csv ;; inspect) echo '0 false' ;; exec) echo 'LDAP result=53 fixture' ;; *) return 1 ;; esac; } |
| | | check_client() { |
| | | echo "$1" >>"$OUT/checked" |
| | | if [ "$1" = load-add-d0 ]; then |
| | | [ -e "$OUT/load/d0.failed" ] || { echo 'worker failure not signalled before collecting pair' >&2; return 1; } |
| | | return 0 |
| | | fi |
| | | return 1 |
| | | } |
| | | if rolling_worker d0; then echo 'client failure was accepted' >&2; exit 1; fi |
| | | grep -Fx load-add-d0 "$OUT/checked" >/dev/null || { echo 'paired client was not checked' >&2; exit 1; } |
| | | [ -f "$OUT/load/load-add-d0.csv" ] || { echo 'paired client output was not collected' >&2; exit 1; } |
| | | [ -e "$OUT/load/d0.failed" ] || { echo 'worker failure was not signalled' >&2; exit 1; } |
| | | grep -F 'LDAP result=53 fixture' "$OUT/load/d0.recent-errors.log" >/dev/null || { echo 'directory server errors were not collected' >&2; exit 1; } |
| | | ) |
| | | # A checkpoint writer must have two running load clients, not just a stale marker. |
| | | ( |
| | | mkdir -p "$OUT/active/load"; OUT="$OUT/active" |
| | | docker() { [ "$1" = inspect ] || return 1; [ "$4" != "${STOPPED_CLIENT:-}" ] && echo true || echo false; } |
| | | if rolling_clients_running d0; then echo 'missing load clients were accepted' >&2; exit 1; fi |
| | | printf 'load-mod-d0 load-add-d0\n' >"$OUT/load/d0.active" |
| | | rolling_clients_running d0 || { echo 'running load clients rejected' >&2; exit 1; } |
| | | STOPPED_CLIENT=load-add-d0 |
| | | if rolling_clients_running d0; then echo 'stopped load client was accepted' >&2; exit 1; fi |
| | | ) |
| | | # Scale load must produce a meaningful fraction of both requested rates. |
| | | ( |
| | | . "$HERE/load.sh" |
| | | mkdir -p "$OUT/min-rate/load"; OUT="$OUT/min-rate" |
| | | DISTURBANCE=scale-kept LOAD_MOD_RATE=100 LOAD_ADD_RATE=20 STAT_INTERVAL=10 |
| | | echo '0 false' >"$OUT/load/load-mod-d0.exit"; echo 30 >"$OUT/load/load-mod-d0.seconds" |
| | | printf 'Time (seconds),Recent throughput (ops/second),Errors/second\n10,1,0\n20,1,0\n30,1,0\n' >"$OUT/load/load-mod-d0.csv" |
| | | if check_client load-mod-d0 >/dev/null 2>&1; then echo 'almost idle scale writer accepted' >&2; exit 1; fi |
| | | sed 's/,1,0$/,10,0/' "$OUT/load/load-mod-d0.csv" >"$OUT/rate.csv" |
| | | cp "$OUT/rate.csv" "$OUT/load/load-mod-d0.csv" |
| | | check_client load-mod-d0 >/dev/null || { echo 'minimum scale rate rejected' >&2; exit 1; } |
| | | ) |
| | | # A final 18 ms statistics row has its real duration, not the weight of a 10 s interval. |
| | | ( |
| | | . "$HERE/load.sh" |
| | | mkdir -p "$OUT/weighted-rate/load"; OUT="$OUT/weighted-rate" |
| | | DISTURBANCE=scale-rs-empty LOAD_MOD_RATE=100 LOAD_ADD_RATE=20 STAT_INTERVAL=10 |
| | | echo '0 false' >"$OUT/load/load-add-d3.exit"; echo 50 >"$OUT/load/load-add-d3.seconds" |
| | | cat >"$OUT/load/load-add-d3.csv" <<'CSV' |
| | | Time (seconds),Recent throughput (ops/second),Errors/second |
| | | 10.002,1.1,0 |
| | | 20.001,2.2,0 |
| | | 30.001,2.7,0 |
| | | 40.001,2.4,0 |
| | | 50.001,2.6,0 |
| | | 50.019,0.0,0 |
| | | CSV |
| | | check_client load-add-d3 >/dev/null || { echo 'short final interval reduced the true average' >&2; exit 1; } |
| | | sed 's/50.019,0.0,0/50.019,0.0,1/' "$OUT/load/load-add-d3.csv" >"$OUT/with-error.csv" |
| | | cp "$OUT/with-error.csv" "$OUT/load/load-add-d3.csv" |
| | | if check_client load-add-d3 >/dev/null 2>&1; then echo 'an error in the short interval was ignored' >&2; exit 1; fi |
| | | sed 's/50.019,0.0,1/50.001,0.0,0/' "$OUT/with-error.csv" >"$OUT/load/load-add-d3.csv" |
| | | check_client load-add-d3 >/dev/null || { echo 'zero-length final interval was rejected' >&2; exit 1; } |
| | | sed 's/50.019,0.0,1/49.999,0.0,0/' "$OUT/with-error.csv" >"$OUT/load/load-add-d3.csv" |
| | | if check_client load-add-d3 >/dev/null 2>&1; then echo 'a decreasing interval time was accepted' >&2; exit 1; fi |
| | | cat >"$OUT/load/load-add-d3.csv" <<'CSV' |
| | | Time (seconds),Recent throughput (ops/second),Errors/second |
| | | 10,1.0,0 |
| | | 20,1.0,0 |
| | | 30,1.0,0 |
| | | 40,1.0,0 |
| | | 50,1.0,0 |
| | | 50.018,100.0,0 |
| | | CSV |
| | | if check_client load-add-d3 >/dev/null 2>&1; then echo 'short final spike hid a low average' >&2; exit 1; fi |
| | | ) |
| | | # The last client must leave time for JVM startup and teardown before the deadline. |
| | | ( |
| | | mkdir -p "$OUT/final/load"; OUT="$OUT/final"; ROLLING_END=$((SECONDS + 80)); unset ROLLING_END_MS |
| | | ROLLING_SEGMENT=120; STAT_INTERVAL=10 |
| | | start_clients() { echo "$3" >"$OUT/length"; touch "$OUT/load/stop"; } |
| | | rolling_worker d0 |
| | | [ "$(cat "$OUT/length")" -le 40 ] || { echo 'last segment left less than 40 seconds for startup and teardown' >&2; exit 1; } |
| | | ) |
| | | # Pausing a node cannot wait beyond the overall load deadline. |
| | | ( |
| | | ROLLING_END=$((SECONDS + 3)); DISTURB_TIMEOUT=900 |
| | | wait_until() { [ "$1" -le 3 ] && [ "$1" -gt 0 ]; } |
| | | rolling_pause deadline-node || { echo 'pause exceeded the load deadline' >&2; exit 1; } |
| | | ) |
| | | # Forty-second segments must preserve indexed searches for every per-DS AddRate shard. |
| | | ( |
| | | . "$HERE/load.sh" |
| | | OUT="$OUT/shards"; mkdir -p "$OUT/load" |
| | | BASE_DN=dc=example,dc=com SAMPLE_DATA=100 LOAD_MOD_RATE=10 LOAD_ADD_RATE=1 ROOT_PASSWORD=x |
| | | DISTURBANCE=scale-rs-kept |
| | | start_client() { printf '%s\n' "$*" >>"$OUT/commands"; } |
| | | start_clients d0 1 40 |
| | | start_clients d0 2 40 |
| | | start_clients d0 3 40 |
| | | start_clients d0 4 40 |
| | | start_clients d1 2 40 |
| | | grep -E '^load-add-d0 addrate .* --noPurge ' "$OUT/commands" >/dev/null || { echo 'scale addrate still purges at the end of each segment' >&2; exit 1; } |
| | | grep -Fx 'sn: AddRate-d0-1' "$OUT/load/addrate-d0.template" >/dev/null || exit 1 |
| | | grep -Fx 'sn: AddRate-d0-2' "$OUT/load/addrate-d0-2.template" >/dev/null || exit 1 |
| | | grep -Fx 'sn: AddRate-d0-3' "$OUT/load/addrate-d0-3.template" >/dev/null || exit 1 |
| | | grep -Fx 'sn: AddRate-d0-1' "$OUT/load/addrate-d0-4.template" >/dev/null || exit 1 |
| | | grep -Fx 'sn: AddRate-d1-2' "$OUT/load/addrate-d1-2.template" >/dev/null || exit 1 |
| | | DS_NODES='d0 d1 d2 d3'; . "$HERE/assert-converged.sh" |
| | | for n in $DS_NODES; do for shard in 1 2 3; do case " $INDEXED_FILTERS " in *" (sn=AddRate-$n-$shard) "*) : ;; *) echo "index shard $n-$shard is not checked" >&2; exit 1 ;; esac; done; done |
| | | ROLLING_SEGMENT=40 DURATION=900 |
| | | rolling_index_budget || { echo 'safe per-DS segment budget rejected' >&2; exit 1; } |
| | | ROLLING_SEGMENT=20 DURATION=3600 |
| | | if rolling_index_budget; then echo 'unsafe per-DS index budget accepted' >&2; exit 1; fi |
| | | DISTURBANCE=restart-ds |
| | | start_clients d2 1 40 |
| | | grep -Fx 'sn: AddRate' "$OUT/load/addrate-d2.template" >/dev/null || { echo 'ordinary AddRate surname changed' >&2; exit 1; } |
| | | if grep -E '^load-add-d2 addrate .* --noPurge ' "$OUT/commands" >/dev/null; then echo 'ordinary AddRate purge changed' >&2; exit 1; fi |
| | | . "$HERE/assert-converged.sh" |
| | | [ "$INDEXED_FILTERS" = '(sn=AddRate) (sn=Diverged)' ] || { echo 'ordinary index filters changed' >&2; exit 1; } |
| | | ) |
| | | # Too many segments leave enough AddRate entries to exceed the sn index limit. |
| | | if (mkdir -p "$OUT/index-limit/load"; OUT="$OUT/index-limit"; DS_NODES='d0 d1 d2 d3' |
| | | ROLLING_SEGMENT=20; DURATION=3600; DISTURB_AT=1; STAT_INTERVAL=0 |
| | | rolling_worker() { :; }; disturb() { :; }; sleep() { :; } |
| | | rolling_run_load) >/dev/null 2>&1; then |
| | | echo 'rolling load accepted enough retained entries to exceed the sn index limit' >&2; exit 1 |
| | | fi |
| | | # A worker cannot launch new clients after the watchdog has set the deadline marker. |
| | | ( |
| | | . "$HERE/load.sh" |
| | | OUT="$OUT/deadline"; mkdir -p "$OUT/load"; touch "$OUT/load/deadline" |
| | | BASE_DN=dc=example,dc=com SAMPLE_DATA=100 LOAD_MOD_RATE=10 LOAD_ADD_RATE=1 ROOT_PASSWORD=x |
| | | start_client() { echo launched >>"$OUT/launched"; } |
| | | if start_clients d0 1 60; then echo 'clients launched after deadline' >&2; exit 1; fi |
| | | [ ! -e "$OUT/launched" ] || { echo 'deadline allowed a client launch' >&2; exit 1; } |
| | | ) |
| | | # A late Docker launch must not start work after the cutoff even if the host watchdog |
| | | # scanned before the container was created: the container enforces the deadline itself. |
| | | ( |
| | | . "$HERE/load.sh" |
| | | OUT="$OUT/client-wrapper"; mkdir -p "$OUT/load" |
| | | NETWORK=fixture IMAGE=fixture CLIENT_JAVA_ARGS=-Xmx128m ROLLING_END_MS=10000 |
| | | docker() { printf '%s\n' "$*" >"$OUT/command"; } |
| | | start_client load-test modrate --hostname example |
| | | grep -F -- '--entrypoint /bin/sh' "$OUT/command" >/dev/null || { echo 'missing in-container deadline guard' >&2; exit 1; } |
| | | grep -F '/usr/bin/timeout' "$OUT/command" >/dev/null || { echo 'missing in-container cutoff' >&2; exit 1; } |
| | | ) |
| | | # Drive the real watchdog with events instead of racing a one-second wall clock. |
| | | # It may fire only once the worker has published both active clients and the |
| | | # disturbance has released it. A separate bound prevents a broken test hanging. |
| | | test_deadline_sleep() { |
| | | local limit=$((SECONDS + 10)) |
| | | [ "$1" -gt 0 ] && [ "$1" -le 60 ] || return 1 |
| | | while [ ! -s "$OUT/load/d0.active" ] || [ ! -e "$OUT/release-watchdog" ]; do |
| | | [ "$SECONDS" -lt "$limit" ] || return 1 |
| | | command sleep 0.01 |
| | | done |
| | | } |
| | | # A disturbance that outlasts the load must fail and both clients must be killed. |
| | | if (mkdir -p "$OUT/slow/load"; OUT="$OUT/slow"; DS_NODES=d0; DURATION=60; DISTURB_AT=0 |
| | | sleep() { test_deadline_sleep "$@"; } |
| | | rolling_worker() { |
| | | echo 'load-mod-d0 load-add-d0' >"$OUT/load/d0.active" |
| | | while [ ! -e "$OUT/load/stop" ]; do command sleep 0.01; done |
| | | } |
| | | docker() { |
| | | case $1 in inspect) echo true ;; kill) echo "$2" >>"$OUT/killed" ;; *) return 1 ;; esac |
| | | } |
| | | disturb() { |
| | | local limit=$((SECONDS + 10)) |
| | | touch "$OUT/release-watchdog" |
| | | while [ ! -f "$OUT/killed" ] || [ "$(wc -l <"$OUT/killed")" -lt 2 ]; do |
| | | [ "$SECONDS" -lt "$limit" ] || return 1 |
| | | command sleep 0.01 |
| | | done |
| | | SECONDS=$ROLLING_END |
| | | } |
| | | rolling_run_load) 2>"$OUT/slow-error"; then |
| | | echo 'disturbance outlasted the load but passed' >&2; exit 1 |
| | | fi |
| | | [ -e "$OUT/slow/load/stop" ] || { echo 'workers were not stopped after a slow disturbance' >&2; exit 1; } |
| | | [ "$(wc -l <"$OUT/slow/killed")" -eq 2 ] || { echo 'active clients were not stopped at deadline' >&2; exit 1; } |
| | | # An early scenario failure must keep the watchdog alive until a blocked worker exits. |
| | | if (mkdir -p "$OUT/early/load"; OUT="$OUT/early"; DS_NODES=d0; DURATION=60; DISTURB_AT=0 |
| | | sleep() { test_deadline_sleep "$@"; } |
| | | rolling_worker() { |
| | | local limit=$((SECONDS + 10)) |
| | | echo 'load-mod-d0 load-add-d0' >"$OUT/load/d0.active" |
| | | while [ ! -e "$OUT/killed" ]; do |
| | | [ "$SECONDS" -lt "$limit" ] || return 1 |
| | | command sleep 0.01 |
| | | done |
| | | } |
| | | docker() { case $1 in inspect) echo true ;; kill) touch "$OUT/killed" ;; *) return 1 ;; esac; } |
| | | disturb() { touch "$OUT/release-watchdog"; return 1; } |
| | | rolling_run_load) 2>"$OUT/early-error"; then |
| | | echo 'early disturbance failure was accepted' >&2; exit 1 |
| | | fi |
| | | [ -e "$OUT/early/killed" ] || { echo 'watchdog stopped before its worker' >&2; exit 1; } |
| | | # A worker failure also aborts a pending checkpoint, without waiting for its timeout. |
| | | ( |
| | | . "$HERE/lib.sh" |
| | | mkdir -p "$OUT/failed-checkpoint/load"; OUT="$OUT/failed-checkpoint"; SCALE_DEADLINE_ACTIVE=1 |
| | | touch "$OUT/load/d0.failed" |
| | | if wait_until 2 'checkpoint' false >"$OUT/result" 2>&1; then echo 'failed worker accepted during checkpoint' >&2; exit 1; fi |
| | | grep -F 'load worker failed' "$OUT/result" >/dev/null || { echo 'checkpoint hid worker failure' >&2; exit 1; } |
| | | if wait_until 2 'ready checkpoint' true >"$OUT/result" 2>&1; then echo 'ready checkpoint hid failed worker' >&2; exit 1; fi |
| | | ) |
| | | # A Docker error must not look like a completed bootstrap. |
| | | ( |
| | | . "$HERE/lib.sh" |
| | | docker() { return "$DOCKER_RESULT"; } |
| | | DOCKER_RESULT=124 |
| | | if bootstrap_ended example; then echo 'docker timeout accepted as a completed join' >&2; exit 1; fi |
| | | DOCKER_RESULT=1 |
| | | if bootstrap_ended example; then echo 'running join accepted as complete' >&2; exit 1; fi |
| | | DOCKER_RESULT=0 |
| | | bootstrap_ended example || { echo 'completed join rejected' >&2; exit 1; } |
| | | ) |
| | | echo 'rolling load pause, resume and deadline passed' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d) |
| | | trap 'rm -rf "$OUT"' EXIT |
| | | |
| | | # Exercise the actual roll, pause/resume, bounded wait and bootstrap-marker predicate. |
| | | # Only Docker transport and unrelated checkpoint/probe collection are replaced. |
| | | run_case() ( |
| | | local shape=$1 scenario=$2 pending=${3:-} node rc=0 writer=d2 |
| | | OUT="$OUT/$shape-$scenario${pending:+-$pending}" |
| | | mkdir -p "$OUT/load" "$OUT/logs" "$OUT/markers" |
| | | TOPOLOGY=rs534 DISTURBANCE=scale-rs-kept |
| | | . "$HERE/lib.sh" |
| | | . "$HERE/rolling-load.sh" |
| | | DS_NODES='d0 d1 d2 d3' RS_ONLY='r0 r1 r2' RS_NODES=$RS_ONLY |
| | | ALL_NODES="$DS_NODES $RS_NODES" PEERS=d0,d1,d2,d3,r0,r1,r2 SCALE_VOLUME=kept |
| | | . "$HERE/disturb-scale.sh" |
| | | ROLLING_END=$((SECONDS + 20)) DISTURB_TIMEOUT=8 SCALE_DEADLINE_ACTIVE=1 |
| | | ROLLING_END_MS=$((($(date +%s) + 20) * 1000)) |
| | | local group='r0 d0 d1' |
| | | if [ "$shape" = single ]; then group=d0; writer=d1; fi |
| | | for node in $group; do |
| | | mkdir -p "$OUT/markers/$node" |
| | | case $node in d*) touch "$OUT/load/$node.parked" ;; esac |
| | | done |
| | | printf 'load-mod-%s load-add-%s\n' "$writer" "$writer" >"$OUT/load/$writer.active" |
| | | scale_checkpoint_wait() { :; } |
| | | scale_probe_batch() { [ "$1" = "$writer" ]; } |
| | | scale_capture_bootstrap() { :; } |
| | | window_open_key() { :; } |
| | | start_server() { |
| | | local node=$1 |
| | | touch "$OUT/markers/$node/started" |
| | | if [ -n "$pending" ] && [ "$node" != "$pending" ]; then touch "$OUT/markers/$node/finished"; fi |
| | | case $scenario in |
| | | failed) |
| | | touch "$OUT/markers/$node/finished" |
| | | [ "$node" != "${pending:-d0}" ] || touch "$OUT/markers/$node/failed" |
| | | ;; |
| | | esac |
| | | } |
| | | docker() { |
| | | local node |
| | | case $1 in |
| | | stop|rm) : ;; |
| | | inspect) |
| | | case ${*: -1} in load-*) echo true ;; *) echo 172.18.0.8 ;; esac |
| | | ;; |
| | | logs) |
| | | [ -f "$OUT/markers/${*: -1}/started" ] || return 1 |
| | | echo '[t] category=CORE severity=NOTICE msgID=135 msg=The Directory Server has started successfully' |
| | | ;; |
| | | exec) |
| | | node=$2; shift 2 |
| | | printf '%s\n' "$node" >>"$OUT/marker-reads" |
| | | if [ "$scenario" = transport ] && [ ! -f "$OUT/markers/$node/transport-retried" ]; then |
| | | touch "$OUT/markers/$node/transport-retried" |
| | | return 125 |
| | | fi |
| | | BOOTSTRAP_FAILED="$OUT/markers/$node/failed" BOOTSTRAP_FINISHED="$OUT/markers/$node/finished" "$@" |
| | | ;; |
| | | *) echo "unexpected Docker call: $*" >&2; return 1 ;; |
| | | esac |
| | | } |
| | | sleep() { |
| | | local node |
| | | SECONDS=$((SECONDS + $1)) |
| | | # A measured segment must not start on either restarted DS until the whole group |
| | | # has finished joining. The untouched writer remains available throughout the wait. |
| | | for node in $group; do |
| | | case $node in |
| | | d*) [ -f "$OUT/load/$node.pause" ] || { echo "resumed $node while the group was joining" >&2; return 200; } ;; |
| | | esac |
| | | done |
| | | rolling_clients_running "$writer" || { echo 'surviving load writer was paused' >&2; return 200; } |
| | | printf '%s\n' "$writer" >>"$OUT/surviving-writer" |
| | | case $scenario in |
| | | complete|transport) |
| | | # Complete just one member per tick so an early per-node resume is observable. |
| | | for node in $group; do |
| | | [ ! -f "$OUT/markers/$node/finished" ] || continue |
| | | touch "$OUT/markers/$node/finished" |
| | | break |
| | | done |
| | | ;; |
| | | worker) touch "$OUT/load/$writer.failed" ;; |
| | | deadline) SECONDS=$ROLLING_END ;; |
| | | late-completion) |
| | | for node in $group; do touch "$OUT/markers/$node/finished"; done |
| | | SECONDS=$ROLLING_END |
| | | ;; |
| | | incomplete) : ;; |
| | | *) echo "unexpected sleep for $scenario" >&2; return 200 ;; |
| | | esac |
| | | } |
| | | if [ "$shape" = pair ]; then |
| | | scale_roll_pair d0 d1 "$SHORT_PEERS" r0 >"$OUT/result" 2>&1 || rc=$? |
| | | else |
| | | scale_roll d0 "$SHORT_PEERS" >"$OUT/result" 2>&1 || rc=$? |
| | | fi |
| | | case $scenario in |
| | | complete|transport) |
| | | [ "$rc" -eq 0 ] || { cat "$OUT/result" >&2; exit 1; } |
| | | [ -s "$OUT/surviving-writer" ] || { echo 'load resumed without waiting for bootstrap' >&2; exit 1; } |
| | | for node in $group; do |
| | | [ -f "$OUT/markers/$node/finished" ] || { echo "bootstrap of $node did not complete before resume" >&2; exit 1; } |
| | | case $node in d*) [ ! -f "$OUT/load/$node.pause" ] || { echo "$node remained paused" >&2; exit 1; } ;; esac |
| | | done |
| | | ;; |
| | | *) |
| | | [ "$rc" -ne 0 ] || { echo "$shape accepted $scenario bootstrap" >&2; exit 1; } |
| | | for node in $group; do |
| | | case $node in d*) [ -f "$OUT/load/$node.pause" ] || { echo "$shape resumed after $scenario bootstrap" >&2; exit 1; } ;; esac |
| | | done |
| | | case $scenario in |
| | | failed) grep -F 'terminal failure' "$OUT/result" >/dev/null ;; |
| | | incomplete) grep -F 'timed out waiting' "$OUT/result" >/dev/null ;; |
| | | worker) grep -F 'load worker failed' "$OUT/result" >/dev/null ;; |
| | | deadline|late-completion) [ "$SECONDS" -ge "$ROLLING_END" ] ;; |
| | | esac |
| | | ;; |
| | | esac |
| | | [ ! -f "$OUT/load/$writer.pause" ] || { echo 'surviving writer was left paused' >&2; exit 1; } |
| | | ) |
| | | |
| | | for shape in pair single; do |
| | | for scenario in complete transport failed incomplete worker deadline late-completion; do |
| | | run_case "$shape" "$scenario" |
| | | done |
| | | done |
| | | # Each member independently blocks the group: completion of the other two cannot |
| | | # authorize resuming its writers, and each terminal bootstrap failure aborts the roll. |
| | | for node in r0 d0 d1; do |
| | | run_case pair complete "$node" |
| | | run_case pair failed "$node" |
| | | done |
| | | echo 'rolling bootstrap gates preserve surviving writers, positive completion, failures and deadlines' |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # |
| | | # 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. |
| | | |
| | | import importlib.util |
| | | import io |
| | | from pathlib import Path |
| | | import sys |
| | | import subprocess |
| | | import tarfile |
| | | import tempfile |
| | | import unittest |
| | | |
| | | sys.dont_write_bytecode = True |
| | | path = Path(__file__).with_name('scale-coverage.py') |
| | | if not path.exists(): |
| | | raise SystemExit('scale changelog coverage is missing') |
| | | spec = importlib.util.spec_from_file_location('scale_coverage', path) |
| | | coverage = importlib.util.module_from_spec(spec) |
| | | spec.loader.exec_module(coverage) |
| | | |
| | | |
| | | class CoverageTest(unittest.TestCase): |
| | | def test_requires_both_boundary_records_and_all_intervening_sequences(self): |
| | | first = (10, 1000) |
| | | last = (50010, 2000) |
| | | records = [(seq, 1000 if seq == 10 else 2000 if seq == 50010 else 1500, 'modify') |
| | | for seq in range(10, 50011)] |
| | | self.assertTrue(coverage.complete(records, first, last)) |
| | | self.assertFalse(coverage.complete(records[1:], first, last)) |
| | | self.assertFalse(coverage.complete(records[:-1], first, last)) |
| | | self.assertFalse(coverage.complete(records[:100] + records[101:], first, last)) |
| | | self.assertFalse(coverage.complete(records, (10, 999), last)) |
| | | |
| | | def test_streamed_changelog_checks_the_exact_fill(self): |
| | | def make_archive(omitted=None): |
| | | stream = bytearray() |
| | | for seq in range(10, 50011): |
| | | if seq == omitted: |
| | | continue |
| | | timestamp = 1000 if seq == 10 else 2000 if seq == 50010 else 1500 |
| | | csn = '%016x%04x%08x' % (timestamp, 1, seq) |
| | | message = b'\x16\x00' + csn.encode('ascii') |
| | | stream.extend(len(message).to_bytes(4, 'big') + message) |
| | | blocks = bytearray(stream[:256]) |
| | | for pos in range(256, len(stream), 252): |
| | | blocks.extend(b'\0' * 4 + stream[pos:pos + 252]) |
| | | output = io.BytesIO() |
| | | with tarfile.open(fileobj=output, mode='w') as tar: |
| | | for name, data in [('changelogDb/domains.state', b'1:dc=example,dc=com\n'), |
| | | ('changelogDb/1.dom/1.server/head.log', bytes(blocks))]: |
| | | entry = tarfile.TarInfo(name) |
| | | entry.size = len(data) |
| | | tar.addfile(entry, io.BytesIO(data)) |
| | | return output.getvalue() |
| | | |
| | | with tempfile.TemporaryDirectory() as tmp: |
| | | root = Path(tmp) |
| | | first = root / 'first.ldif' |
| | | last = root / 'last.ldif' |
| | | first.write_text('dn: cn=fill\ndescription: scale-1\nds-sync-hist: ' |
| | | 'description:00000000000003e800010000000a:repl:scale-1\n') |
| | | last.write_text('dn: cn=fill\ndescription: scale-50001\nds-sync-hist: ' |
| | | 'description:00000000000007d000010000c35a:repl:scale-50001\n') |
| | | command = [sys.executable, str(path), 'dc=example,dc=com', str(first), str(last)] |
| | | for omitted, expected in [(None, 0), (10, 1), (100, 1), (50010, 1)]: |
| | | result = subprocess.run(command, input=make_archive(omitted), capture_output=True, timeout=30) |
| | | self.assertEqual(result.returncode, expected, result.stderr.decode()) |
| | | |
| | | def test_rejects_too_short_or_reversed_interval(self): |
| | | with self.assertRaises(ValueError): |
| | | coverage.complete([], (10, 1000), (100, 2000)) |
| | | with self.assertRaises(ValueError): |
| | | coverage.complete([], (50010, 1000), (10, 2000)) |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | unittest.main() |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # |
| | | # 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. |
| | | |
| | | from pathlib import Path |
| | | import subprocess |
| | | import sys |
| | | import time |
| | | import tempfile |
| | | import unittest |
| | | |
| | | PROGRAM = Path(__file__).with_name('scale-deadline.py') |
| | | |
| | | |
| | | class DeadlineTest(unittest.TestCase): |
| | | def test_completes_or_is_stopped_at_the_deadline(self): |
| | | if not PROGRAM.exists(): |
| | | self.fail('deadline wrapper is missing') |
| | | deadline = str(int((time.time() + 2) * 1000)) |
| | | self.assertEqual(subprocess.run([sys.executable, str(PROGRAM), deadline, sys.executable, '-c', 'pass']).returncode, 0) |
| | | deadline = str(int((time.time() + 0.5) * 1000)) |
| | | result = subprocess.run([sys.executable, str(PROGRAM), deadline, sys.executable, '-c', 'import time; time.sleep(10)'], timeout=3) |
| | | self.assertEqual(result.returncode, 124) |
| | | |
| | | def test_termination_stops_the_child_process_group(self): |
| | | with tempfile.TemporaryDirectory() as tmp: |
| | | marker = str(Path(tmp) / 'survived') |
| | | deadline = str(int((time.time() + 10) * 1000)) |
| | | program = 'import pathlib,sys,time; time.sleep(0.8); pathlib.Path(sys.argv[1]).touch()' |
| | | process = subprocess.Popen([sys.executable, str(PROGRAM), deadline, sys.executable, '-c', program, marker]) |
| | | time.sleep(0.2) |
| | | process.terminate() |
| | | process.wait(timeout=3) |
| | | time.sleep(1) |
| | | self.assertFalse(Path(marker).exists(), 'child survived wrapper termination') |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | unittest.main() |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # |
| | | # 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. |
| | | |
| | | import base64 |
| | | import contextlib |
| | | import importlib.util |
| | | import io |
| | | from pathlib import Path |
| | | import sys |
| | | import tempfile |
| | | import unittest |
| | | |
| | | sys.dont_write_bytecode = True |
| | | path = Path(__file__).with_name('scale-fence.py') |
| | | if not path.exists(): |
| | | raise SystemExit('scale fence is missing') |
| | | spec = importlib.util.spec_from_file_location('scale_fence', path) |
| | | fence = importlib.util.module_from_spec(spec) |
| | | spec.loader.exec_module(fence) |
| | | |
| | | |
| | | class FenceTest(unittest.TestCase): |
| | | def test_waits_for_the_writers_own_position(self): |
| | | with tempfile.TemporaryDirectory() as tmp: |
| | | root = Path(tmp) |
| | | writer = root / 'writer.ldif' |
| | | current = root / 'rs.ldif' |
| | | writer.write_text('dn: cn=writer\ndescription: scale-50001\n' |
| | | 'ds-sync-hist: description:000000000000000100010000000a:repl:scale-50001\n' |
| | | 'server-id: 1\nserver-state: 0000000000000001000100000009 date\n') |
| | | current.write_text('dn: cn=changelog\ndomain-name: dc=example,dc=com\n' |
| | | 'replicationServer-database: 1\nlast-change: 0000000000000001000100000009\n') |
| | | with contextlib.redirect_stdout(io.StringIO()): |
| | | self.assertEqual(fence.main(['fence', 'dc=example,dc=com', str(writer), str(current)]), 1) |
| | | current.write_text(current.read_text().replace('00000009', '0000000b')) |
| | | output = io.StringIO() |
| | | with contextlib.redirect_stdout(output): |
| | | self.assertEqual(fence.main(['fence', 'dc=example,dc=com', str(writer), str(current)]), 0) |
| | | self.assertIn('needs 000000000000000100010000000a, RS has 000000000000000100010000000b', output.getvalue()) |
| | | writer.write_text('dn: cn=writer\ndescription: scale-50001\n' |
| | | 'ds-sync-hist: description:000000000000000100010000000a:repl:wrong-value\n') |
| | | with contextlib.redirect_stderr(io.StringIO()): |
| | | self.assertEqual(fence.main(['fence', 'dc=example,dc=com', str(writer), str(current)]), 2) |
| | | |
| | | def test_folded_base64_state_and_duplicate_writer_fail_closed(self): |
| | | with tempfile.TemporaryDirectory() as tmp: |
| | | writer = Path(tmp) / 'writer.ldif' |
| | | value = base64.b64encode(b'description:000000000000000100010000000a:repl:scale-50001').decode() |
| | | writer.write_text('dn: cn=writer\ndescription: scale-50001\nds-sync-hist:: ' + value[:16] + '\n ' + value[16:] + '\n') |
| | | self.assertEqual(fence.writer_position(writer), (1, '000000000000000100010000000a')) |
| | | with writer.open('a') as output: |
| | | output.write('ds-sync-hist: description:000000000000000100010000000a:add:scale-50001\n') |
| | | with self.assertRaises(ValueError): |
| | | fence.writer_position(writer) |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | unittest.main() |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d) |
| | | trap 'rm -rf "$OUT"' EXIT |
| | | . "$HERE/collect.sh" |
| | | MONITOR_DOMAIN=monitor |
| | | admin_search() { [ "${BROKEN:-0}" = 0 ] || return 1; printf '%s\n' "$RESPONSE"; } |
| | | fail() { echo "$*" >&2; return 1; } |
| | | printf '1 d0\n2 d1\n' >"$OUT/server-ids.txt" |
| | | RESPONSE='dn: cn=Directory server DS(2) test' |
| | | record_rejoined_id d1 || exit 1 |
| | | [ "${REJOINED_WITH_NEW_ID:-}" = 0 ] || { echo 'same ID reported as new' >&2; exit 1; } |
| | | [ "$(wc -l <"$OUT/server-ids.txt")" -eq 2 ] || { echo 'same id appended twice' >&2; exit 1; } |
| | | RESPONSE='dn: cn=Directory server DS(3) test' |
| | | record_rejoined_id d1 || exit 1 |
| | | grep -Fx '3 d1' "$OUT/server-ids.txt" >/dev/null |
| | | [ "$REJOINED_WITH_NEW_ID" = 1 ] || { echo 'new ID was not reported' >&2; exit 1; } |
| | | record_rejoined_id d1 || exit 1 |
| | | [ "$REJOINED_WITH_NEW_ID" = 0 ] || { echo 'already recorded ID reported as new' >&2; exit 1; } |
| | | RESPONSE='dn: cn=Directory server DS(1) test' |
| | | if record_rejoined_id d1; then echo 'duplicate id of another node accepted' >&2; exit 1; fi |
| | | RESPONSE='' |
| | | if record_rejoined_id d1; then echo 'missing id accepted' >&2; exit 1; fi |
| | | RESPONSE=$'dn: cn=Directory server DS(4) test\ndn: cn=Directory server DS(5) test' |
| | | if record_rejoined_id d1; then echo 'multiple ids accepted' >&2; exit 1; fi |
| | | BROKEN=1 |
| | | if record_rejoined_id d1; then echo 'failed monitor search accepted' >&2; exit 1; fi |
| | | echo 'scale replica identities passed' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # |
| | | # 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. |
| | | |
| | | set -eu -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | . "$HERE/scale-membership.sh" |
| | | ROOT_PASSWORD=secret ROLLING_END_MS=2000000000000 |
| | | TEST_MAPPING=127.0.0.1:14444 |
| | | docker() { [ "$1" = port ] || return 1; printf '%s\n' "$TEST_MAPPING"; } |
| | | python3() { printf '%s\n' "$*" >"$OUT/args"; cat >"$OUT/password"; return "${RESULT:-0}"; } |
| | | peer_removed survivor cv-r1 || { echo 'absent membership rejected' >&2; exit 1; } |
| | | [ "$(cat "$OUT/password")" = secret ] || { echo 'password did not arrive on stdin' >&2; exit 1; } |
| | | grep -F '14444 2000000000000 membership cv-r1 absent' "$OUT/args" >/dev/null || { echo 'membership request has wrong arguments' >&2; exit 1; } |
| | | peer_present survivor cv-r1 || exit 1 |
| | | grep -F 'membership cv-r1 present' "$OUT/args" >/dev/null || exit 1 |
| | | RESULT=1 |
| | | if peer_present survivor cv-r1; then echo 'failed membership search passed' >&2; exit 1; fi |
| | | rm -f "$OUT/args"; TEST_MAPPING=0.0.0.0:14444 |
| | | if peer_removed survivor cv-r1; then echo 'non-loopback admin port accepted' >&2; exit 1; fi |
| | | [ ! -e "$OUT/args" ] || { echo 'query sent to non-loopback port' >&2; exit 1; } |
| | | echo 'scale membership wiring passed' |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | # |
| | | # 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. |
| | | |
| | | import importlib.util |
| | | from pathlib import Path |
| | | import socket |
| | | import subprocess |
| | | import sys |
| | | import threading |
| | | import time |
| | | import unittest |
| | | |
| | | sys.dont_write_bytecode = True |
| | | spec = importlib.util.spec_from_file_location('monitor', Path(__file__).with_name('scale-monitor.py')) |
| | | monitor = importlib.util.module_from_spec(spec) |
| | | spec.loader.exec_module(monitor) |
| | | |
| | | |
| | | def wrap(tag, value): |
| | | return monitor.tlv(tag, value) |
| | | |
| | | |
| | | def msg(message_id, tag, value): |
| | | return wrap(0x30, wrap(0x02, bytes([message_id])) + wrap(tag, value)) |
| | | |
| | | |
| | | def ldap_result(code): |
| | | return wrap(0x0a, bytes([code])) + wrap(0x04, b'') + wrap(0x04, b'') |
| | | |
| | | |
| | | def entry(): |
| | | attrs = [] |
| | | for name, value in [(b'domain-name', b'dc=example,dc=com'), |
| | | (b'replicationServer-database', b'42'), |
| | | (b'last-change', b'000001a1a1e836e4002a00000001')]: |
| | | attrs.append(wrap(0x30, wrap(0x04, name) + wrap(0x31, wrap(0x04, value)))) |
| | | return wrap(0x04, b'cn=example,cn=monitor') + wrap(0x30, b''.join(attrs)) |
| | | |
| | | |
| | | def member_entry(dn, attributes): |
| | | attrs = [wrap(0x30, wrap(0x04, name) + wrap(0x31, b''.join(wrap(0x04, v) for v in values))) |
| | | for name, values in attributes.items()] |
| | | return wrap(0x04, dn) + wrap(0x30, b''.join(attrs)) |
| | | |
| | | |
| | | class MonitorTest(unittest.TestCase): |
| | | def exchange(self, responses, timeout=3): |
| | | client, server = socket.socketpair() |
| | | errors = [] |
| | | def respond(): |
| | | try: |
| | | monitor.read_frame(server, time.monotonic() + 3) |
| | | server.sendall(responses[0]) |
| | | if len(responses) > 1: |
| | | 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]) |
| | | except (BrokenPipeError, ConnectionResetError): |
| | | pass |
| | | except Exception as error: |
| | | errors.append(error) |
| | | finally: |
| | | server.close() |
| | | thread = threading.Thread(target=respond) |
| | | thread.start() |
| | | try: |
| | | return monitor.search(client, b'password', time.monotonic() + timeout) |
| | | finally: |
| | | client.close() |
| | | thread.join(4) |
| | | if errors: |
| | | raise errors[0] |
| | | |
| | | def test_search_collects_fragmented_entries_after_success(self): |
| | | text = self.exchange([msg(1, 0x61, ldap_result(0)), msg(2, 0x64, entry()), |
| | | msg(2, 0x65, ldap_result(0))]) |
| | | self.assertIn('replicationServer-database:: NDI=', text) |
| | | self.assertIn('dn:: ', text) |
| | | self.assertTrue(text.endswith('\n\n')) |
| | | |
| | | def test_rejects_bind_failure(self): |
| | | with self.assertRaises(monitor.LdapError): |
| | | self.exchange([msg(1, 0x61, ldap_result(49))]) |
| | | |
| | | def test_rejects_incomplete_search_even_after_entries(self): |
| | | with self.assertRaises(monitor.LdapError): |
| | | self.exchange([msg(1, 0x61, ldap_result(0)), msg(2, 0x64, entry()), |
| | | msg(2, 0x65, ldap_result(3))]) |
| | | |
| | | def test_rejects_wrong_message_id(self): |
| | | with self.assertRaises(monitor.LdapError): |
| | | self.exchange([msg(7, 0x61, ldap_result(0))]) |
| | | |
| | | def test_rejects_invalid_lengths_and_truncated_messages(self): |
| | | for value in (b'\x30\x80', b'\x30\x82\xff\xff', b'\x30\x05\x02'): |
| | | with self.subTest(value=value): |
| | | client, server = socket.socketpair() |
| | | server.sendall(value); server.close() |
| | | try: |
| | | with self.assertRaises((monitor.LdapError, EOFError)): |
| | | monitor.read_frame(client, time.monotonic() + 1) |
| | | finally: |
| | | client.close() |
| | | |
| | | def test_refuses_oversized_snapshot_without_returning_partial_data(self): |
| | | original = monitor.MAX_SNAPSHOT |
| | | monitor.MAX_SNAPSHOT = 10 |
| | | try: |
| | | with self.assertRaises(monitor.LdapError): |
| | | self.exchange([msg(1, 0x61, ldap_result(0)), msg(2, 0x64, entry()), |
| | | msg(2, 0x65, ldap_result(0))]) |
| | | finally: |
| | | monitor.MAX_SNAPSHOT = original |
| | | |
| | | def test_expired_load_deadline_returns_no_snapshot(self): |
| | | result = subprocess.run([sys.executable, str(Path(__file__).with_name('scale-monitor.py')), '1', '1'], |
| | | input=b'password', stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| | | self.assertEqual(result.returncode, 124) |
| | | self.assertEqual(result.stdout, b'') |
| | | self.assertIn(b'timeout=load', result.stderr) |
| | | |
| | | def test_deadline_after_final_response_does_not_return_a_snapshot(self): |
| | | original = monitor.require_success |
| | | calls = [] |
| | | def delayed_result(value): |
| | | calls.append(1) |
| | | original(value) |
| | | if len(calls) == 2: |
| | | time.sleep(0.4) |
| | | monitor.require_success = delayed_result |
| | | try: |
| | | with self.assertRaises(TimeoutError): |
| | | self.exchange([msg(1, 0x61, ldap_result(0)), msg(2, 0x65, ldap_result(0))], timeout=0.3) |
| | | self.assertEqual(len(calls), 2) |
| | | finally: |
| | | monitor.require_success = original |
| | | |
| | | def test_no_bind_is_sent_after_the_deadline(self): |
| | | client, server = socket.socketpair() |
| | | server.settimeout(0.05) |
| | | try: |
| | | with self.assertRaises(TimeoutError): |
| | | monitor.search(client, b'password', time.monotonic() - 1) |
| | | with self.assertRaises(socket.timeout): |
| | | server.recv(1) |
| | | finally: |
| | | client.close(); server.close() |
| | | |
| | | def test_absolute_deadline_interrupts_wait(self): |
| | | client, server = socket.socketpair() |
| | | try: |
| | | with self.assertRaises(TimeoutError): |
| | | monitor.read_frame(client, time.monotonic() + 0.05) |
| | | finally: |
| | | client.close(); server.close() |
| | | |
| | | def membership_exchange(self, registry, config, last_result=0): |
| | | client, server = socket.socketpair() |
| | | requests, errors = [], [] |
| | | def respond(): |
| | | try: |
| | | for message_id, entries in [(1, None), (2, registry), (3, config)]: |
| | | requests.append(monitor.read_frame(server, time.monotonic() + 3)) |
| | | if entries is None: |
| | | server.sendall(msg(1, 0x61, ldap_result(0))) |
| | | else: |
| | | for value in entries: |
| | | server.sendall(msg(message_id, 0x64, value)) |
| | | server.sendall(msg(message_id, 0x65, ldap_result(last_result if message_id == 3 else 0))) |
| | | except (BrokenPipeError, ConnectionResetError): |
| | | pass |
| | | except Exception as error: |
| | | errors.append(error) |
| | | finally: |
| | | server.close() |
| | | thread = threading.Thread(target=respond); thread.start() |
| | | try: |
| | | result = monitor.membership(client, b'password', time.monotonic() + 3, 'cv-r1', 'absent') |
| | | return result, requests |
| | | finally: |
| | | client.close(); thread.join(4) |
| | | if errors: raise errors[0] |
| | | |
| | | def test_membership_uses_one_bind_and_two_complete_searches(self): |
| | | registry = [member_entry(b'cn=d0,cn=Servers,cn=admin data', {b'hostname': [b'cv-d0.example']})] |
| | | config = [member_entry(b'cn=domain,cn=config', {b'ds-cfg-replication-server': [b'cv-r10.example:8989']})] |
| | | result, requests = self.membership_exchange(registry, config) |
| | | self.assertTrue(result) |
| | | self.assertEqual(len(requests), 3) |
| | | self.assertIn(b'cn=Servers,cn=admin data', requests[1]) |
| | | self.assertIn(b'cn=config', requests[2]) |
| | | |
| | | def test_membership_rejects_a_partial_second_search(self): |
| | | registry = [member_entry(b'cn=d0', {b'hostname': [b'cv-d0']})] |
| | | config = [member_entry(b'cn=domain', {})] |
| | | with self.assertRaises(monitor.LdapError): |
| | | self.membership_exchange(registry, config, last_result=3) |
| | | |
| | | def test_membership_semantics_for_all_lists(self): |
| | | good_registry = [{'hostname': ['CV-R1.example']}] |
| | | good_config = [{'ds-cfg-replication-server': ['cv-r1.example:8989']}] |
| | | self.assertTrue(monitor.membership_matches(good_registry, good_config, 'cv-r1', 'present')) |
| | | self.assertFalse(monitor.membership_matches(good_registry, good_config + [{}], 'cv-r1', 'present')) |
| | | self.assertFalse(monitor.membership_matches(good_registry, good_config, 'cv-r1', 'absent')) |
| | | self.assertFalse(monitor.membership_matches([], good_config, 'cv-r1', 'absent')) |
| | | self.assertFalse(monitor.membership_matches([{}], good_config, 'cv-r1', 'absent')) |
| | | self.assertFalse(monitor.membership_matches([{'hostname': ['']}], [{}], 'cv-r1', 'absent')) |
| | | self.assertFalse(monitor.membership_matches(good_registry, [], 'cv-r1', 'present')) |
| | | self.assertTrue(monitor.membership_matches([{'hostname': ['cv-d0']}], [{}], 'cv-r1', 'absent')) |
| | | self.assertFalse(monitor.membership_matches([{'hostname': ['cv-r0']}], good_config, 'cv-r1', 'present')) |
| | | self.assertFalse(monitor.membership_matches(good_registry, [{'ds-cfg-replication-server': ['cv-r0:8989']}], 'cv-r1', 'present')) |
| | | self.assertFalse(monitor.membership_matches([{'hostname': ['cv-d0']}], good_config, 'cv-r1', 'absent')) |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | unittest.main() |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | mkdir -p "$OUT/logs" "$OUT/scale-progress" |
| | | DS_NODES='d0 d1' RS_ONLY='r0 r1 r2' RS_NODES=$RS_ONLY ALL_NODES="$DS_NODES $RS_ONLY" |
| | | TOPOLOGY=rs534 SCALE_VOLUME=kept PEERS=d0,d1,r0,r1,r2 NETWORK=test BASE_DN=dc=example,dc=com |
| | | . "$HERE/disturb-scale.sh" |
| | | printf '23874 d0\n' >"$OUT/server-ids.txt" |
| | | printf '0\n' >"$OUT/logs/d0.mark" |
| | | printf '0 dns:r1\n' >"$OUT/logs/d0.window-up-d0" |
| | | docker() { case ${@: -1} in r0) echo 172.18.0.8 ;; r1) echo 172.18.0.9 ;; r2) echo 172.18.0.10 ;; *) return 1 ;; esac; } |
| | | errors_lines() { if [ -n "${WINDOW_AFTER:-}" ]; then echo "$WINDOW_AFTER"; else wc -l <"$OUT/errors"; fi; } |
| | | since_mark() { cat "$OUT/errors"; } |
| | | bootstrap_ended() { return "${BOOTSTRAP_STATUS:-0}"; } |
| | | E='[t] category=SYNC severity=ERROR msgID=212 msg=Directory server DS(23874) timed out while connecting to replication server r1:8989 for domain "dc=example,dc=com"' |
| | | N='[t] category=SYNC severity=NOTICE msgID=62 msg=Directory server DS(23874) has connected to replication server RS(9861) for domain "dc=example,dc=com" at 172.18.0.9:8989 with generation ID 1' |
| | | S='[t] category=CORE severity=NOTICE msgID=135 msg=The Directory Server has started successfully' |
| | | printf 'other\n%s\n%s\n%s\n' "$E" "$N" "$S" >"$OUT/errors" |
| | | scale_record_reconnected_timeouts d0 r1 up |
| | | grep -Fx '1 2 startup-timeout:d0' "$OUT/logs/d0.windows" >/dev/null || { echo 'confirmed timeout was not scoped to its line' >&2; exit 1; } |
| | | for notice in "${N/172.18.0.9/172.18.0.77}" "${N/DS(23874)/DS(23875)}" "${N/dc=example,dc=com/cn=schema}"; do |
| | | : >"$OUT/logs/d0.windows" |
| | | printf '%s\n%s\n%s\n' "$E" "$notice" "$S" >"$OUT/errors" |
| | | scale_record_reconnected_timeouts d0 r1 up |
| | | [ ! -s "$OUT/logs/d0.windows" ] || { echo 'different reconnection accepted' >&2; exit 1; } |
| | | done |
| | | : >"$OUT/logs/d0.windows" |
| | | printf '%s\n%s\n%s\n' "$N" "$E" "$S" >"$OUT/errors" |
| | | scale_record_reconnected_timeouts d0 r1 up |
| | | [ ! -s "$OUT/logs/d0.windows" ] || { echo 'earlier connection accepted' >&2; exit 1; } |
| | | printf '%s\n%s\n%s\n' "$S" "$E" "$N" >"$OUT/errors" |
| | | scale_record_reconnected_timeouts d0 r1 up |
| | | [ ! -s "$OUT/logs/d0.windows" ] || { echo 'timeout after startup accepted' >&2; exit 1; } |
| | | printf '%s\n%s\n' "$E" "$N" >"$OUT/errors" |
| | | scale_record_reconnected_timeouts d0 r1 up |
| | | [ ! -s "$OUT/logs/d0.windows" ] || { echo 'missing startup marker accepted' >&2; exit 1; } |
| | | echo 'scale startup timeout requires the same later connection' |
| | | printf '0 dns:r1\n' >"$OUT/logs/d0.window-down-r0" |
| | | D='[t] category=SYNC severity=ERROR msgID=180 msg=Directory server DS(23874) encountered an error while receiving changes for domain "dc=example,dc=com" from replication server RS(9860) at 172.18.0.8:8989. The connection will be closed, and this directory server will now try to connect to another replication server' |
| | | : >"$OUT/logs/d0.windows" |
| | | printf '%s\n%s\n%s\n%s\n' "$S" "$D" "$E" "$N" >"$OUT/errors" |
| | | scale_record_roll_failover d0 r0 r1 down 172.18.0.8 |
| | | grep -Fx '1 2 disconnect:d0:172.18.0.8' "$OUT/logs/d0.windows" >/dev/null |
| | | grep -Fx '2 3 timeout:d0:r1' "$OUT/logs/d0.windows" >/dev/null |
| | | for rows in "$S"$'\n'"$E"$'\n'"$N" "$D"$'\n'"$E" "${D/172.18.0.8/172.18.0.7}"$'\n'"$E"$'\n'"$N" "$D"$'\n'"$E"$'\n'"${N/dc=example,dc=com/cn=schema}" "$N"$'\n'"$D"$'\n'"$E"; do |
| | | : >"$OUT/logs/d0.windows" |
| | | printf '%s\n' "$rows" >"$OUT/errors" |
| | | scale_record_roll_failover d0 r0 r1 down 172.18.0.8 |
| | | [ ! -s "$OUT/logs/d0.windows" ] || { echo 'unproven rolling failover accepted' >&2; exit 1; } |
| | | done |
| | | echo 'rolling failover requires the stopped peer and a later connection in the same domain' |
| | | |
| | | # After return, either live RS can receive a surviving writer. The absent third RS |
| | | # is not a candidate during scale-in, even if its address still appears in a log. |
| | | docker() { case ${@: -1} in r1) echo 172.18.0.9 ;; r2) echo 172.18.0.10 ;; *) return 1 ;; esac; } |
| | | printf '0 dns:r0\n' >"$OUT/logs/d0.window-up-r0" |
| | | : >"$OUT/logs/d0.windows" |
| | | printf '%s\n%s\n' "$D" "${N/172.18.0.9/172.18.0.10}" >"$OUT/errors" |
| | | scale_record_roll_failover d0 r0 r1 up 172.18.0.8 |
| | | grep -Fx '0 1 disconnect:d0:172.18.0.8' "$OUT/logs/d0.windows" >/dev/null || { echo 'returned third RS failover rejected' >&2; exit 1; } |
| | | for direction in down up; do |
| | | for address in 172.18.0.8 172.18.0.77 $([ "$direction" != down ] || echo 172.18.0.10); do |
| | | : >"$OUT/logs/d0.windows" |
| | | printf '%s\n%s\n' "$D" "${N/172.18.0.9/$address}" >"$OUT/errors" |
| | | scale_record_roll_failover d0 r0 r1 "$direction" 172.18.0.8 |
| | | [ ! -s "$OUT/logs/d0.windows" ] || { echo 'stopped or unknown RS failover accepted' >&2; exit 1; } |
| | | done |
| | | done |
| | | echo 'returned RS is accepted only after return; stopped and unknown peers remain errors' |
| | | |
| | | # Exercise the recorder and the error filter together. The admin-data domain has |
| | | # its own DS ID, and recovery may choose another currently available RS. |
| | | . "$HERE/assert-converged.sh" |
| | | errors_lines() { if [ -n "${WINDOW_AFTER:-}" ]; then echo "$WINDOW_AFTER"; else wc -l <"$OUT/errors"; fi; } |
| | | since_mark() { cat "$OUT/errors"; } |
| | | docker() { |
| | | case ${@: -1} in |
| | | r0) echo 172.18.0.8 ;; r1) echo 172.18.0.9 ;; r2) echo 172.18.0.10 ;; |
| | | *) return 1 ;; |
| | | esac |
| | | } |
| | | REMOVED=r2 |
| | | A='[t] category=SYNC severity=ERROR msgID=212 msg=Directory server DS(31955) timed out while connecting to replication server r1:8989 for domain "cn=admin data"' |
| | | B='[t] category=SYNC severity=NOTICE msgID=62 msg=Directory server DS(31955) has connected to replication server RS(9860) for domain "cn=admin data" at 172.18.0.8:8989 with generation ID 1' |
| | | check_startup() { # <description> <direction> <expected error count> <records...> |
| | | local description=$1 direction=$2 expected=$3; shift 3 |
| | | : >"$OUT/logs/d0.windows" |
| | | rm -f "$OUT/logs/d0.startup-timeouts" |
| | | printf '%s dns:r1\n' "${WINDOW_BEFORE:-0}" >"$OUT/logs/d0.window-$direction-d0" |
| | | printf '%s\n' "$@" >"$OUT/errors" |
| | | scale_record_reconnected_timeouts d0 r1 "$direction" |
| | | replication_errors d0 >"$OUT/rejected" |
| | | [ "$(wc -l <"$OUT/rejected" | tr -d ' ')" = "$expected" ] \ |
| | | || { echo "startup: $description (expected $expected errors)" >&2; cat "$OUT/rejected" >&2; exit 1; } |
| | | } |
| | | check_startup 'admin domain recovers on another eligible RS' down 0 "$A" "$B" "$S" |
| | | check_startup 'schema domain recovers' down 0 "${A/cn=admin data/cn=schema}" "${B/cn=admin data/cn=schema}" "$S" |
| | | check_startup 'returning RS is available during scale-out' up 0 "$A" "${B/172.18.0.8/172.18.0.10}" "$S" |
| | | check_startup 'removed RS is unavailable during scale-in' down 1 "$A" "${B/172.18.0.8/172.18.0.10}" "$S" |
| | | check_startup 'unknown RS' up 1 "$A" "${B/172.18.0.8/172.18.0.77}" "$S" |
| | | check_startup 'different domain' down 1 "$A" "${B/cn=admin data/cn=schema}" "$S" |
| | | check_startup 'different DS' down 1 "$A" "${B/DS(31955)/DS(31956)}" "$S" |
| | | check_startup 'connection precedes error' down 1 "$B" "$A" "$S" |
| | | check_startup 'connection follows startup before successful bootstrap' down 0 "$A" "$S" "$B" |
| | | check_startup 'unknown timeout peer' down 1 "${A/r1:8989/unknown:8989}" "$S" "$B" |
| | | check_startup 'unknown matching domain' down 1 "${A/cn=admin data/dc=unknown}" "$S" "${B/cn=admin data/dc=unknown}" |
| | | check_startup 'later unrelated restart' down 1 "$A" "$S" "$S" "$B" |
| | | BOOTSTRAP_STATUS=1 check_startup 'bootstrap incomplete' down 1 "$A" "$S" "$B" |
| | | BOOTSTRAP_STATUS=200 check_startup 'bootstrap failed' down 1 "$A" "$S" "$B" |
| | | WINDOW_BEFORE=1 check_startup 'timeout before rolling window' down 1 "$A" "$S" "$B" |
| | | WINDOW_AFTER=2 check_startup 'connection after captured bootstrap bound' down 1 "$A" "$S" "$B" |
| | | check_startup 'startup incomplete' down 1 "$A" "$B" |
| | | check_startup 'timeout outside startup window' down 1 "$S" "$A" "$B" |
| | | check_startup 'unrecovered second domain' down 1 "$A" "${A/cn=admin data/cn=schema}" "$B" "$S" |
| | | check_startup 'only the recorded line is accepted' down 1 "$A" "$B" "$S" "$A" |
| | | check_startup 'original evidence' down 0 "$A" "$B" "$S" |
| | | printf '%s\n%s\n%s\n' "${A/cn=admin data/cn=schema}" "$B" "$S" >"$OUT/errors" |
| | | [ "$(replication_errors d0 | wc -l | tr -d ' ')" = 1 ] || { echo 'changed log accepted with stale evidence' >&2; exit 1; } |
| | | echo 'startup timeouts require exact evidence, matching domain/DS, an eligible RS and completed bootstrap in one bounded rolling startup' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | check() ( |
| | | TOPOLOGY=$1 DISTURBANCE=$2 |
| | | . "$HERE/lib.sh" |
| | | [ "$(echo "$DS_NODES" | wc -w)" -eq 4 ] || exit 1 |
| | | [ "$(echo "$RS_NODES" | wc -w)" -eq "$3" ] || exit 1 |
| | | [ "$(echo "$ALL_NODES" | wc -w)" -eq "$4" ] || exit 1 |
| | | ) |
| | | check rs534 scale-rs-kept 3 7 |
| | | check rs534 scale-rs-empty 3 7 |
| | | check rs534 empty-rs 2 6 |
| | | check rs534 none 2 6 |
| | | check combined scale-kept 4 4 |
| | | check combined scale-empty 4 4 |
| | | # Scale uses a 2700 s load ceiling and reduced rates; other rows and explicit settings retain theirs. |
| | | for disturbance in scale-rs-kept scale-rs-empty scale-kept scale-empty; do |
| | | ( unset DISTURB_AT DURATION LOAD_MOD_RATE LOAD_ADD_RATE; TOPOLOGY=combined DISTURBANCE=$disturbance |
| | | . "$HERE/lib.sh" |
| | | [ "$DURATION" -eq 2700 ] && [ "$DISTURB_AT" -eq 120 ] && [ "$LOAD_MOD_RATE" -eq 100 ] && [ "$LOAD_ADD_RATE" -eq 20 ] ) || exit 1 |
| | | done |
| | | ( unset DISTURB_AT DURATION LOAD_MOD_RATE LOAD_ADD_RATE; TOPOLOGY=rs534 DISTURBANCE=empty-rs |
| | | . "$HERE/lib.sh" |
| | | [ "$DISTURB_AT" -eq 300 ] && [ "$LOAD_MOD_RATE" -eq 423 ] && [ "$LOAD_ADD_RATE" -eq 85 ] ) || exit 1 |
| | | ( TOPOLOGY=combined DISTURBANCE=scale-kept DISTURB_AT=77 DURATION=900 LOAD_MOD_RATE=42 LOAD_ADD_RATE=7 |
| | | . "$HERE/lib.sh" |
| | | [ "$DISTURB_AT" -eq 77 ] && [ "$LOAD_MOD_RATE" -eq 42 ] && [ "$LOAD_ADD_RATE" -eq 7 ] ) || exit 1 |
| | | # Only scale rows publish the admin port, and only on loopback for the native monitor. |
| | | ( |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | . "$HERE/topology-up.sh" |
| | | docker() { printf '%s\n' "$*" >>"$OUT/calls"; } |
| | | NETWORK=test ROOT_PASSWORD=password SERVER_JAVA_ARGS=-Xmx1g IMAGE=test PEERS=d0,d1 |
| | | DISTURBANCE=scale-kept; start_server d0 combined |
| | | grep -F -- '-p 127.0.0.1::4444' "$OUT/calls" >/dev/null || { echo 'scale admin port is not loopback-published' >&2; exit 1; } |
| | | grep -F -- '-e JOIN_TIMING=1' "$OUT/calls" >/dev/null || { echo 'scale bootstrap timing is not enabled' >&2; exit 1; } |
| | | : >"$OUT/calls"; DISTURBANCE=restart-ds; start_server d0 combined |
| | | if grep -F -- '-p 127.0.0.1::4444' "$OUT/calls" >/dev/null; then echo 'ordinary topology published an admin port' >&2; exit 1; fi |
| | | if grep -F -- 'JOIN_TIMING=' "$OUT/calls" >/dev/null; then echo 'ordinary topology enabled bootstrap timing' >&2; exit 1; fi |
| | | ) |
| | | echo 'scale topology cases passed' |
| | |
| | | echo "400000 435000 d1 $how" >"$OUT/disturbances.txt" |
| | | check "$DISTURBANCE completed" "| disturbance | $how of d1 300 s into the load, serving again 35 s later |" |
| | | done |
| | | # The post-load failover must remain visible even if only one RS was checked. |
| | | DISTURBANCE=empty-rs DISTURB_STEPS=1 CONVERGED_IN=10 |
| | | printf 'r0 r1 450\n' >"$OUT/failover.txt" |
| | | summarize failed |
| | | checks=$((checks + 1)) |
| | | if ! grep -Fx '| failover | stopped r0; all directory servers connected to r1 after 450 s |' "$OUT/summary.md" >/dev/null \ |
| | | || ! grep -Fx '| failover | incomplete: 1 of 2 replication servers checked |' "$OUT/summary.md" >/dev/null; then |
| | | echo '::error::partial failover is absent from the summary' |
| | | failed=$((failed + 1)) |
| | | fi |
| | | # The measured backlog belongs in the CI summary, not only the uploaded artifact. |
| | | DISTURBANCE=scale-rs-empty DISTURB_STEPS=1 |
| | | printf '400000 900000 r1 scale-empty\n' >"$OUT/disturbances.txt" |
| | | check 'scale completed' '| disturbance | scale-empty of r1 300 s into the load, completed 500 s later |' |
| | | mkdir -p "$OUT/scale-checkpoint" |
| | | echo '50001 changes while the server was absent' >"$OUT/scale-checkpoint/backlog.txt" |
| | | summarize passed |
| | | checks=$((checks + 1)) |
| | | if ! grep -Fx '| scale backlog | 50001 changes while the server was absent |' "$OUT/summary.md" >/dev/null; then |
| | | echo '::error::scale backlog is absent from the summary'; failed=$((failed + 1)) |
| | | fi |
| | | |
| | | echo "summary: $((checks - failed)) checks passed, $failed failed" |
| | | [ "$failed" -eq 0 ] |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # |
| | | # 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. |
| | | |
| | | # Exercise the real access-log reader against files standing in for the container's logs. |
| | | set -eE -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | . "$HERE/assert-converged.sh" |
| | | BASE_DN=dc=example,dc=com |
| | | OUT=$(mktemp -d) |
| | | trap 'rm -rf "$OUT"' EXIT |
| | | |
| | | docker() { |
| | | [ "$1 $2 $3 $4" = 'exec cv-d1 sh -c' ] || return 1 |
| | | local command=${5//\/opt\/opendj\/data\/logs/$OUT} |
| | | sh -c "$command" |
| | | } |
| | | |
| | | cat >"$OUT/access.20261107161156Z" <<'LOG' |
| | | [07/Nov/2026:15:52:52 +0000] SEARCH REQ conn=70 op=1 msgID=2 base="ou=People,dc=example,dc=com" scope=one filter="(objectClass=inetOrgPerson)" attrs="1.1" |
| | | [07/Nov/2026:15:52:54 +0000] SEARCH RES conn=70 op=1 msgID=2 result=0 nentries=10000 unindexed etime=1994 |
| | | LOG |
| | | cat >"$OUT/access" <<'LOG' |
| | | [07/Nov/2026:16:28:32 +0000] SEARCH REQ conn=70 op=1 msgID=2 base="dc=example,dc=com" scope=sub filter="(sn=AddRate)" attrs="1.1" |
| | | [07/Nov/2026:16:28:32 +0000] SEARCH RES conn=70 op=1 msgID=2 result=0 nentries=0 etime=0 |
| | | [07/Nov/2026:16:28:33 +0000] SEARCH REQ conn=71 op=1 msgID=2 base="dc=example,dc=com" scope=sub filter="(sn=Diverged)" attrs="1.1" |
| | | [07/Nov/2026:16:28:33 +0000] SEARCH RES conn=71 op=1 msgID=2 result=0 nentries=0 etime=0 |
| | | LOG |
| | | out=$(unindexed_searches cv-d1) |
| | | if [ -n "$out" ]; then |
| | | echo "FAIL: unrelated search before restart was paired with a later request: $out" >&2 |
| | | exit 1 |
| | | fi |
| | | |
| | | # A target request and response may straddle rotation. A real unindexed response must |
| | | # still be reported even when the same connection and operation are reused later. |
| | | cat >"$OUT/access.20261107161156Z" <<'LOG' |
| | | [07/Nov/2026:15:52:52 +0000] SEARCH REQ conn=70 op=1 msgID=2 base="dc=example,dc=com" scope=sub filter="(sn=AddRate)" attrs="1.1" |
| | | LOG |
| | | cat >"$OUT/access" <<'LOG' |
| | | [07/Nov/2026:15:52:54 +0000] SEARCH RES conn=70 op=1 msgID=2 result=0 nentries=0 unindexed etime=10 |
| | | [07/Nov/2026:16:28:32 +0000] SEARCH REQ conn=70 op=1 msgID=2 base="dc=example,dc=com" scope=sub filter="(sn=AddRate)" attrs="1.1" |
| | | [07/Nov/2026:16:28:32 +0000] SEARCH RES conn=70 op=1 msgID=2 result=0 nentries=0 etime=0 |
| | | [07/Nov/2026:16:28:33 +0000] SEARCH REQ conn=71 op=1 msgID=2 base="dc=example,dc=com" scope=sub filter="(sn=Diverged)" attrs="1.1" |
| | | [07/Nov/2026:16:28:33 +0000] SEARCH RES conn=71 op=1 msgID=2 result=0 nentries=0 etime=0 |
| | | LOG |
| | | out=$(unindexed_searches cv-d1) |
| | | [ "$out" = '::error::cv-d1 ran (sn=AddRate) without an index' ] || { |
| | | echo "FAIL: missed an unindexed response across rotation: $out" >&2; exit 1; |
| | | } |
| | | |
| | | # An interrupted old request cannot claim an unrelated response after restart. |
| | | cat >"$OUT/access.20261107161156Z" <<'LOG' |
| | | [07/Nov/2026:15:52:52 +0000] SEARCH REQ conn=70 op=1 msgID=2 base="dc=example,dc=com" scope=sub filter="(sn=AddRate)" attrs="1.1" |
| | | LOG |
| | | cat >"$OUT/access" <<'LOG' |
| | | [07/Nov/2026:16:28:32 +0000] SEARCH REQ conn=70 op=1 msgID=2 base="ou=People,dc=example,dc=com" scope=one filter="(objectClass=inetOrgPerson)" attrs="1.1" |
| | | [07/Nov/2026:16:28:32 +0000] SEARCH RES conn=70 op=1 msgID=2 result=0 nentries=10000 unindexed etime=10 |
| | | [07/Nov/2026:16:28:33 +0000] SEARCH REQ conn=71 op=1 msgID=2 base="dc=example,dc=com" scope=sub filter="(sn=Diverged)" attrs="1.1" |
| | | [07/Nov/2026:16:28:33 +0000] SEARCH RES conn=71 op=1 msgID=2 result=0 nentries=0 etime=0 |
| | | LOG |
| | | out=$(unindexed_searches cv-d1) |
| | | [ -z "$out" ] || { echo "FAIL: interrupted request claimed another response: $out" >&2; exit 1; } |
| | | |
| | | # An absent target search must remain an error. |
| | | rm "$OUT/access.20261107161156Z" |
| | | out=$(unindexed_searches cv-d1) |
| | | [ "$out" = '::error::the access log of cv-d1 holds no search of (sn=AddRate)' ] || { |
| | | echo "FAIL: missing target search was accepted: $out" >&2; exit 1; |
| | | } |
| | | |
| | | echo 'unindexed-searches: 4 checks passed' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | . "$HERE/lib.sh" |
| | | sleep() { :; } |
| | | calls=0 |
| | | late_success() { calls=$((calls + 1)); [ "$calls" -ge 3 ]; } |
| | | # A caller may use wait_until in a condition, disabling errexit for the whole function. |
| | | # It must still stop at its deadline, even if the predicate would later succeed. |
| | | if wait_until 0 'a late predicate' late_success >/dev/null; then |
| | | echo 'wait_until accepted a predicate after its deadline' >&2 |
| | | exit 1 |
| | | fi |
| | | [ "$calls" -eq 1 ] || { echo 'wait_until kept trying after timeout' >&2; exit 1; } |
| | | . "$HERE/monitor.sh" |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | DS_NODES=d0 RS_NODES=r0 QUIESCE_TIMEOUT=100 MONITORING_PERIOD=0 |
| | | sample() { |
| | | local count=0 |
| | | [ ! -f "$OUT/count" ] || count=$(cat "$OUT/count") |
| | | count=$((count + 1)); echo "$count" >"$OUT/count" |
| | | if [ "$count" -eq 1 ]; then echo '100 r0 123 42 3'; else echo '101 r0 123 0 0'; fi |
| | | } |
| | | sleep() { SECONDS=$((SECONDS + 5)); } |
| | | wait_converged |
| | | grep -Fx '100 r0 123 42 3' "$OUT/convergence-samples.txt" >/dev/null \ |
| | | || { echo 'missing nonzero convergence sample' >&2; exit 1; } |
| | | grep -Fx '101 r0 123 0 0' "$OUT/convergence-samples.txt" >/dev/null \ |
| | | || { echo 'missing converged sample' >&2; exit 1; } |
| | | echo 'wait deadline passed' |
| | | calls=0 |
| | | incomplete_checkpoint() { calls=$((calls + 1)); [ "$calls" -ge 2 ] || return 2; } |
| | | wait_until 100 'a checkpoint which is not complete yet' incomplete_checkpoint >"$OUT/retryable" \ |
| | | || { echo 'ordinary predicate status 2 aborted a retryable wait' >&2; exit 1; } |
| | | [ "$calls" -eq 2 ] |
| | | # Status 200 is a terminal predicate failure, not a state which more waiting fixes. |
| | | calls=0 |
| | | terminal_failure() { calls=$((calls + 1)); return 200; } |
| | | if wait_until 100 'a failed bootstrap' terminal_failure >"$OUT/terminal"; then |
| | | echo 'terminal bootstrap failure accepted' >&2; exit 1 |
| | | fi |
| | | [ "$calls" -eq 1 ] || { echo 'terminal bootstrap failure retried until timeout' >&2; exit 1; } |
| | | # Run the predicate shell against real marker files; only Docker transport is replaced. |
| | | docker() { |
| | | case $1 in |
| | | inspect) echo healthy; return "${INSPECT_RC:-0}" ;; |
| | | exec) [ "${EXEC_RC:-0}" -eq 0 ] || return "$EXEC_RC"; shift 2; BOOTSTRAP_FAILED="$OUT/bootstrap-failed" BOOTSTRAP_FINISHED="$OUT/bootstrap-finished" "$@" ;; |
| | | *) return 1 ;; |
| | | esac |
| | | } |
| | | # Setup has not launched join.sh yet: absence of a join process is not completion. |
| | | if bootstrap_ended node; then |
| | | echo 'setup before join counted as a completed bootstrap' >&2; exit 1 |
| | | fi |
| | | touch "$OUT/bootstrap-finished" |
| | | bootstrap_ended node || { echo 'successful bootstrap rejected' >&2; exit 1; } |
| | | is_healthy node |
| | | printf 'join:8\n' >"$OUT/bootstrap-failed" |
| | | rc=0; is_healthy node || rc=$? |
| | | [ "$rc" -eq 200 ] || { echo 'failed join counted as healthy' >&2; exit 1; } |
| | | rc=0; bootstrap_ended node || rc=$? |
| | | [ "$rc" -eq 200 ] || { echo 'failed join counted as successfully ended' >&2; exit 1; } |
| | | rm "$OUT/bootstrap-failed" |
| | | for code in 1 2 124 137; do |
| | | if EXEC_RC=$code bootstrap_ended node; then |
| | | echo 'failed Docker marker read counted as a completed bootstrap' >&2; exit 1 |
| | | fi |
| | | if EXEC_RC=$code is_healthy node; then |
| | | echo 'failed Docker marker read counted as healthy' >&2; exit 1 |
| | | fi |
| | | done |
| | | if INSPECT_RC=1 is_healthy node; then |
| | | echo 'failed Docker inspect counted as healthy' >&2; exit 1 |
| | | fi |
| | | echo 'terminal bootstrap failures abort waits immediately' |
| | |
| | | # its REPLICATION_ROLE, as a StatefulSet would start it. |
| | | |
| | | start_server() { # <name> <role> [<docker run option>...] |
| | | local name=$1 role=$2 |
| | | local name=$1 role=$2 java_args=$SERVER_JAVA_ARGS token= |
| | | local -a monitor_port=() timing=() |
| | | shift 2 |
| | | docker volume create "vol-$name" >/dev/null |
| | | docker run -d --network $NETWORK --name "$name" --hostname "$name" \ |
| | | # Scale checkpoints use a lightweight host client; the admin listener remains loopback-only. |
| | | case ${DISTURBANCE:-none} in scale-*) monitor_port=(-p 127.0.0.1::4444); timing=(-e JOIN_TIMING=1) ;; esac |
| | | case ${DISTURBANCE:-none} in |
| | | scale-empty|scale-rs-empty) |
| | | java_args="$java_args -Dorg.opends.server.replication.traceTlsFailures=true" |
| | | ;; |
| | | esac |
| | | if [ "${CSN_TRACE:-0}" = 1 ] && [ "$role" != replication ]; then |
| | | token=$(python3 -c 'import uuid; print(uuid.uuid4().hex)') || return 1 |
| | | java_args="$java_args -Dorg.opends.server.replication.csnTraceDirectory=/opt/opendj/data/csn-trace -Dorg.opends.server.replication.csnTraceToken=$token -Dorg.opends.server.replication.csnTraceTokenFile=/opt/opendj/data/csn-trace-token-$token" |
| | | fi |
| | | docker volume create "vol-$name" >/dev/null || return 1 |
| | | docker run -d --network $NETWORK --name "$name" --hostname "$name" "${monitor_port[@]}" "${timing[@]}" \ |
| | | -v "vol-$name:/opt/opendj/data" \ |
| | | -e ROOT_PASSWORD="$ROOT_PASSWORD" -e ADD_BASE_ENTRY="--addBaseEntry" \ |
| | | -e OPENDJ_JAVA_ARGS="$SERVER_JAVA_ARGS" \ |
| | | -e OPENDJ_JAVA_ARGS="$java_args" \ |
| | | -e OPENDJ_REPLICATION_TYPE=simple -e REPLICATION_ROLE="$role" -e REPLICATION_PEERS="$PEERS" \ |
| | | -e REPLICATION_RETRY_INTERVAL=3 \ |
| | | "$@" "$IMAGE" >/dev/null |
| | | "$@" "$IMAGE" >/dev/null || return 1 |
| | | if [ -n "$token" ]; then |
| | | mkdir -p "$OUT/csn-trace-tokens" || return 1 |
| | | printf '%s\n' "$token" >"$OUT/csn-trace-tokens/$name" || return 1 |
| | | printf '%s %s\n' "$name" "$token" >>"$OUT/csn-trace-expected.txt" || return 1 |
| | | fi |
| | | } |
| | | |
| | | topology_up() { |
| | |
| | | [ -e "$INSTANCE_ROOT/logs/server.starting" ] |
| | | kill -0 "$LIVE_PID" |
| | | grep -Fq 'timed out after 1' "$INSTANCE_ROOT/stderr" |
| | | grep -Fq "server pid $LIVE_PID, status running" "$INSTANCE_ROOT/logs/start-ds.log" |
| | | kill "$LIVE_PID" |
| | | LIVE_PID= |
| | | |
| | |
| | | kill "$LIVE_PID" |
| | | LIVE_PID= |
| | | |
| | | # A later successful start must preserve the earlier failure diagnostics. |
| | | rm "$INSTANCE_ROOT/checked" "$INSTANCE_ROOT/final-check" |
| | | FIXTURE_PROBE_STATUS=98 run_case failed-probe 3 99 0 --timeout 3 |
| | | grep -Fxq 'probe output' "$INSTANCE_ROOT/logs/start-ds.log" |
| | | kill "$LIVE_PID" |
| | | LIVE_PID= |
| | | |
| | | # An unusable diagnostic path must leave the final probe's result intact. |
| | | mkdir -p "$FIXTURES/unwritable-diagnostics instance/logs/start-ds.log" |
| | | run_case unwritable-diagnostics 3 99 1 --timeout 3 |
| | | [ -e "$INSTANCE_ROOT/final-check" ] |
| | | grep -Fxq 'probe output' "$INSTANCE_ROOT/stderr" |
| | | kill "$LIVE_PID" |
| | | LIVE_PID= |
| | | |
| | | cat > "$FIXTURES/bin/start-ds" <<'START' |
| | | #!/bin/sh |
| | | [ ! -e "$INSTANCE_ROOT/logs/server.pid" ] || exit 1 |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | export FIXTURE="$OUT" |
| | | mkdir "$OUT/bin" |
| | | # A stopped daemon target supports logs/cp, but every exec fails. Include a secret |
| | | # file and a symlink next to the CLI log: neither belongs in the exported evidence. |
| | | python3 - "$OUT/tool-logs.tar" <<'PYTHON' |
| | | import io, sys, tarfile |
| | | with tarfile.open(sys.argv[1], "w") as archive: |
| | | for name, data in [("opendj-replication-one.log", b"replication failed\n"), |
| | | ("password", b"must not escape\n")]: |
| | | entry = tarfile.TarInfo(name); entry.size = len(data) |
| | | archive.addfile(entry, io.BytesIO(data)) |
| | | link = tarfile.TarInfo("opendj-setup-link.log") |
| | | link.type = tarfile.SYMTYPE; link.linkname = "/etc/passwd" |
| | | archive.addfile(link) |
| | | PYTHON |
| | | cat >"$OUT/bin/docker" <<'DOCKER' |
| | | #!/usr/bin/env bash |
| | | case "$1" in |
| | | inspect) printf '%s\n' '{"Status":"exited","ExitCode":137,"OOMKilled":true}' ;; |
| | | logs) echo 'server stopped' ;; |
| | | exec) echo 'container is not running' >&2; exit 1 ;; |
| | | cp) |
| | | case "$2" in |
| | | */data/logs) mkdir -p "$3/logs"; echo 'fatal server failure' >"$3/logs/errors" ;; |
| | | */data/tmp/.) cat "$FIXTURE/tool-logs.tar" ;; |
| | | */.bootstrap-failed) echo 'join:8' >"$3" ;; |
| | | *) exit 1 ;; |
| | | esac ;; |
| | | *) exit 1 ;; |
| | | esac |
| | | DOCKER |
| | | chmod +x "$OUT/bin/docker" |
| | | PATH="$OUT/bin:$PATH" bash "$HERE/docker-startup-diagnostics.sh" node "$OUT/evidence" >"$OUT/output" |
| | | grep -F '"OOMKilled":true' "$OUT/evidence/state.json" >/dev/null |
| | | grep -Fx 'fatal server failure' "$OUT/evidence/logs/errors" >/dev/null |
| | | grep -Fx 'replication failed' "$OUT/evidence/tool-logs/opendj-replication-one.log" >/dev/null |
| | | grep -Fx 'join:8' "$OUT/evidence/bootstrap-failed" >/dev/null |
| | | [ "$(ls "$OUT/evidence/tool-logs" | wc -l | tr -d ' ')" = 1 ] |
| | | grep -Fx 'fatal server failure' "$OUT/output" >/dev/null |
| | | # Diagnostics and cleanup failing must not replace the test's original exit code. |
| | | # Extract the real trap registration and execute it with failing collector commands. |
| | | sed -n '/^trap .* ERR$/p' "$HERE/docker-test-replication.sh" >"$OUT/trap.sh" |
| | | rc=0 |
| | | bash -c 'set -eE; dump_logs() { return 9; }; timings() { return 10; }; cleanup() { return 11; }; . "$1"; (exit 42)' bash "$OUT/trap.sh" >"$OUT/trap-output" 2>&1 || rc=$? |
| | | [ "$rc" -eq 42 ] || { echo "diagnostics replaced failure 42 with $rc" >&2; exit 1; } |
| | | echo 'Stopped-container diagnostics retain exit state and logs, exclude secrets and preserve the original error' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | # Execute the fixture's actual wait functions with only Docker and time replaced. |
| | | for function in fail wait_until container_running wait_running; do |
| | | sed -n "/^$function() {/,/^}/p" "$HERE/docker-test-replication.sh" |
| | | done >"$OUT/functions.sh" |
| | | . "$OUT/functions.sh" |
| | | sleep() { SECONDS=$((SECONDS + 2)); } |
| | | docker() { |
| | | [ "$1" = inspect ] || return 1 |
| | | [ "${INSPECT_RC:-0}" -eq 0 ] || return "$INSPECT_RC" |
| | | case "$*" in *'.State.Status'*) echo "$STATE";; *) echo '{"Status":"exited","ExitCode":137,"OOMKilled":true}';; esac |
| | | } |
| | | calls=0 |
| | | pending() { calls=$((calls + 1)); return 1; } |
| | | for STATE in exited dead; do |
| | | calls=0 |
| | | if wait_running node 300 'node rejoins' pending >"$OUT/result" 2>&1; then |
| | | echo 'stopped container accepted' >&2; exit 1 |
| | | fi |
| | | [ "$calls" -eq 0 ] || { echo 'stopped container was retried' >&2; exit 1; } |
| | | grep -F 'ExitCode' "$OUT/result" >/dev/null || { cat "$OUT/result"; echo 'exit state not reported' >&2; exit 1; } |
| | | done |
| | | # A ready old log cannot make an exited container pass either. |
| | | if wait_running node 300 'old log matches' true >"$OUT/result" 2>&1; then |
| | | echo 'old log hid a stopped container' >&2; exit 1 |
| | | fi |
| | | STATE=running |
| | | wait_running node 300 'running node is ready' true |
| | | # Missing/created/restarting containers and Docker transport errors are retryable, |
| | | # but must never let a successful predicate through before running is verified. |
| | | for STATE in created restarting paused; do |
| | | if wait_running node 0 'node starts' true >"$OUT/result" 2>&1; then exit 1; fi |
| | | grep -F 'timed out' "$OUT/result" >/dev/null |
| | | done |
| | | if INSPECT_RC=1 wait_running node 0 'Docker recovers' true >"$OUT/result" 2>&1; then exit 1; fi |
| | | grep -F 'timed out' "$OUT/result" >/dev/null |
| | | # Deliberately stopped peers are outside this wait's explicit target set. |
| | | STATE=exited |
| | | wait_until 0 'a check which needs no running container' true |
| | | calls=0 |
| | | if wait_until 0 'a false predicate' pending >"$OUT/result" 2>&1; then exit 1; fi |
| | | [ "$calls" -eq 1 ] || { echo 'wait continued past its deadline' >&2; exit 1; } |
| | | echo 'Docker fixture waits stop on exited targets, retry transport failures and respect their deadline' |
| | | |
| | | # Exercise the real restart assertions with the log from before and after a restart. |
| | | for function in logs_have_since assert_no_replication_reset; do |
| | | sed -n "/^$function() {/,/^}/p" "$HERE/docker-test-replication.sh" |
| | | done | sed 's/^assert_no_replication_reset()/check_reset_in_logs()/' >"$OUT/log-functions.sh" |
| | | sed -n '/^phase "roles: restarts"$/,/^roles_hold$/p' "$HERE/docker-test-replication.sh" >"$OUT/separate.sh" |
| | | sed -n '/^phase "restart of a member"$/,/^phase "seed without a domain"$/p' \ |
| | | "$HERE/docker-test-replication.sh" >"$OUT/combined.sh" |
| | | run_restart_case() { |
| | | bash -e -o pipefail -c ' |
| | | OUT=$1 |
| | | topology=$2 |
| | | log_status=$3 |
| | | . "$OUT/functions.sh" |
| | | . "$OUT/log-functions.sh" |
| | | phase() { :; } |
| | | is_healthy() { :; } |
| | | wait_healthy() { :; } |
| | | roles_hold() { :; } |
| | | recorded_role_of() { echo combined; } |
| | | wait_has() { :; } |
| | | add_ou() { :; } |
| | | assert_no_replication_reset() { |
| | | if [ "$topology/$1" = combined/dj-0 ]; then |
| | | [ -f "$OUT/dj-0-member" ] || fail "checked dj-0 for a reset before it rejoined" |
| | | touch "$OUT/dj-0-reset-checked" |
| | | elif [ "$log_status" -ne 0 ]; then |
| | | touch "$OUT/reset-check-$1" |
| | | fi |
| | | check_reset_in_logs "$@" |
| | | } |
| | | sleep() { |
| | | SECONDS=$((SECONDS + 2)) |
| | | if [ "$topology" = combined ] && [ ! -f "$OUT/dj-0-member" ]; then |
| | | echo "join: already a member of the replication topology" >>"$OUT/dj-0.log" |
| | | touch "$OUT/dj-0-member" |
| | | fi |
| | | } |
| | | docker() { |
| | | case "$1" in |
| | | exec|restart|start|stop) : ;; |
| | | logs) |
| | | if [ "$topology" = combined ]; then |
| | | cat "$OUT/$2.log" |
| | | elif [ "$log_status" -ne 0 ] && [ -f "$OUT/reset-check-$2" ]; then |
| | | echo "Docker transport error" >&2 |
| | | return "$log_status" |
| | | else |
| | | cat "$OUT/container.log" |
| | | fi |
| | | ;; |
| | | *) return 1 ;; |
| | | esac |
| | | } |
| | | . "$OUT/$topology.sh" |
| | | ' restart "$OUT" "$1" "${2:-0}" |
| | | } |
| | | cat >"$OUT/container.log" <<'LOG' |
| | | Starting OpenDJ |
| | | join: taking its replication configuration down to enable it anew |
| | | Starting OpenDJ |
| | | join: already a member of the replication topology |
| | | LOG |
| | | run_restart_case separate |
| | | rc=0 |
| | | run_restart_case separate 1 >"$OUT/result" 2>&1 || rc=$? |
| | | [ "$rc" -ne 0 ] || { echo 'restart accepted an unreadable Docker log' >&2; exit 1; } |
| | | grep -F 'could not read the current startup log for dj-r0' "$OUT/result" >/dev/null |
| | | |
| | | echo 'join: taking its replication configuration down to enable it anew' >>"$OUT/container.log" |
| | | rc=0 |
| | | run_restart_case separate >"$OUT/result" 2>&1 || rc=$? |
| | | [ "$rc" -ne 0 ] |
| | | grep -F 'dj-r0 reset its replication on a plain restart' "$OUT/result" >/dev/null |
| | | echo 'Docker fixture reports resets and unreadable logs from the current start' |
| | | |
| | | cat >"$OUT/dj-0.log" <<'LOG' |
| | | Starting OpenDJ |
| | | join: already a member of the replication topology |
| | | Starting OpenDJ |
| | | LOG |
| | | sed '$d' "$OUT/container.log" >"$OUT/dj-1.log" |
| | | run_restart_case combined |
| | | [ -f "$OUT/dj-0-reset-checked" ] || { echo "combined restart did not check dj-0 for a reset" >&2; exit 1; } |
| | | echo 'Docker fixture waits for current membership of the restarted combined seed' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | export FIXTURE_ROOT="$OUT/instance" |
| | | mkdir -p "$FIXTURE_ROOT/bin" "$FIXTURE_ROOT/bootstrap" "$FIXTURE_ROOT/data/config" "$FIXTURE_ROOT/template/config" |
| | | python3 - "$HERE/../../opendj-packages/opendj-docker/run.sh" "$OUT/run.sh" "$FIXTURE_ROOT" <<'PYTHON' |
| | | from pathlib import Path |
| | | import sys |
| | | Path(sys.argv[2]).write_text(Path(sys.argv[1]).read_text().replace('/opt/opendj', sys.argv[3])) |
| | | PYTHON |
| | | cat >"$FIXTURE_ROOT/bootstrap/setup.sh" <<'SETUP' |
| | | #!/bin/sh |
| | | # At this point join.sh has not even started; stale success must already be gone. |
| | | [ ! -e "$FIXTURE_ROOT/.bootstrap-finished" ] || exit 91 |
| | | mkdir -p "$FIXTURE_ROOT/data/config" |
| | | printf '1.0.0\n' >"$FIXTURE_ROOT/data/config/buildinfo" |
| | | exit "${SETUP_RC:-0}" |
| | | SETUP |
| | | cat >"$FIXTURE_ROOT/bootstrap/join.sh" <<'JOIN' |
| | | #!/bin/sh |
| | | [ ! -e "$FIXTURE_ROOT/.bootstrap-finished" ] || exit 92 |
| | | # Retained volumes stay health-ready independently of this unfinished join. |
| | | if [ "$CASE" = retained ]; then [ -f "$FIXTURE_ROOT/.bootstrap-complete" ] || exit 93; fi |
| | | printf 'join was called\n' |
| | | exit "${JOIN_RC:-0}" |
| | | JOIN |
| | | printf '#!/bin/sh\nexit 0\n' >"$FIXTURE_ROOT/bin/start-ds" |
| | | cp "$FIXTURE_ROOT/bin/start-ds" "$FIXTURE_ROOT/bin/stop-ds" |
| | | cp "$FIXTURE_ROOT/bin/start-ds" "$FIXTURE_ROOT/upgrade" |
| | | printf '1.0.0\n' >"$FIXTURE_ROOT/template/config/buildinfo" |
| | | chmod +x "$FIXTURE_ROOT/bootstrap/join.sh" "$FIXTURE_ROOT/bin/"* "$FIXTURE_ROOT/upgrade" |
| | | export ADMIN_PORT=14444 OPENDJ_REPLICATION_TYPE=simple REPLICATION_PEERS=seed ROOT_PASSWORD=fixture |
| | | unset BOOTSTRAP_COMPLETE BOOTSTRAP_FINISHED BOOTSTRAP_FAILED BOOTSTRAP_PENDING REJOIN_PENDING INITIALIZE_PENDING BOOTSTRAP |
| | | for CASE in fresh retained failed-join failed-setup no-join; do |
| | | export CASE |
| | | rm -rf "$FIXTURE_ROOT/data" |
| | | mkdir "$FIXTURE_ROOT/data" |
| | | export SETUP_RC=0 JOIN_RC=0 |
| | | OPENDJ_REPLICATION_TYPE=simple |
| | | case "$CASE" in |
| | | retained) mkdir "$FIXTURE_ROOT/data/config"; cp "$FIXTURE_ROOT/template/config/buildinfo" "$FIXTURE_ROOT/data/config/" ;; |
| | | failed-join) JOIN_RC=8 ;; |
| | | failed-setup) SETUP_RC=7 ;; |
| | | no-join) OPENDJ_REPLICATION_TYPE= ;; |
| | | esac |
| | | # All starts, including docker restart reusing the writable layer, clear old results. |
| | | touch "$FIXTURE_ROOT/.bootstrap-finished" "$FIXTURE_ROOT/.bootstrap-failed" |
| | | # The command substitution keeps the background wrapper's stdout open until it |
| | | # exits too, so assertions below observe the published result without sleeping. |
| | | result=$(bash "$OUT/run.sh" 2>&1) |
| | | case "$CASE" in |
| | | failed-*) |
| | | [ ! -f "$FIXTURE_ROOT/.bootstrap-finished" ] || { echo "$CASE kept stale success" >&2; exit 1; } |
| | | [ -f "$FIXTURE_ROOT/.bootstrap-failed" ] || exit 1 ;; |
| | | *) |
| | | [ -f "$FIXTURE_ROOT/.bootstrap-finished" ] || { echo "$CASE did not finish: $result" >&2; exit 1; } |
| | | [ ! -f "$FIXTURE_ROOT/.bootstrap-failed" ] || exit 1 ;; |
| | | esac |
| | | done |
| | | echo 'Every container start clears completion; only successful setup and join republish it' |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | set -e -o pipefail |
| | | HERE=$(cd "$(dirname "$0")" && pwd) |
| | | OUT=$(mktemp -d); trap 'rm -rf "$OUT"' EXIT |
| | | export FIXTURE_ROOT="$OUT/instance" CALLS="$OUT/calls" |
| | | mkdir -p "$FIXTURE_ROOT/bin" |
| | | # Run the actual bootstrap with only its external installation path redirected. |
| | | python3 - "$HERE/../../opendj-packages/opendj-docker/bootstrap/setup.sh" "$OUT/bootstrap.sh" "$FIXTURE_ROOT" <<'PYTHON' |
| | | from pathlib import Path |
| | | import sys |
| | | Path(sys.argv[2]).write_text(Path(sys.argv[1]).read_text().replace('/opt/opendj', sys.argv[3])) |
| | | PYTHON |
| | | cat >"$FIXTURE_ROOT/setup" <<'SETUP' |
| | | #!/bin/sh |
| | | printf 'setup\n' >>"$CALLS" |
| | | [ "${SETUP_RC:-0}" -eq 0 ] || exit "$SETUP_RC" |
| | | touch "$FIXTURE_ROOT/setup-running" |
| | | no_start=false |
| | | for arg; do [ "$arg" != --doNotStart ] || no_start=true; done |
| | | if [ "$no_start" = false ]; then "$FIXTURE_ROOT/bin/start-ds" || exit $?; fi |
| | | rm "$FIXTURE_ROOT/setup-running" |
| | | printf 'setup-exited\n' >>"$CALLS" |
| | | SETUP |
| | | cat >"$FIXTURE_ROOT/bin/start-ds" <<'START' |
| | | #!/bin/sh |
| | | printf 'start\n' >>"$CALLS" |
| | | if [ -e "$FIXTURE_ROOT/setup-running" ]; then |
| | | echo 'overlapping setup and server JVMs exhaust the memory budget' >&2 |
| | | exit 137 |
| | | fi |
| | | [ "${START_RC:-0}" -eq 0 ] || exit "$START_RC" |
| | | touch "$FIXTURE_ROOT/server-ready" |
| | | START |
| | | cat >"$FIXTURE_ROOT/bin/dsconfig" <<'CONFIG' |
| | | #!/bin/sh |
| | | printf 'configure\n' >>"$CALLS" |
| | | [ -f "$FIXTURE_ROOT/server-ready" ] |
| | | CONFIG |
| | | chmod +x "$FIXTURE_ROOT/setup" "$FIXTURE_ROOT/bin/"* |
| | | export ROOT_PASSWORD=password ROOT_USER_DN='cn=Directory Manager' ADMIN_PORT=4444 PORT=1389 LDAPS_PORT=1636 |
| | | export BASE_DN='dc=example,dc=com' OPENDJ_SSL_OPTIONS=--generateSelfSignedCertificate |
| | | unset INITIALIZE_PENDING SETUP_ARGS ADD_BASE_ENTRY SAMPLE_DATA |
| | | sh "$OUT/bootstrap.sh" >"$OUT/result" 2>&1 || { cat "$OUT/result" >&2; exit 1; } |
| | | printf 'setup\nsetup-exited\nstart\nconfigure\n' >"$OUT/expected" |
| | | diff -u "$OUT/expected" "$CALLS" |
| | | for failure in setup start; do |
| | | rm -f "$CALLS" "$FIXTURE_ROOT/server-ready" |
| | | rc=0 |
| | | if [ "$failure" = setup ]; then |
| | | SETUP_RC=8 sh "$OUT/bootstrap.sh" >"$OUT/result" 2>&1 || rc=$? |
| | | printf 'setup\n' >"$OUT/expected" |
| | | else |
| | | START_RC=1 sh "$OUT/bootstrap.sh" >"$OUT/result" 2>&1 || rc=$? |
| | | printf 'setup\nsetup-exited\nstart\n' >"$OUT/expected" |
| | | fi |
| | | [ "$rc" -ne 0 ] || { echo "failed $failure reported success" >&2; exit 1; } |
| | | diff -u "$OUT/expected" "$CALLS" |
| | | done |
| | | echo 'Docker bootstrap separates setup from startup and preserves both failures' |
| | |
| | | echo "MAVEN_JAVADOC_GOAL=javadoc:aggregate" >> $GITHUB_OUTPUT |
| | | |
| | | - name: Build with Maven |
| | | id: maven |
| | | timeout-minutes: 180 |
| | | env: |
| | | MAVEN_OPTS: -Dhttps.protocols=TLSv1.2 -Dmaven.wagon.httpconnectionManager.ttlSeconds=120 -Dmaven.wagon.http.retryHandler.requestSentEnabled=true -Dmaven.wagon.http.retryHandler.count=10 |
| | | run: mvn --batch-mode --errors --update-snapshots verify ${{ steps.javadoc.outputs.MAVEN_JAVADOC_GOAL }} --file pom.xml ${{ steps.failsafe.outputs.MAVEN_PROFILE_FLAG }} |
| | | |
| | | # TestListener removes passing test instances and keeps failed instances for diagnosis. |
| | | - name: Upload failed test audit logs |
| | | if: failure() && steps.maven.outcome == 'failure' |
| | | uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 |
| | | with: |
| | | name: failed-test-audit-logs-${{ matrix.os }}-${{ matrix.java }}-attempt-${{ github.run_attempt }} |
| | | path: | |
| | | opendj-server-legacy/target/unit-tests/*/package-instance/logs/audit |
| | | opendj-server-legacy/target/unit-tests/*/package-instance/logs/audit.* |
| | | retention-days: 5 |
| | | if-no-files-found: ignore |
| | | |
| | | - name: Validate the MSI (ICE) |
| | | # wix build runs no ICE validation (only MSBuild projects or an explicit validate |
| | | # do), so a green build alone proves the authoring compiles, not that it validates - |
| | |
| | | sparse-checkout: | |
| | | .github/benchmark |
| | | .github/scripts |
| | | opendj-server-legacy/resource/bin |
| | | opendj-packages/opendj-docker/bootstrap |
| | | - name: Download the image |
| | | uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 |
| | | with: |
| | |
| | | - name: Docker test |
| | | shell: bash |
| | | run: | |
| | | trap 'code=$?; echo "::group::container logs (test)"; docker logs test 2>&1 || true; echo "::endgroup::"; exit $code' ERR |
| | | bash .github/scripts/selftest-docker-setup.sh |
| | | bash .github/scripts/selftest-docker-run.sh |
| | | bash .github/scripts/selftest-docker-replication-wait.sh |
| | | bash .github/scripts/selftest-docker-diagnostics.sh |
| | | trap 'code=$?; bash .github/scripts/docker-startup-diagnostics.sh test "$RUNNER_TEMP/docker-startup" || true; exit $code' ERR |
| | | # the image draws nothing: the OS carries none of what AWT needs to, freetype with brotli, X11 or ALSA. |
| | | # The temurin JRE of the default image keeps a freetype of its own in /opt/java, linking nothing but libc (#1238) |
| | | awt=$(docker run --rm --entrypoint sh localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} -c 'find / -xdev \( -name "libfreetype.so*" ! -path "/opt/java/*" -o -name "libbrotli*.so*" -o -name "libX11.so*" -o -name "libasound.so*" \) 2>/dev/null; true') |
| | | if [ -n "$awt" ]; then echo "::error::The image carries libraries only AWT needs:"; echo "$awt"; false; fi |
| | | docker run -it -d --memory="512m" --name=test localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | docker run -it -d --name=test localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | # the bootstrap's server is down before the marker the health check waits for is |
| | | # written: the stop has logged its record by the time the marker is there |
| | | timeout 3m bash -c 'until docker exec test sh -c "test -f \"\$BOOTSTRAP_COMPLETE\"" 2>/dev/null; do sleep 0.2; done' |
| | |
| | | out=$(docker exec test sh -c 'unset JAVA_HOME; PATH=/bin:/usr/bin /opt/opendj/bin/ldapsearch --version' 2>&1 || true) |
| | | if grep -F "unexpected operator" <<<"$out"; then echo "::error::The lookup of java on the PATH fails with a shell error where it finds no java"; false; fi |
| | | docker rm -f test |
| | | - name: Upload Docker startup diagnostics |
| | | if: ${{ failure() }} |
| | | uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 |
| | | with: |
| | | name: docker-startup-${{ matrix.flavor }} |
| | | path: ${{ runner.temp }}/docker-startup |
| | | if-no-files-found: ignore |
| | | - name: Docker test custom password |
| | | shell: bash |
| | | run: | |
| | | trap 'code=$?; echo "::group::container logs (test_custom)"; docker logs test_custom 2>&1 || true; echo "::endgroup::"; exit $code' ERR |
| | | docker run --rm -it -d --memory="512m" -e ADD_BASE_ENTRY="--addBaseEntry" -e ROOT_PASSWORD=custom_password --name=test_custom localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | docker run --rm -it -d -e ADD_BASE_ENTRY="--addBaseEntry" -e ROOT_PASSWORD=custom_password --name=test_custom localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | timeout 3m bash -c 'until docker inspect --format="{{json .State.Health.Status}}" test_custom | grep -q \"healthy\"; do sleep 10; done' |
| | | docker exec test_custom 'sh' '-c' '/opt/opendj/bin/ldapsearch --hostname localhost --port 1636 --bindDN "cn=Directory Manager" --bindPassword custom_password --useSsl --trustAll --baseDN "dc=example,dc=com" --searchScope base "(objectClass=*)" 1.1' |
| | | docker kill test_custom |
| | |
| | | shell: bash |
| | | run: | |
| | | trap 'code=$?; echo "::group::container logs (test_base_dn)"; docker logs test_base_dn 2>&1 || true; echo "::endgroup::"; exit $code' ERR |
| | | docker run --rm -it -d --memory="512m" -e ADD_BASE_ENTRY="--addBaseEntry" -e BASE_DN="o=My Company,c=US" --name=test_base_dn localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | docker run --rm -it -d -e ADD_BASE_ENTRY="--addBaseEntry" -e BASE_DN="o=My Company,c=US" --name=test_base_dn localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | timeout 3m bash -c 'until docker inspect --format="{{json .State.Health.Status}}" test_base_dn | grep -q \"healthy\"; do sleep 10; done' |
| | | docker exec test_base_dn 'sh' '-c' '/opt/opendj/bin/ldapsearch --hostname localhost --port 1636 --bindDN "cn=Directory Manager" --bindPassword password --useSsl --trustAll --baseDN "o=My Company,c=US" --searchScope base "(objectClass=*)" 1.1 | grep -qx "dn: o=My Company,c=US"' |
| | | docker kill test_base_dn |
| | |
| | | run: | |
| | | trap 'code=$?; echo "::group::container logs (test_uid)"; docker logs test_uid 2>&1 || true; echo "::endgroup::"; exit $code' ERR |
| | | uid=$((1000000000 + RANDOM)) |
| | | docker run --rm -it -d --memory="512m" --user $uid:0 -e ADD_BASE_ENTRY="--addBaseEntry" --name=test_uid localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | docker run --rm -it -d --user $uid:0 -e ADD_BASE_ENTRY="--addBaseEntry" --name=test_uid localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | timeout 3m bash -c 'until docker inspect --format="{{json .State.Health.Status}}" test_uid | grep -q \"healthy\"; do sleep 10; done' |
| | | docker exec test_uid 'sh' '-c' "test \"\$(stat -c %u /opt/opendj/instance.loc)\" = $uid" |
| | | docker exec test_uid 'sh' '-c' '/opt/opendj/bin/ldapsearch --hostname localhost --port 1636 --bindDN "cn=Directory Manager" --bindPassword password --useSsl --trustAll --baseDN "dc=example,dc=com" --searchScope base "(objectClass=*)" 1.1' |
| | |
| | | # scenarios for both images |
| | | shell: bash |
| | | run: .github/scripts/docker-test-replication.sh "localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }}" |
| | | - name: Upload Docker replication diagnostics |
| | | if: failure() |
| | | uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 |
| | | with: |
| | | name: docker-replication-${{ matrix.flavor }}-attempt-${{ github.run_attempt }} |
| | | path: ${{ runner.temp }}/docker-replication |
| | | if-no-files-found: ignore |
| | | - name: Docker test secret volume |
| | | # a keystore mounted at SECRET_VOLUME is what LDAPS serves from the first start on, a |
| | | # renewed one - a new password included - is copied while the server runs and served |
| | |
| | | healthy() { timeout 3m bash -c 'until docker inspect --format="{{json .State.Health.Status}}" test_secret | grep -q \"healthy\"; do sleep 10; done'; } |
| | | copies() { docker logs test_secret 2>&1 | grep -c "^Copied $1 from the secret volume$" || true; } |
| | | keystore secret-v1 |
| | | docker run -d --memory="512m" -e SECRET_VOLUME_REFRESH=5 -p 127.0.0.1:1637:1636 --name=test_secret \ |
| | | docker run -d -e SECRET_VOLUME_REFRESH=5 -p 127.0.0.1:1637:1636 --name=test_secret \ |
| | | -v "$SECRETS":/var/secrets/opendj:ro -v test_secret_data:/opt/opendj/data "$IMAGE" |
| | | healthy |
| | | grep -q "CN=secret-v1" <<< "$(served)" |
| | |
| | | # renewed while no container runs, the keystore, its new password and its new alias |
| | | # are copied by the start, over the instance already there |
| | | keystore secret-v4 changeit3 |
| | | docker run -d --memory="512m" -e SECRET_VOLUME_REFRESH=0 -p 127.0.0.1:1637:1636 --name=test_secret \ |
| | | docker run -d -e SECRET_VOLUME_REFRESH=0 -p 127.0.0.1:1637:1636 --name=test_secret \ |
| | | -v "$SECRETS":/var/secrets/opendj:ro -v test_secret_data:/opt/opendj/data "$IMAGE" |
| | | healthy |
| | | grep -q "CN=secret-v4" <<< "$(served)" |
| | |
| | | IMAGE=localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | trap 'code=$?; for c in test_bootstrap_lf test_bootstrap_cr test_bootstrap; do echo "::group::container logs ($c)"; docker logs $c 2>&1 || true; echo "::endgroup::"; done; exit $code' ERR |
| | | # a root password with a line break is refused: the tools read only the first line of the password file |
| | | docker run -d --memory="512m" -e ROOT_PASSWORD=$'ab\ncd' --name=test_bootstrap_lf "$IMAGE" |
| | | docker run -d --memory="512m" -e ROOT_PASSWORD=$'ab\rcd' --name=test_bootstrap_cr "$IMAGE" |
| | | docker run -d -e ROOT_PASSWORD=$'ab\ncd' --name=test_bootstrap_lf "$IMAGE" |
| | | docker run -d -e ROOT_PASSWORD=$'ab\rcd' --name=test_bootstrap_cr "$IMAGE" |
| | | for c in test_bootstrap_lf test_bootstrap_cr; do |
| | | timeout 2m bash -c 'until docker logs $0 2>&1 | grep -qF "ROOT_PASSWORD must not contain a line break"; do sleep 2; done' $c |
| | | done |
| | |
| | | chmod -R a+rX "$BOOTSTRAP_DIR" |
| | | # the containers of a Kubernetes pod share its /dev/shm, which outlives a restart of one of them: the holder stands in for the pod |
| | | docker run -d --no-healthcheck --ipc=shareable --entrypoint sleep --name=test_bootstrap_shm "$IMAGE" 3600 |
| | | docker run -it -d --memory="512m" --ipc=container:test_bootstrap_shm -e ADD_BASE_ENTRY="--addBaseEntry" -e ROOT_PASSWORD="$ROOT_PASSWORD" -e ADMIN_PORT=5444 -v "$BOOTSTRAP_DIR/schema:/opt/opendj/bootstrap/schema:ro" -v "$BOOTSTRAP_DIR/data:/opt/opendj/bootstrap/data:ro" -v "$BOOTSTRAP_DIR/config/schema:/opt/opendj/bootstrap/config/schema:ro" --name=test_bootstrap "$IMAGE" |
| | | docker run -it -d --ipc=container:test_bootstrap_shm -e ADD_BASE_ENTRY="--addBaseEntry" -e ROOT_PASSWORD="$ROOT_PASSWORD" -e ADMIN_PORT=5444 -v "$BOOTSTRAP_DIR/schema:/opt/opendj/bootstrap/schema:ro" -v "$BOOTSTRAP_DIR/data:/opt/opendj/bootstrap/data:ro" -v "$BOOTSTRAP_DIR/config/schema:/opt/opendj/bootstrap/config/schema:ro" --name=test_bootstrap "$IMAGE" |
| | | # while the bootstrap runs, the password file is on the tmpfs of /dev/shm rather than in the writable |
| | | # layer, and its name carries the admin port of the container |
| | | timeout 2m bash -c 'until docker exec test_bootstrap sh -c "ls /dev/shm/opendj-setup-password.5444.*" >/dev/null 2>&1; do sleep 1; done' |
| | |
| | | done |
| | | } |
| | | # ROOT_PASSWORD is only the initial root password: changing it must not turn the container unhealthy |
| | | docker run -it -d --memory="512m" --health-interval=5s -e ROOT_PASSWORD=initial_password --name=test_health $IMAGE |
| | | docker run -it -d --health-interval=5s -e ROOT_PASSWORD=initial_password --name=test_health $IMAGE |
| | | timeout 3m bash -c 'until docker inspect --format="{{json .State.Health.Status}}" test_health | grep -q \"healthy\"; do sleep 10; done' |
| | | docker exec test_health /opt/opendj/bin/ldappasswordmodify --hostname localhost --port 1636 --useSsl --trustAll --bindDN "cn=Directory Manager" --bindPassword initial_password --currentPassword initial_password --newPassword rotated_password |
| | | # bind settings kept for the CLI in the home of the image user must not reach the probe |
| | |
| | | # a password of its own, so the command lines below can be searched for it |
| | | printf hc_secret_1092 > "$RUNNER_TEMP/healthcheck_password" |
| | | chmod 644 "$RUNNER_TEMP/healthcheck_password" |
| | | docker run -it -d --memory="512m" --health-interval=5s -v "$RUNNER_TEMP/healthcheck_password:/tmp/healthcheck_password:ro" -e ROOT_PASSWORD=hc_secret_1092 -e HEALTHCHECK_BIND_DN="cn=Directory Manager" -e HEALTHCHECK_BIND_PASSWORD_FILE=/tmp/healthcheck_password --name=test_health_bind $IMAGE |
| | | docker run -it -d --health-interval=5s -v "$RUNNER_TEMP/healthcheck_password:/tmp/healthcheck_password:ro" -e ROOT_PASSWORD=hc_secret_1092 -e HEALTHCHECK_BIND_DN="cn=Directory Manager" -e HEALTHCHECK_BIND_PASSWORD_FILE=/tmp/healthcheck_password --name=test_health_bind $IMAGE |
| | | timeout 3m bash -c 'until docker inspect --format="{{json .State.Health.Status}}" test_health_bind | grep -q \"healthy\"; do sleep 10; done' |
| | | docker exec test_health_bind /opt/opendj/bin/dsconfig set-global-configuration-prop --hostname localhost --port 4444 --bindDN "cn=Directory Manager" --bindPasswordFile /tmp/healthcheck_password --set reject-unauthenticated-requests:true --no-prompt --trustAll |
| | | # the setting has taken: the anonymous probe would now be refused |
| | |
| | | shell: bash |
| | | run: | |
| | | IMAGE=localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | MEMORY=512m |
| | | trap 'code=$?; echo "::group::container logs (test_failed)"; docker logs test_failed 2>&1 || true; docker inspect --format="{{json .State.Health}}" test_failed 2>&1 || true; echo "::endgroup::"; docker rm -f test_failed >/dev/null 2>&1 || true; docker volume rm test_failed_data >/dev/null 2>&1 || true; exit $code' ERR |
| | | # an unknown backend type fails create-backend once setup has written data/config |
| | | docker run -d --memory="$MEMORY" --health-interval=5s -e ADD_BASE_ENTRY="--addBaseEntry" -e BACKEND_TYPE=bogus -v test_failed_data:/opt/opendj/data --name=test_failed "$IMAGE" |
| | | docker run -d --health-interval=5s -e ADD_BASE_ENTRY="--addBaseEntry" -e BACKEND_TYPE=bogus -v test_failed_data:/opt/opendj/data --name=test_failed "$IMAGE" |
| | | timeout 3m bash -c 'until docker logs test_failed 2>&1 | grep -qF "failed, this container will not report itself healthy"; do sleep 2; done' |
| | | docker restart -t 60 test_failed |
| | | timeout 3m bash -c 'until docker logs test_failed 2>&1 | grep -qF "The bootstrap of this volume did not complete"; do sleep 2; done' |
| | |
| | | run: | |
| | | IMAGE=localhost:5000/${GITHUB_REPOSITORY,,}:${{ env.release_version }}${{ matrix.suffix }} |
| | | RELEASED=openidentityplatform/opendj:${{ env.release_version }}${{ matrix.suffix }} |
| | | MEMORY=512m |
| | | trap 'code=$?; echo "::group::container logs (test_upgrade)"; docker logs test_upgrade 2>&1 || true; docker inspect --format="{{json .State.Health}}" test_upgrade 2>&1 || true; echo "::endgroup::"; docker rm -f test_upgrade >/dev/null 2>&1 || true; docker volume rm test_upgrade_data >/dev/null 2>&1 || true; exit $code' ERR |
| | | search() { docker exec test_upgrade /opt/opendj/bin/ldapsearch --hostname localhost --port 1636 --useSsl --trustAll --bindDN "cn=Directory Manager" --bindPassword password "$@"; } |
| | | # release.yml publishes the GitHub release before it pushes the images of it: in between, |
| | |
| | | *) exit 1 ;; |
| | | esac |
| | | fi |
| | | docker run -d --memory="$MEMORY" -e ADD_BASE_ENTRY="--addBaseEntry" -e SAMPLE_DATA=10 -v test_upgrade_data:/opt/opendj/data --name=test_upgrade "$RELEASED" |
| | | docker run -d -e ADD_BASE_ENTRY="--addBaseEntry" -e SAMPLE_DATA=10 -v test_upgrade_data:/opt/opendj/data --name=test_upgrade "$RELEASED" |
| | | # the entries, not the health status: the health check of 5.1.2 turned healthy before |
| | | # import-ldif had finished |
| | | export -f search |
| | | timeout 5m bash -c 'until search --baseDN "ou=People,dc=example,dc=com" --searchScope one "(uid=user.9)" 1.1 2>/dev/null | grep -q "^dn:"; do sleep 5; done' |
| | | docker stop -t 60 test_upgrade |
| | | docker rm test_upgrade |
| | | docker run -d --memory="$MEMORY" -v test_upgrade_data:/opt/opendj/data --name=test_upgrade "$IMAGE" |
| | | docker run -d -v test_upgrade_data:/opt/opendj/data --name=test_upgrade "$IMAGE" |
| | | timeout 10m bash -c 'until docker inspect --format="{{json .State.Health.Status}}" test_upgrade | grep -q \"healthy\"; do sleep 5; done' |
| | | # the upgrade ran its tasks: on equal versions it would be a no-op |
| | | if docker logs test_upgrade 2>&1 | grep -F "has already been upgraded"; then echo "::error::The build image found nothing to upgrade on the volume of $RELEASED"; false; fi |
| | |
| | | docker stop -t 60 test_upgrade |
| | | docker rm test_upgrade |
| | | docker run --rm --entrypoint sh -v test_upgrade_data:/opt/opendj/data "$IMAGE" -c 'echo "an earlier version to this one" >/opt/opendj/data/.upgrade-pending' |
| | | docker run -d --memory="$MEMORY" --health-interval=5s -v test_upgrade_data:/opt/opendj/data --name=test_upgrade "$IMAGE" |
| | | docker run -d --health-interval=5s -v test_upgrade_data:/opt/opendj/data --name=test_upgrade "$IMAGE" |
| | | timeout 3m bash -c 'until docker logs test_upgrade 2>&1 | grep -qF "did not complete on an earlier start"; do sleep 2; done' |
| | | # the server is up to be looked at, and no probe passes over 45 s of probes every 5 s |
| | | timeout 3m bash -c 'until search --baseDN "" --searchScope base "(objectClass=*)" 1.1 >/dev/null 2>&1; do sleep 5; done' |
| | |
| | | docker volume rm test_upgrade_data |
| | | # the mark goes on before the upgrade and stays when it fails: a read-only buildinfo |
| | | # fails it where it records the new version, after its upgrade tasks |
| | | docker run -d --memory="$MEMORY" -e ADD_BASE_ENTRY="--addBaseEntry" -v test_upgrade_data:/opt/opendj/data --name=test_upgrade "$RELEASED" |
| | | docker run -d -e ADD_BASE_ENTRY="--addBaseEntry" -v test_upgrade_data:/opt/opendj/data --name=test_upgrade "$RELEASED" |
| | | timeout 5m bash -c 'until search --baseDN "dc=example,dc=com" --searchScope base "(objectClass=*)" 1.1 2>/dev/null | grep -q "^dn:"; do sleep 5; done' |
| | | docker stop -t 60 test_upgrade |
| | | docker rm test_upgrade |
| | | docker run --rm --user root --entrypoint chmod -v test_upgrade_data:/opt/opendj/data "$IMAGE" 444 /opt/opendj/data/config/buildinfo |
| | | docker run -d --memory="$MEMORY" -v test_upgrade_data:/opt/opendj/data --name=test_upgrade "$IMAGE" |
| | | docker run -d -v test_upgrade_data:/opt/opendj/data --name=test_upgrade "$IMAGE" |
| | | timeout 5m bash -c 'until docker logs test_upgrade 2>&1 | grep -qF "The upgrade did not complete, this container will not report itself healthy"; do sleep 2; done' |
| | | docker run --rm --entrypoint test -v test_upgrade_data:/opt/opendj/data "$IMAGE" -s /opt/opendj/data/.upgrade-pending |
| | | docker rm -f test_upgrade |
| | |
| | | # a red row turns the Build run red, and deploy.yml then skips the snapshot deploy and the |
| | | # publishing of the docs of a push to master |
| | | runs-on: 'ubuntu-latest' |
| | | # Scale has a 45-minute load ceiling plus setup, final checks and artifact upload. |
| | | timeout-minutes: ${{ startsWith(matrix.disturbance, 'scale-') && 75 || 360 }} |
| | | permissions: |
| | | contents: read |
| | | strategy: |
| | |
| | | matrix: |
| | | topology: [rs534, combined] |
| | | # none: the base run; restart-ds and kill-ds: a directory server restarts or crashes; |
| | | # kill-rs and restart-rs: one RS is killed or gracefully restarted per fresh topology |
| | | # while every DS writes. Only rs534 has replication servers apart from directory servers. |
| | | disturbance: [none, restart-ds, kill-ds, kill-rs, restart-rs] |
| | | # kill-rs and restart-rs: one RS is killed or gracefully restarted per fresh topology; |
| | | # empty-rs rebuilds an RS while one DS is down, then tests failover to each RS. |
| | | # scale variants remove a node and roll survivors, then add it back. |
| | | # Only rs534 has replication servers apart from directory servers. |
| | | disturbance: [none, restart-ds, kill-ds, kill-rs, restart-rs, empty-rs, scale-rs-kept, scale-rs-empty, scale-kept, scale-empty] |
| | | exclude: |
| | | - topology: combined |
| | | disturbance: kill-rs |
| | | - topology: combined |
| | | disturbance: restart-rs |
| | | - topology: combined |
| | | disturbance: empty-rs |
| | | - topology: combined |
| | | disturbance: scale-rs-kept |
| | | - topology: combined |
| | | disturbance: scale-rs-empty |
| | | - topology: rs534 |
| | | disturbance: scale-kept |
| | | - topology: rs534 |
| | | disturbance: scale-empty |
| | | steps: |
| | | - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 |
| | | with: |
| | | sparse-checkout: | |
| | | .github/scripts/replication |
| | | opendj-packages/opendj-docker |
| | | # what a green row does not show: what a disturbance window of the errors log check |
| | | # expects - nothing it expects is logged outside the window there, and a base row has |
| | | # none - and where each disturbance opens and closes its windows |
| | |
| | | shell: bash |
| | | run: | |
| | | .github/scripts/replication/selftest-replication-errors.sh |
| | | .github/scripts/replication/selftest-unindexed-searches.sh |
| | | .github/scripts/replication/selftest-disturb-restart-ds.sh |
| | | .github/scripts/replication/selftest-disturb-kill-ds.sh |
| | | .github/scripts/replication/selftest-disturb-rs.sh |
| | | .github/scripts/replication/selftest-disturb-empty-rs.sh |
| | | .github/scripts/replication/selftest-disturb-scale.sh |
| | | bash .github/scripts/replication/selftest-scale-timeout.sh |
| | | bash .github/scripts/replication/selftest-scale-bootstrap.sh |
| | | .github/scripts/replication/selftest-scale-membership.sh |
| | | .github/scripts/replication/selftest-scale-ids.sh |
| | | .github/scripts/replication/selftest-scale-topology.sh |
| | | bash .github/scripts/replication/selftest-join-timing.sh |
| | | bash .github/scripts/replication/selftest-join-batch.sh |
| | | bash .github/scripts/replication/selftest-join-reset.sh |
| | | bash .github/scripts/replication/selftest-join-search.sh |
| | | .github/scripts/replication/selftest-rolling-load.sh |
| | | .github/scripts/replication/selftest-wait.sh |
| | | python3 .github/scripts/replication/selftest-changelog-checkpoint.py |
| | | python3 .github/scripts/replication/selftest-changelog-gaps.py |
| | | python3 .github/scripts/replication/selftest-csn-trace.py |
| | | bash .github/scripts/replication/selftest-csn-trace-harness.sh |
| | | python3 .github/scripts/replication/selftest-scale-monitor.py |
| | | python3 .github/scripts/replication/selftest-scale-fence.py |
| | | python3 .github/scripts/replication/selftest-scale-coverage.py |
| | | python3 .github/scripts/replication/selftest-scale-deadline.py |
| | | .github/scripts/replication/selftest-summary.sh |
| | | - name: Download the image |
| | | uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 |
| | |
| | | shell: bash |
| | | run: docker load -i "$RUNNER_TEMP/image/image.tar" |
| | | - name: Convergence run (${{ matrix.topology }}, ${{ matrix.disturbance }}) |
| | | timeout-minutes: ${{ startsWith(matrix.disturbance, 'scale-') && 70 || 360 }} |
| | | shell: bash |
| | | env: |
| | | TOPOLOGY: ${{ matrix.topology }} |
| | | DISTURBANCE: ${{ matrix.disturbance }} |
| | | # Every row runs 900 s of load; disturbed rows act a third of the way in. |
| | | DURATION: "900" |
| | | CSN_TRACE: "${{ (startsWith(matrix.disturbance, 'scale-') || matrix.disturbance == 'empty-rs') && '1' || '0' }}" |
| | | # Scale stops after verified post-scale writes, subject to this 45-minute ceiling. |
| | | DURATION: "${{ startsWith(matrix.disturbance, 'scale-') && '2700' || '900' }}" |
| | | # the replicas fall behind during the load and catch up after it: 900 s at 325 and 65 |
| | | # a second converged in 396 s (run 38944365728), 1800 s at 423 and 85 in 2489 s (run |
| | | # 39043600905), the backlog growing faster than the load above the replay capacity; a |
| | | # run that does not converge in time skips the checks of the data |
| | | QUIESCE_TIMEOUT: "4500" |
| | | # Run 43857403579: the retained combined replica still lacked 113636 updates after 299 s. |
| | | # Its slowest mean drain rate projects 735 s to zero, plus over 65 s of stable zero samples. |
| | | QUIESCE_TIMEOUT: "${{ matrix.topology == 'combined' && matrix.disturbance == 'scale-kept' && '900' || matrix.topology == 'combined' && matrix.disturbance == 'scale-empty' && '600' || startsWith(matrix.disturbance, 'scale-') && '300' || '4500' }}" |
| | | SAMPLE_DATA: "10000" |
| | | OUT: ${{ runner.temp }}/replication-out |
| | | run: .github/scripts/replication/run.sh "localhost:5000/${GITHUB_REPOSITORY,,}:${{ needs.build-docker.outputs.release_version }}" |
| New file |
| | |
| | | /* |
| | | * 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. |
| | | */ |
| | | package com.forgerock.opendj.ldap.tools; |
| | | |
| | | import static java.nio.charset.StandardCharsets.UTF_8; |
| | | |
| | | import java.io.BufferedReader; |
| | | import java.io.ByteArrayOutputStream; |
| | | import java.io.IOException; |
| | | import java.io.InputStream; |
| | | import java.io.InputStreamReader; |
| | | import java.io.OutputStream; |
| | | import java.io.PrintStream; |
| | | import java.security.Security; |
| | | import java.util.Base64; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * Internal worker for Docker bootstrap reads. Each request runs a fresh LDAPSearch, with |
| | | * a fresh connection and argument parser, while sharing the JVM startup and TLS providers. |
| | | * Requests are base64 encoded NUL-separated arguments; responses are a status and base64 |
| | | * encoded stdout on one line. The private pipes are owned by the joining container user. |
| | | */ |
| | | public final class BootstrapSearch { |
| | | private BootstrapSearch() { |
| | | // Utility class. |
| | | } |
| | | |
| | | /** |
| | | * Runs searches until the parent closes its request pipe. |
| | | * @param args unused |
| | | * @throws IOException if a pipe cannot be read or written |
| | | */ |
| | | public static void main(String[] args) throws IOException { |
| | | configureDnsCaching(); |
| | | PrintStream protocol = System.out; |
| | | // Libraries must not interleave their diagnostics with protocol frames. |
| | | System.setOut(System.err); |
| | | serve(System.in, protocol, "1".equals(System.getenv("JOIN_TIMING"))); |
| | | } |
| | | |
| | | static void configureDnsCaching() { |
| | | // A recreated container keeps its hostname, not its address. Match the fresh |
| | | // DNS view of separate ldapsearch JVMs, including names which were absent. |
| | | Security.setProperty("networkaddress.cache.ttl", "0"); |
| | | Security.setProperty("networkaddress.cache.negative.ttl", "0"); |
| | | Security.setProperty("networkaddress.cache.stale.ttl", "0"); |
| | | } |
| | | |
| | | static String[] decode(String request) { |
| | | String decoded = new String(Base64.getDecoder().decode(request), UTF_8); |
| | | if (!decoded.endsWith("\0")) { |
| | | throw new IllegalArgumentException("Unterminated bootstrap search request"); |
| | | } |
| | | return decoded.substring(0, decoded.length() - 1).split("\0", -1); |
| | | } |
| | | |
| | | static void serve(InputStream input, PrintStream output, boolean timing) throws IOException { |
| | | BufferedReader requests = new BufferedReader(new InputStreamReader(input, UTF_8)); |
| | | String request; |
| | | while ((request = requests.readLine()) != null) { |
| | | String[] args = decode(request); |
| | | ByteArrayOutputStream result = new ByteArrayOutputStream(); |
| | | long start = System.nanoTime(); |
| | | int status; |
| | | try (PrintStream stdout = new PrintStream(result, false, "UTF-8"); |
| | | PrintStream stderr = new PrintStream(OutputStream.nullOutputStream())) { |
| | | status = LDAPSearch.run(stdout, stderr, args); |
| | | } |
| | | if (timing) { |
| | | System.err.println("join-search event=result milliseconds=" |
| | | + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + " status=" + status); |
| | | } |
| | | output.println(status + " " + Base64.getEncoder().encodeToString(result.toByteArray())); |
| | | output.flush(); |
| | | if (output.checkError()) { |
| | | throw new IOException("Bootstrap search response pipe closed"); |
| | | } |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * 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. |
| | | */ |
| | | package com.forgerock.opendj.ldap.tools; |
| | | |
| | | import static java.nio.charset.StandardCharsets.UTF_8; |
| | | import static org.testng.Assert.*; |
| | | |
| | | import java.io.ByteArrayInputStream; |
| | | import java.io.ByteArrayOutputStream; |
| | | import java.io.OutputStream; |
| | | import java.io.PrintStream; |
| | | import java.net.InetAddress; |
| | | import java.net.UnknownHostException; |
| | | import java.nio.file.Files; |
| | | import java.nio.file.Path; |
| | | import java.util.Base64; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | import org.forgerock.opendj.ldap.IntermediateResponseHandler; |
| | | import org.forgerock.opendj.ldap.LdapResultHandler; |
| | | import org.forgerock.opendj.ldap.ResultCode; |
| | | import org.forgerock.opendj.ldap.SearchResultHandler; |
| | | import org.forgerock.opendj.ldap.requests.SearchRequest; |
| | | import org.forgerock.opendj.ldap.responses.Responses; |
| | | import org.forgerock.opendj.ldap.responses.Result; |
| | | import org.forgerock.testng.ForgeRockTestCase; |
| | | import org.testng.annotations.Test; |
| | | |
| | | /** Checks framing and recovery between searches in the Docker bootstrap worker. */ |
| | | @SuppressWarnings("javadoc") |
| | | @Test |
| | | public class BootstrapSearchTestCase extends ForgeRockTestCase { |
| | | @Test |
| | | public void failedSearchDoesNotPoisonTheNextRequest() throws Exception { |
| | | String input = request("--invalid-option") + request("--help"); |
| | | ByteArrayOutputStream output = new ByteArrayOutputStream(); |
| | | BootstrapSearch.serve(new ByteArrayInputStream(input.getBytes(UTF_8)), |
| | | new PrintStream(output), false); |
| | | String[] lines = output.toString("UTF-8").lines().toArray(String[]::new); |
| | | assertEquals(lines.length, 2); |
| | | assertFalse(lines[0].startsWith("0 ")); |
| | | assertTrue(lines[1].startsWith("0 ")); |
| | | assertTrue(new String(Base64.getDecoder().decode(lines[1].substring(2)), UTF_8).contains("baseDN")); |
| | | } |
| | | |
| | | @Test |
| | | public void workerPreservesPartialLdifAndSizeLimitStatus() throws Exception { |
| | | String partialDn = "cn=partial,dc=example"; |
| | | String completeDn = "cn=complete,dc=example"; |
| | | ToolLdapServer server = new ToolLdapServer() { |
| | | @Override |
| | | ToolLdapServerConnection newServerConnection() { |
| | | return new ToolLdapServerConnection() { |
| | | @Override |
| | | public void handleSearch(Integer requestContext, SearchRequest request, |
| | | IntermediateResponseHandler intermediateResponseHandler, |
| | | SearchResultHandler entryHandler, |
| | | LdapResultHandler<Result> resultHandler) { |
| | | String dn = request.getName().toString(); |
| | | if (partialDn.equals(dn)) { |
| | | entryHandler.handleEntry(Responses.newSearchResultEntry("dn: " + partialDn, "cn: partial")); |
| | | resultHandler.handleResult(Responses.newResult(ResultCode.SIZE_LIMIT_EXCEEDED)); |
| | | } else if (completeDn.equals(dn)) { |
| | | entryHandler.handleEntry( |
| | | Responses.newSearchResultEntry("dn: " + completeDn, "cn: complete")); |
| | | resultHandler.handleResult(Responses.newResult(ResultCode.SUCCESS)); |
| | | } else { |
| | | resultHandler.handleResult(Responses.newResult(ResultCode.NO_SUCH_OBJECT)); |
| | | } |
| | | } |
| | | }; |
| | | } |
| | | }; |
| | | server.start(); |
| | | try { |
| | | String[] partialArgs = searchArgs(server, partialDn); |
| | | String[] completeArgs = searchArgs(server, completeDn); |
| | | ByteArrayOutputStream cliOutput = new ByteArrayOutputStream(); |
| | | int cliStatus; |
| | | try (PrintStream stdout = new PrintStream(cliOutput, false, UTF_8); |
| | | PrintStream stderr = new PrintStream(OutputStream.nullOutputStream())) { |
| | | cliStatus = LDAPSearch.run(stdout, stderr, partialArgs); |
| | | } |
| | | assertEquals(cliStatus, 4); |
| | | String partialLdif = cliOutput.toString(UTF_8); |
| | | assertEquals(partialLdif.stripTrailing().lines().toArray(String[]::new), |
| | | new String[] {"dn: " + partialDn, "cn: partial"}); |
| | | |
| | | String input = request(partialArgs) + request(completeArgs); |
| | | ByteArrayOutputStream output = new ByteArrayOutputStream(); |
| | | try (PrintStream protocol = new PrintStream(output, false, UTF_8)) { |
| | | BootstrapSearch.serve(new ByteArrayInputStream(input.getBytes(UTF_8)), protocol, false); |
| | | } |
| | | String[] frames = output.toString(UTF_8).lines().toArray(String[]::new); |
| | | assertEquals(frames.length, 2); |
| | | assertEquals(frames[0], cliStatus + " " + Base64.getEncoder().encodeToString(cliOutput.toByteArray())); |
| | | String[] success = frames[1].split(" ", 2); |
| | | assertEquals(success.length, 2); |
| | | assertEquals(success[0], "0"); |
| | | String completeLdif = new String(Base64.getDecoder().decode(success[1]), UTF_8); |
| | | assertEquals(completeLdif.stripTrailing().lines().toArray(String[]::new), |
| | | new String[] {"dn: " + completeDn, "cn: complete"}); |
| | | } finally { |
| | | server.stop(); |
| | | } |
| | | } |
| | | |
| | | private static String[] searchArgs(ToolLdapServer server, String dn) { |
| | | return new String[] {"--noPropertiesFile", "-h", server.getHostName(), "-p", server.getPort(), |
| | | "-b", dn, "-s", "base", "(objectClass=*)", "cn"}; |
| | | } |
| | | |
| | | @Test |
| | | public void framingPreservesEmptyUnicodeAndMultilineArguments() { |
| | | String[] args = {"", "cn=тест,dc=example", "(description=one\ntwo)", "a b\tc"}; |
| | | assertEquals(BootstrapSearch.decode(request(args).trim()), args); |
| | | } |
| | | |
| | | @Test |
| | | public void workerRefreshesPositiveAndNegativeDnsAnswers() throws Exception { |
| | | Path hosts = Files.createTempFile("bootstrap-dns", ".hosts"); |
| | | Process probe = null; |
| | | try { |
| | | probe = new ProcessBuilder(System.getProperty("java.home") + "/bin/java", |
| | | "-Djdk.net.hosts.file=" + hosts, "-cp", System.getProperty("java.class.path"), |
| | | DnsProbe.class.getName(), hosts.toString()).redirectErrorStream(true).start(); |
| | | assertTrue(probe.waitFor(20, TimeUnit.SECONDS), "DNS probe did not finish"); |
| | | assertEquals(probe.exitValue(), 0, new String(probe.getInputStream().readAllBytes(), UTF_8)); |
| | | } finally { |
| | | if (probe != null) { |
| | | probe.destroyForcibly(); |
| | | } |
| | | Files.deleteIfExists(hosts); |
| | | } |
| | | } |
| | | |
| | | /** Runs in a fresh JVM so the test neither inherits nor alters the suite's DNS policy. */ |
| | | public static final class DnsProbe { |
| | | public static void main(String[] args) throws Exception { |
| | | BootstrapSearch.configureDnsCaching(); |
| | | Path hosts = Path.of(args[0]); |
| | | Files.writeString(hosts, "127.0.0.1 peer\n"); |
| | | requireAddress("peer", "127.0.0.1"); |
| | | Files.writeString(hosts, "127.0.0.2 peer\n"); |
| | | requireAddress("peer", "127.0.0.2"); |
| | | try { |
| | | InetAddress.getByName("new-peer"); |
| | | throw new AssertionError("missing peer resolved"); |
| | | } catch (UnknownHostException expected) { |
| | | // The next request must not retain this negative result. |
| | | } |
| | | Files.writeString(hosts, "127.0.0.3 new-peer\n"); |
| | | requireAddress("new-peer", "127.0.0.3"); |
| | | } |
| | | |
| | | private static void requireAddress(String host, String expected) throws Exception { |
| | | String actual = InetAddress.getByName(host).getHostAddress(); |
| | | if (!expected.equals(actual)) { |
| | | throw new AssertionError(host + ": expected " + expected + ", got " + actual); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private static String request(String... args) { |
| | | return Base64.getEncoder().encodeToString((String.join("\0", args) + "\0").getBytes(UTF_8)) + "\n"; |
| | | } |
| | | } |
| | |
| | | failed, say): `BASE_DN` is replicated, and every later enable only reports it as replicated |
| | | already, without registering the server where it is missing. |
| | | |
| | | Bootstrap LDAP reads share one Java process to avoid starting a JVM for every search. |
| | | Each search opens a fresh connection and reads the current configuration or registrations; |
| | | responses are not cached across topology changes. If the worker exits or cannot answer within |
| | | `REPLICATION_ATTEMPT_TIMEOUT`, the join falls back to the regular `ldapsearch` command. |
| | | Set `JOIN_SEARCH_REUSE=0` to use that command for every read. With `JOIN_TIMING=1`, |
| | | `join-search` records the duration inside the worker alongside the enclosing bootstrap timings. |
| | | |
| | | ### Server roles |
| | | |
| | | `REPLICATION_ROLE` sets the part a server of `simple` takes in its topology: |
| | |
| | | the peer, so a server that joins through a `directory` server never hands it a replication |
| | | server - unless that server runs an image from before roles, whose join gives every peer one: |
| | | move every server to an image with roles before any of them takes another role than `combined`. |
| | | For a controlled scale-out after removing an RS endpoint from every directory server, |
| | | `REPLICATION_RECOVER_FROM_RS=1` on the returning `replication` server enables recovery through |
| | | ready RS peers only. It joins the administrative topology without adding its endpoint to |
| | | existing directory servers' `BASE_DN` lists, so the RS mesh can first transfer retained |
| | | changelog history. Missing or unreadable RS peers are retried; this mode never falls back to |
| | | a directory peer. The controller must verify history catch-up before restarting directory |
| | | servers with the expanded peer list. `ready` still means membership, not completed history |
| | | transfer. This mode does not repair pre-existing history gaps or protect an endpoint still |
| | | listed on live directory servers. It is off by default; ordinary bootstrap keeps configuring |
| | | the directory servers' endpoint lists as before. |
| | | |
| | | Roles may be mixed - `combined` servers with additional `directory` ones, say. Separate |
| | | replication servers on Kubernetes take two StatefulSets, one per role, with one |
| | | `REPLICATION_PEERS` that lists the pods of both, the directory servers first: |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | # dsconfig's batch parser accepts shell-style quotes but does not expand shell syntax. |
| | | join_batch_quote() { |
| | | local rest=$1 prefix |
| | | printf "'" |
| | | while [[ $rest == *"'"* ]]; do |
| | | prefix=${rest%%\'*} |
| | | printf "%s'\\\\''" "$prefix" |
| | | rest=${rest#*\'} |
| | | done |
| | | printf "%s'" "$rest" |
| | | } |
| | | |
| | | # A batch stops at its first error. If it fails, retry each change separately, including |
| | | # already-applied ones: the previous code ignored each change's error and continued. |
| | | join_batch_individual() { |
| | | while [ "$#" -ge 4 ]; do |
| | | change_replication_servers "$1" "$2" "$3" "$4" || : |
| | | shift 4 |
| | | done |
| | | } |
| | | |
| | | join_batch_changes() { # repeated <kind> <domain cn> <--add|--remove> <host:port> |
| | | local batch= command name value unsafe= |
| | | local -a changes=("$@") |
| | | [ "$#" -gt 0 ] || return 0 |
| | | [ $(( $# % 4 )) -eq 0 ] || return 1 |
| | | [ "$#" -gt 4 ] || { join_batch_individual "$@"; return; } |
| | | while [ "$#" -ge 4 ]; do |
| | | case "$1$2$3$4" in *$'\n'*|*$'\r'*) unsafe=1 ;; esac |
| | | name=$(join_batch_quote "$2") |
| | | value=$(join_batch_quote "replication-server:$4") |
| | | if [ "$1" = server ]; then |
| | | command="set-replication-server-prop --provider-name 'Multimaster Synchronization' $3 $value" |
| | | else |
| | | command="set-replication-domain-prop --provider-name 'Multimaster Synchronization' --domain-name $name $3 $value" |
| | | fi |
| | | batch="$batch$command"$'\n' |
| | | shift 4 |
| | | done |
| | | if [ -z "$unsafe" ] && dsconfig_local --batch <<<"$batch"; then return 0; fi |
| | | join_batch_individual "${changes[@]}" |
| | | } |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | # One sequential worker per join. Every request still creates a fresh LDAP connection; |
| | | # no configuration or membership result survives a request. Private FIFOs and base64 |
| | | # framing preserve empty arguments, whitespace and LDIF without evaluating their contents. |
| | | join_search_init() { |
| | | [ "${JOIN_SEARCH_REUSE:-1}" = 1 ] || return 0 |
| | | JOIN_SEARCH_DIR=$(mktemp -d "${TMPDIR:-/tmp}/opendj-join-search.XXXXXX") || return 1 |
| | | mkfifo "$JOIN_SEARCH_DIR/request" "$JOIN_SEARCH_DIR/response" || return 1 |
| | | ( |
| | | trap - EXIT |
| | | # Open both pipe ends before setup: a failed setup then produces EOF, not a |
| | | # parent blocked forever opening a FIFO which no child will ever open. |
| | | exec 7<"$JOIN_SEARCH_DIR/request" 8>"$JOIN_SEARCH_DIR/response" |
| | | INSTALL_ROOT=${JOIN_INSTALL_ROOT:-/opt/opendj} |
| | | SCRIPT_NAME=ldapsearch SCRIPT_UTIL_CMD=set-full-environment |
| | | export INSTALL_ROOT SCRIPT_NAME SCRIPT_UTIL_CMD |
| | | . "$INSTALL_ROOT/lib/_script-util.sh" || exit 1 |
| | | # Preserve the same JVM flags, class path, trust and bind behavior as bin/ldapsearch. |
| | | exec "$OPENDJ_JAVA_BIN" ${OPENDJ_JAVA_ARGS:-} ${SCRIPT_ARGS:-} ${SCRIPT_NAME_ARG:-} \ |
| | | com.forgerock.opendj.ldap.tools.BootstrapSearch <&7 >&8 7<&- 8>&- |
| | | ) & |
| | | JOIN_SEARCH_PID=$! |
| | | exec 7>"$JOIN_SEARCH_DIR/request" 8<"$JOIN_SEARCH_DIR/response" |
| | | } |
| | | |
| | | join_search_close() { |
| | | [ -n "${JOIN_SEARCH_DIR:-}" ] || return 0 |
| | | exec 7>&- 8<&- |
| | | if [ -n "${JOIN_SEARCH_PID:-}" ]; then |
| | | kill "$JOIN_SEARCH_PID" 2>/dev/null || : |
| | | wait "$JOIN_SEARCH_PID" 2>/dev/null || : |
| | | fi |
| | | rm -rf "$JOIN_SEARCH_DIR" |
| | | JOIN_SEARCH_DIR= JOIN_SEARCH_PID= |
| | | } |
| | | |
| | | join_search() { |
| | | local request status response |
| | | if [ -n "${JOIN_SEARCH_DIR:-}" ] && [ ! -e "$JOIN_SEARCH_DIR/disabled" ]; then |
| | | request=$(printf '%s\0' "$@" | PATH=/usr/bin:/bin base64 | tr -d '\n') || return 1 |
| | | # A timeout disables this worker for every later command substitution too: an |
| | | # eventual response must never be mistaken for the response to another search. |
| | | if (trap '' PIPE; printf '%s\n' "$request" >&7) \ |
| | | && IFS=' ' read -r -t "${REPLICATION_ATTEMPT_TIMEOUT:-120}" status response <&8; then |
| | | case $status in |
| | | ''|*[!0-9]*) ;; |
| | | *) |
| | | if [ "$status" -le 255 ] && printf '%s' "$response" | PATH=/usr/bin:/bin base64 -d >"$JOIN_SEARCH_DIR/result"; then |
| | | cat "$JOIN_SEARCH_DIR/result" || return 1 |
| | | return "$status" |
| | | fi |
| | | ;; |
| | | esac |
| | | fi |
| | | : >"$JOIN_SEARCH_DIR/disabled" |
| | | kill "$JOIN_SEARCH_PID" 2>/dev/null || : |
| | | fi |
| | | # An older distribution may not contain the worker. Reads are safe to retry, |
| | | # and genuine LDAP result codes above never take this fallback. |
| | | ldapsearch "$@" |
| | | } |
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # 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. |
| | | |
| | | # The descriptor survives the redirections and command substitutions of join.sh. Only |
| | | # the step name and result are logged: command arguments can contain credentials. |
| | | join_timing_init() { |
| | | [ "${JOIN_TIMING:-0}" != 1 ] || exec 9>&2 |
| | | } |
| | | |
| | | join_timed() { # <step> <command> [<argument>...] |
| | | local __join_step=$1 __join_rc |
| | | shift |
| | | if [ "${JOIN_TIMING:-0}" != 1 ]; then "$@"; return $?; fi |
| | | printf 'join-timing event=start pid=%s step=%s seconds=%s\n' "${BASHPID:-$$}" "$__join_step" "$SECONDS" >&9 || : |
| | | if "$@"; then __join_rc=0; else __join_rc=$?; fi |
| | | printf 'join-timing event=end pid=%s step=%s seconds=%s status=%s\n' "${BASHPID:-$$}" "$__join_step" "$SECONDS" "$__join_rc" >&9 || : |
| | | return "$__join_rc" |
| | | } |
| | |
| | | |
| | | cd /opt/opendj || exit 1 |
| | | export PATH=/opt/opendj/bin:$PATH |
| | | . /opt/opendj/bootstrap/join-timing.sh |
| | | . /opt/opendj/bootstrap/join-batch.sh |
| | | . /opt/opendj/bootstrap/join-search.sh |
| | | join_timing_init |
| | | |
| | | BASE_DN=${BASE_DN:-"dc=example,dc=com"} |
| | | ROOT_USER_DN=${ROOT_USER_DN:-"cn=Directory Manager"} |
| | |
| | | BOOTSTRAP_COMPLETE=${BOOTSTRAP_COMPLETE:-/opt/opendj/.bootstrap-complete} |
| | | INITIALIZE_PENDING=${INITIALIZE_PENDING:-/opt/opendj/data/.replication-initialize-pending} |
| | | REJOIN_PENDING=${REJOIN_PENDING:-/opt/opendj/data/.replication-rejoin-pending} |
| | | RESET_PENDING=${RESET_PENDING:-/opt/opendj/data/.replication-reset-pending} |
| | | # the role the volume was set up with (setup.sh), or the one a first start of this image read |
| | | # from a volume set up before roles |
| | | REPLICATION_ROLE_FILE=${REPLICATION_ROLE_FILE:-/opt/opendj/data/.replication-role} |
| | |
| | | # name, on every start - in /dev/shm those of its ADMIN_PORT, in /tmp all of them |
| | | PASSWORD_FILE=$(mktemp -p /dev/shm "opendj-join.$ADMIN_PORT.XXXXXX" 2>/dev/null \ |
| | | || mktemp "/tmp/opendj-join.$ADMIN_PORT.XXXXXX") || exit 1 |
| | | trap 'rm -f "$PASSWORD_FILE"' EXIT |
| | | trap 'join_search_close; rm -f "$PASSWORD_FILE"' EXIT |
| | | printf '%s\n' "$ROOT_PASSWORD" >"$PASSWORD_FILE" || exit 1 |
| | | join_search_init || exit 1 |
| | | |
| | | lower() { |
| | | printf '%s' "$1" | tr '[:upper:]' '[:lower:]' |
| | |
| | | search() { |
| | | local host=$1 |
| | | shift |
| | | ldapsearch --noPropertiesFile --hostname "$host" --port "$ADMIN_PORT" --useSsl --trustAll \ |
| | | join_timed "ldapsearch:$host" join_search --noPropertiesFile --hostname "$host" --port "$ADMIN_PORT" --useSsl --trustAll \ |
| | | --bindDN "$ROOT_USER_DN" --bindPasswordFile "$PASSWORD_FILE" "$@" 2>/dev/null |
| | | } |
| | | |
| | | ldapmodify_on() { # <host> [<option>...] |
| | | local host=$1 |
| | | shift |
| | | ldapmodify --noPropertiesFile --hostname "$host" --port "$ADMIN_PORT" --useSsl --trustAll \ |
| | | join_timed "ldapmodify:$host" ldapmodify --noPropertiesFile --hostname "$host" --port "$ADMIN_PORT" --useSsl --trustAll \ |
| | | --bindDN "$ROOT_USER_DN" --bindPasswordFile "$PASSWORD_FILE" "$@" 2>/dev/null |
| | | } |
| | | |
| | |
| | | } |
| | | |
| | | dsconfig_local() { |
| | | dsconfig "$@" --hostname localhost --port "$ADMIN_PORT" --bindDN "$ROOT_USER_DN" \ |
| | | join_timed "dsconfig:$1" dsconfig "$@" --hostname localhost --port "$ADMIN_PORT" --bindDN "$ROOT_USER_DN" \ |
| | | --bindPasswordFile "$PASSWORD_FILE" --trustAll --no-prompt |
| | | } |
| | | |
| | |
| | | fi |
| | | } |
| | | |
| | | server_up() { |
| | | search localhost --baseDN "" --searchScope base "(objectClass=*)" 1.1 >/dev/null |
| | | } |
| | | |
| | | # the state goes with the role of this server, after it: a peer reads the first word as the |
| | | # state, which a join of an image before roles reads alone |
| | | publish_state() { |
| | |
| | | |
| | | is_member() { |
| | | local host |
| | | # reset_if_unregistered just verified both the local configuration and |
| | | # registration. Consume that result once; subsequent checks must read afresh. |
| | | if [ "${RESET_MEMBER_CONFIRMED:-no}" = yes ]; then |
| | | RESET_MEMBER_CONFIRMED=no |
| | | JOIN_REGISTRATIONS_READY=${JOIN_REGISTRATIONS_AVAILABLE:-no} |
| | | return 0 |
| | | fi |
| | | JOIN_REGISTRATIONS_READY=no |
| | | holds_own_part || return 1 |
| | | for host in $(registered_hosts); do |
| | | is_self "$host" && return 0 |
| | |
| | | # stands - nothing else can be asked. |
| | | registered_with_peers() { |
| | | local peer host hosts config asked=no |
| | | JOIN_MEMBERSHIP_PEER= |
| | | JOIN_MEMBERSHIP_CONFIG= |
| | | for peer in "${PEERS[@]}"; do |
| | | is_self "$peer" && continue |
| | | # a replication server alone is a member only as a replication server; on a combined |
| | |
| | | hosts=$(registered_hosts "$peer") || continue |
| | | asked=yes |
| | | for host in $hosts; do |
| | | is_self "$host" && return 0 |
| | | if is_self "$host"; then |
| | | JOIN_MEMBERSHIP_PEER=$peer |
| | | JOIN_MEMBERSHIP_CONFIG=$config |
| | | return 0 |
| | | fi |
| | | done |
| | | done |
| | | [ "$asked" = no ] |
| | | } |
| | | |
| | | # The just-confirmed peer's configuration is sufficient for the advisory generation-ID |
| | | # cross-check. Consume it once and only for that peer; every other caller searches afresh. |
| | | replicates_base_dn_after_membership() { # <host> |
| | | local cached_peer=$JOIN_MEMBERSHIP_PEER cached_config=$JOIN_MEMBERSHIP_CONFIG |
| | | JOIN_MEMBERSHIP_PEER= |
| | | JOIN_MEMBERSHIP_CONFIG= |
| | | if [ -n "$cached_peer" ] && [ "$1" = "$cached_peer" ]; then |
| | | grep -qx domain <<<"$cached_config" |
| | | else |
| | | replicates_base_dn "$1" |
| | | fi |
| | | } |
| | | |
| | | member_of_topology() { |
| | | is_member && registered_with_peers |
| | | } |
| | |
| | | # decides nothing |
| | | registered_here() { |
| | | local out host |
| | | JOIN_REGISTRATIONS_AVAILABLE=no |
| | | out=$(search localhost --baseDN "cn=Servers,cn=admin data" --searchScope one "(objectClass=*)" hostname) |
| | | case $? in |
| | | 0) ;; |
| | |
| | | *) return 2 ;; |
| | | esac |
| | | for host in $(printf '%s\n' "$out" | awk 'tolower($1) == "hostname:" { print $2 }'); do |
| | | is_self "$host" && return 0 |
| | | if is_self "$host"; then |
| | | JOIN_REGISTRATIONS=$(printf '%s\n' "$out" | awk '/^dn: /{dn=substr($0,5)} tolower($1) == "hostname:" {print dn "\t" $2}') |
| | | JOIN_REGISTRATIONS_AVAILABLE=yes |
| | | return 0 |
| | | fi |
| | | done |
| | | return 1 |
| | | } |
| | |
| | | } |
| | | |
| | | release_join_lock() { # <host> <value> |
| | | local rc=0 |
| | | [ -n "$2" ] || return 0 |
| | | printf 'dn: %s\nchangetype: delete\n' "$JOIN_LOCK_DN" \ |
| | | | ldapmodify_on "$1" --assertionFilter "(description=$2)" >/dev/null \ |
| | | || echo "join: could not remove the lock on $1, it expires in $JOIN_LOCK_TTL s" |
| | | | ldapmodify_on "$1" --assertionFilter "(description=$2)" >/dev/null || rc=$? |
| | | [ "$rc" -eq 0 ] || echo "join: could not remove the lock on $1, it expires in $JOIN_LOCK_TTL s" |
| | | return "$rc" |
| | | } |
| | | |
| | | # The scale recovery path is explicit: it first connects only the RS mesh, and |
| | | # the controller later expands DS lists after verifying retained history. Unknown |
| | | # or unavailable RS peers must leave this path retrying, never fall back to a DS. |
| | | # Ordinary bootstrap retains its original peer order and directory advertisement. |
| | | join_candidates() { |
| | | local peer config state |
| | | local -a servers=() |
| | | if [ "$ROLE" = replication ] && [ "${REPLICATION_RECOVER_FROM_RS:-0}" = 1 ]; then |
| | | for peer in "${PEERS[@]}"; do |
| | | is_self "$peer" && continue |
| | | state=$(peer_state "$peer") || continue |
| | | [ "$state" = ready ] || continue |
| | | config=$(replication_config "$peer") || continue |
| | | grep -qx server <<<"$config" && servers+=("$peer") |
| | | done |
| | | [ "${#servers[@]}" -eq 0 ] || printf '%s\n' "${servers[@]}" |
| | | else |
| | | for peer in "${PEERS[@]}"; do is_self "$peer" || printf '%s\n' "$peer"; done |
| | | fi |
| | | } |
| | | |
| | | # exits 75 without running the enable while another server enables through the peer or |
| | |
| | | # dsreplication enable refuses it. The peer is read under its lock, which an enable through |
| | | # it by another server holds while it changes what the peer runs. |
| | | enable_through() { |
| | | local rc own peer_lock config role peer_args own_args |
| | | local rc own peer_lock config role state peer_args own_args |
| | | local -a enable_args=(--baseDN "$BASE_DN") |
| | | take_join_lock localhost || return 75 |
| | | own=$JOIN_LOCK_VALUE |
| | | if ! take_join_lock "$1"; then |
| | |
| | | if ! config=$(replication_config "$1"); then |
| | | echo "join: could not read how $1 replicates" |
| | | rc=75 |
| | | elif [ "$ROLE" = replication ] && [ "${REPLICATION_RECOVER_FROM_RS:-0}" = 1 ] \ |
| | | && { ! grep -qx server <<<"$config" || ! state=$(peer_state "$1") || [ "$state" != ready ]; }; then |
| | | # Recheck under the peer lock: discovery is not permission to use a peer |
| | | # which has since reset its replication or become unavailable. |
| | | echo "join: $1 is not a ready replication server, retained-history recovery will retry" |
| | | rc=75 |
| | | elif role=$(peer_role "$config") && [ "$ROLE" = directory ] && [ "$role" = directory ] \ |
| | | && [ -z "$(config_shape "$config")" ]; then |
| | | echo "join: $1 is a directory server that no replication server joined yet, and a directory server joins only through a topology that has one" |
| | | rc=75 |
| | | else |
| | | # An existing RS already serves all its domains over its RS sessions. Joining |
| | | # its administrative topology is sufficient to receive their changelogs. |
| | | # Naming BASE_DN here would also add this empty RS to every DS domain list, |
| | | # allowing lossy DS recovery to overtake the retained RS history. Directory |
| | | # peers discover the joined RS when their own bootstrap repairs their lists. |
| | | if [ "$ROLE" = replication ] && [ "${REPLICATION_RECOVER_FROM_RS:-0}" = 1 ]; then |
| | | # Suppress the schema domain that dsreplication enables by default. |
| | | enable_args=(--baseDN 'cn=admin data' --noSchemaReplication) |
| | | fi |
| | | mapfile -t peer_args < <(role_arguments 1 "$role") |
| | | mapfile -t own_args < <(role_arguments 2 "$ROLE") |
| | | bounded "$REPLICATION_ATTEMPT_TIMEOUT" dsreplication enable \ |
| | |
| | | --host2 "$MYHOSTNAME" --port2 "$ADMIN_PORT" --bindDN2 "$ROOT_USER_DN" \ |
| | | --bindPasswordFile2 "$PASSWORD_FILE" "${own_args[@]}" \ |
| | | --adminUID admin --adminPasswordFile "$PASSWORD_FILE" \ |
| | | --baseDN "$BASE_DN" -X -n |
| | | "${enable_args[@]}" -X -n |
| | | rc=$? |
| | | fi |
| | | release_join_lock "$1" "$peer_lock" |
| | |
| | | # lock while its configuration goes, so that no server enables through it then. One attempt: |
| | | # a lock another join holds leaves everything as it was, and the next round tries again. |
| | | reset_replication() { # <rejoining|pending> <why> |
| | | local dn host own |
| | | local own rc=0 remaining |
| | | echo "join: $2, taking its replication configuration down to enable it anew" |
| | | publish_state "$1" || return 1 |
| | | touch "$REJOIN_PENDING" |
| | | rm -f "$BOOTSTRAP_COMPLETE" |
| | | touch "$REJOIN_PENDING" || return 1 |
| | | rm -f "$BOOTSTRAP_COMPLETE" || return 1 |
| | | if ! take_join_lock localhost; then |
| | | echo "join: its replication configuration stays as it is until the next round" |
| | | return 1 |
| | |
| | | release_join_lock localhost "$own" |
| | | return 1 |
| | | fi |
| | | registrations | while IFS=$'\t' read -r dn host; do |
| | | [ -n "$host" ] && is_self "$host" || continue |
| | | echo "join: dropping the stale entry $dn" |
| | | unregister "$dn" || echo "join: could not remove $dn" |
| | | done |
| | | # A failed disable may already have removed BASE_DN. Persist the unfinished |
| | | # reset so the next round/start finishes it even when holds_own_part is false. |
| | | if ! touch "$RESET_PENDING"; then |
| | | release_join_lock localhost "$own" |
| | | return 1 |
| | | fi |
| | | # The local root account exists even when a partial enable left cn=admin data |
| | | # without its global administrator. --bindDN also keeps disable local: this |
| | | # repair must not edit every peer while it holds only its own join lock. |
| | | # --disableAll removes this server registration and the local admin data too. |
| | | bounded "$REPLICATION_ATTEMPT_TIMEOUT" dsreplication disable --hostname "$MYHOSTNAME" --port "$ADMIN_PORT" \ |
| | | --adminUID admin --adminPasswordFile "$PASSWORD_FILE" --disableAll -X -n \ |
| | | || echo "join: dsreplication disable exited with $?" |
| | | release_join_lock localhost "$own" |
| | | --bindDN "$ROOT_USER_DN" --adminPasswordFile "$PASSWORD_FILE" --disableAll -X -n || rc=$? |
| | | if [ "$rc" -ne 0 ]; then |
| | | echo "join: dsreplication disable exited with $rc, replication has not been reset" |
| | | else |
| | | remaining=$(search localhost --baseDN cn=config --searchScope sub \ |
| | | '(|(objectClass=ds-cfg-replication-domain)(objectClass=ds-cfg-replication-server))' 1.1) || rc=$? |
| | | if [ "$rc" -ne 0 ]; then |
| | | echo "join: could not verify replication cleanup, LDAP status $rc" |
| | | elif grep -qi '^dn:' <<<"$remaining"; then |
| | | echo "join: replication configuration remains after disable, not enabling over a partial reset" |
| | | rc=1 |
| | | fi |
| | | fi |
| | | release_join_lock localhost "$own" || { [ "$rc" -ne 0 ] || rc=1; } |
| | | if [ "$rc" -eq 0 ]; then |
| | | rm -f "$RESET_PENDING" || rc=1 |
| | | fi |
| | | return "$rc" |
| | | } |
| | | |
| | | # "<backend-id> <writability-mode>" of the backend that holds BASE_DN; the mode is left out |
| | |
| | | # left alone: nothing tells it from a server listed by name, and the list moving from |
| | | # MASTER_SERVER to REPLICATION_PEERS would otherwise throw the live master out. |
| | | cleanup_departed() { |
| | | local dn host kind cn value |
| | | local dn host kind cn value registrations_snapshot |
| | | local -a changes=() |
| | | [ "$PEERS_ARE_EXPLICIT" = yes ] || return 0 |
| | | registrations | while IFS=$'\t' read -r dn host; do |
| | | # reset_if_unregistered just read these same entries and is_member consumed its |
| | | # successful result. No topology changes occur between that check and cleanup. |
| | | if [ "${JOIN_REGISTRATIONS_READY:-no}" = yes ]; then |
| | | registrations_snapshot=$JOIN_REGISTRATIONS |
| | | JOIN_REGISTRATIONS_READY=no |
| | | else |
| | | registrations_snapshot=$(registrations) |
| | | fi |
| | | while IFS=$'\t' read -r dn host; do |
| | | [ -z "$host" ] && continue |
| | | is_address "$host" && continue |
| | | if ! in_peers "$host" && ! is_self "$host"; then |
| | | echo "join: removing departed server $host from cn=admin data" |
| | | unregister "$dn" || echo "join: could not remove $dn (already removed by another survivor?)" |
| | | fi |
| | | done |
| | | replication_server_lists | while IFS=$'\t' read -r kind cn value; do |
| | | done <<<"$registrations_snapshot" |
| | | while IFS=$'\t' read -r kind cn value; do |
| | | [ -z "$value" ] && continue |
| | | host=${value%:*} |
| | | is_address "$host" && continue |
| | | if ! in_peers "$host" && ! is_self "$host"; then |
| | | echo "join: removing departed replication server $value from the $kind list of $cn" |
| | | change_replication_servers "$kind" "$cn" --remove "$value" || true |
| | | changes+=("$kind" "$cn" --remove "$value") |
| | | fi |
| | | done |
| | | done < <(replication_server_lists) |
| | | join_batch_changes "${changes[@]}" |
| | | } |
| | | |
| | | # Adds every listed peer that is registered in the topology to each replication server list |
| | |
| | | # start. |
| | | repair_replication_servers() { |
| | | local i peer waiting hosts host lists kind cn value found config servers= |
| | | local -a changes=() |
| | | [ "$PEERS_ARE_EXPLICIT" = yes ] || return 0 |
| | | for i in $(seq 1 "$REPLICATION_RETRY_COUNT"); do |
| | | waiting= |
| | |
| | | echo "join: waiting for$waiting to register in the topology before the replication server lists are checked" |
| | | sleep "$REPLICATION_RETRY_INTERVAL" |
| | | done |
| | | hosts=$(registered_hosts) |
| | | # A successful round already contains every configured peer. Reuse it; if |
| | | # the retries expired with peers still missing, refresh once for a late join. |
| | | [ -z "$waiting" ] || hosts=$(registered_hosts) |
| | | lists=$(replication_server_lists) |
| | | # a here-string of nothing still reads as one empty line |
| | | [ -n "$lists" ] || return 0 |
| | |
| | | for host in $servers; do |
| | | if ! list_holds "$host" "$kind" "$cn" "$lists"; then |
| | | echo "join: adding replication server $host:$REPLICATION_PORT to the $kind list of $cn" |
| | | change_replication_servers "$kind" "$cn" --add "$host:$REPLICATION_PORT" || true |
| | | changes+=("$kind" "$cn" --add "$host:$REPLICATION_PORT") |
| | | fi |
| | | done |
| | | done <<<"$lists" |
| | | join_batch_changes "${changes[@]}" |
| | | } |
| | | |
| | | # whether the list of that kind and cn holds the host, in replication_server_lists output |
| | |
| | | } |
| | | |
| | | joined() { |
| | | cleanup_departed |
| | | join_timed cleanup_departed cleanup_departed |
| | | leave_rejoin || exit 1 |
| | | # a replication server published itself rejoining until now, on the ready road too |
| | | if [ "$ROLE" = replication ] && ! publish_state ready; then |
| | |
| | | fi |
| | | touch "$BOOTSTRAP_COMPLETE" |
| | | echo "join: this server is a member of the replication topology, the health check may probe it" |
| | | repair_replication_servers |
| | | join_timed repair_replication_servers repair_replication_servers |
| | | } |
| | | |
| | | # the peers learn that this server holds the data before anything else changes: a seed whose |
| | |
| | | |
| | | echo "join: waiting for the server on the administration connector" |
| | | for i in $(seq 1 150); do |
| | | server_up && own_config=$(replication_config localhost) && break |
| | | own_config=$(replication_config localhost) && break |
| | | if [ "$i" -eq 150 ]; then |
| | | echo "join: the server did not come up, or does not take ROOT_PASSWORD any more, giving up" |
| | | exit 1 |
| | |
| | | # an enable registers nobody before it. |
| | | reset_if_unregistered() { # <the state to publish meanwhile> |
| | | local rc=0 |
| | | RESET_MEMBER_CONFIRMED=no |
| | | JOIN_REGISTRATIONS_AVAILABLE=no |
| | | JOIN_REGISTRATIONS_READY=no |
| | | if [ -f "$RESET_PENDING" ]; then |
| | | reset_replication "$1" "an earlier replication reset did not finish" |
| | | return |
| | | fi |
| | | holds_own_part || return 0 |
| | | if ! registered_with_peers; then |
| | | reset_replication "$1" "the peers no longer register this server" |
| | |
| | | registered_here || rc=$? |
| | | if [ "$rc" -eq 1 ]; then |
| | | reset_replication "$1" "the peers register this server but its own cn=admin data does not" |
| | | elif [ "$rc" -eq 0 ]; then |
| | | RESET_MEMBER_CONFIRMED=yes |
| | | fi |
| | | } |
| | | |
| | |
| | | publish_state ready |
| | | fi |
| | | for i in $(seq 1 "$REPLICATION_RETRY_COUNT"); do |
| | | if ! reset_if_unregistered rejoining; then |
| | | if ! join_timed reset_if_unregistered reset_if_unregistered rejoining; then |
| | | : # the next round tries the reset again |
| | | elif is_member; then |
| | | elif join_timed is_member is_member; then |
| | | echo "join: already a member of the replication topology" |
| | | joined |
| | | exit |
| | |
| | | # an enable with any of them registers the two in a registry of their own - which counts |
| | | # as membership, a peer of the pair lists this server - beside the survivors, whom |
| | | # nothing ever adds to it |
| | | for peer in "${PEERS[@]}"; do |
| | | while IFS= read -r peer; do |
| | | is_self "$peer" && continue |
| | | state=$(peer_state "$peer") |
| | | if ! trusted "$state"; then |
| | |
| | | # a replication server holds no generation ID of BASE_DN to compare with, neither |
| | | # this one nor the peer joined through |
| | | if [ "$ROLE" != replication ]; then |
| | | replicates_base_dn "$peer" || peer=$(trusted_source) || peer= |
| | | replicates_base_dn_after_membership "$peer" || peer=$(trusted_source) || peer= |
| | | [ -z "$peer" ] || cross_check "$peer" "; replication will not flow until this server or that one is initialized by hand" |
| | | fi |
| | | joined |
| | | exit |
| | | fi |
| | | [ "$rc" -eq 75 ] || echo "join: dsreplication enable with $peer exited with $rc and membership is not there" |
| | | done |
| | | done < <(join_candidates) |
| | | fi |
| | | # a list without a single other server leaves nothing to retry against, and peers that |
| | | # all wait for data join through this one rather than the other way round |
| | |
| | | for i in $(seq 1 "$REPLICATION_RETRY_COUNT"); do |
| | | member=no |
| | | reset_due=no |
| | | if ! reset_if_unregistered pending; then |
| | | if ! join_timed reset_if_unregistered reset_if_unregistered pending; then |
| | | reset_due=yes |
| | | elif is_member; then |
| | | elif join_timed is_member is_member; then |
| | | member=yes |
| | | fi |
| | | if [ "$member" = no ] && [ "$reset_due" = no ]; then |
| | | for peer in "${PEERS[@]}"; do |
| | | while IFS= read -r peer; do |
| | | is_self "$peer" && continue |
| | | state=$(peer_state "$peer") |
| | | if ! trusted "$state"; then |
| | |
| | | break |
| | | fi |
| | | [ "$rc" -eq 75 ] || echo "join: dsreplication enable with $peer exited with $rc and membership is not there" |
| | | done |
| | | done < <(join_candidates) |
| | | fi |
| | | if [ "$member" = yes ] && [ "$ROLE" = replication ]; then |
| | | # a replication server holds no data that an initialize would bring: membership is all |
| | |
| | | # the volume holds - and a restart of a container replays this script over the writable |
| | | # layer the previous run left behind, so it is cleared before anything else. |
| | | BOOTSTRAP_COMPLETE=${BOOTSTRAP_COMPLETE:-/opt/opendj/.bootstrap-complete} |
| | | rm -f "$BOOTSTRAP_COMPLETE" |
| | | export BOOTSTRAP_FAILED=${BOOTSTRAP_FAILED:-/opt/opendj/.bootstrap-failed} |
| | | # Completion of this start is separate from health: a retained volume may serve before |
| | | # its background join repairs membership. Absence of join.sh is not completion either: |
| | | # setup runs first, and there is a gap before the background child starts. |
| | | BOOTSTRAP_FINISHED=${BOOTSTRAP_FINISHED:-/opt/opendj/.bootstrap-finished} |
| | | rm -f "$BOOTSTRAP_COMPLETE" "$BOOTSTRAP_FAILED" "$BOOTSTRAP_FINISHED" |
| | | |
| | | # A replicate.sh or a setup.sh killed before its EXIT trap ran leaves the root password in |
| | | # /dev/shm, and on Kubernetes that outlives the container: the pod keeps its /dev/shm across |
| | |
| | | [ "$OPENDJ_REPLICATION_TYPE" = "simple" ] && [ -n "${REPLICATION_PEERS:-$MASTER_SERVER}" ] |
| | | } |
| | | |
| | | # Record the background result separately from readiness: a terminal join failure |
| | | # is observable immediately, including on a volume which used to be ready. |
| | | run_join() { |
| | | local rc=0 |
| | | /opt/opendj/bootstrap/join.sh || rc=$? |
| | | if [ "$rc" -ne 0 ]; then |
| | | printf 'join:%s\n' "$rc" >"$BOOTSTRAP_FAILED" |
| | | else |
| | | touch "$BOOTSTRAP_FINISHED" || return 1 |
| | | fi |
| | | return "$rc" |
| | | } |
| | | |
| | | # Keystores and truststores mounted as a volume (a Kubernetes Secret, say) are copied into |
| | | # the instance on every start, not only on the one that bootstraps it: the instance lives on |
| | | # a persistent volume, and a renewed certificate in the Secret has to reach it. |
| | |
| | | fi |
| | | # the join also repairs membership that changed while no container ran, on every start |
| | | if join_requested; then |
| | | /opt/opendj/bootstrap/join.sh & |
| | | run_join & |
| | | else |
| | | touch "$BOOTSTRAP_FINISHED" |
| | | fi |
| | | else |
| | | echo "The upgrade did not complete, this container will not report itself healthy" |
| | |
| | | fi |
| | | if ! sh "${BOOTSTRAP}"; then |
| | | BOOTSTRAPPED=false |
| | | printf 'setup failed\n' >"$BOOTSTRAP_FAILED" |
| | | echo "$BOOTSTRAP failed, this container will not report itself healthy" |
| | | fi |
| | | |
| | |
| | | if ! join_requested && [ -n "${MASTER_SERVER}" ] && [ -n "${OPENDJ_REPLICATION_TYPE}" ]; then |
| | | if ! /opt/opendj/bootstrap/replicate.sh; then |
| | | BOOTSTRAPPED=false |
| | | printf 'replication setup failed\n' >"$BOOTSTRAP_FAILED" |
| | | echo "Replication setup failed, this container will not report itself healthy" |
| | | fi |
| | | fi |
| | |
| | | fi |
| | | if [ "$BOOTSTRAPPED" = true ]; then |
| | | if join_requested; then |
| | | /opt/opendj/bootstrap/join.sh & |
| | | run_join & |
| | | echo "The instance is bootstrapped, joining the replication topology decides whether it is healthy" |
| | | else |
| | | touch "$BOOTSTRAP_COMPLETE" |
| | | touch "$BOOTSTRAP_FINISHED" |
| | | echo "The instance is bootstrapped, the health check may probe it" |
| | | fi |
| | | fi |
| New file |
| | |
| | | /* |
| | | * 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. |
| | | */ |
| | | package org.opends.server.replication.plugin; |
| | | |
| | | import java.io.BufferedOutputStream; |
| | | import java.io.IOException; |
| | | import java.io.OutputStream; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.nio.file.Files; |
| | | import java.nio.file.Path; |
| | | import java.nio.file.Paths; |
| | | import java.util.Base64; |
| | | import java.util.Locale; |
| | | import java.util.zip.CRC32; |
| | | |
| | | import org.forgerock.i18n.LocalizableMessage; |
| | | import org.opends.server.api.ServerShutdownListener; |
| | | import org.opends.server.core.DirectoryServer; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.opends.server.replication.common.CSNGenerator; |
| | | import org.opends.server.replication.service.ReplicationDomain; |
| | | |
| | | /** Opt-in, test-only evidence of every locally allocated CSN, including failed operations. */ |
| | | final class CsnAllocationTrace |
| | | { |
| | | private static final String DIRECTORY = "org.opends.server.replication.csnTraceDirectory"; |
| | | private static final String TOKEN = "org.opends.server.replication.csnTraceToken"; |
| | | private static final String TOKEN_FILE = "org.opends.server.replication.csnTraceTokenFile"; |
| | | private static final CsnAllocationTrace ACTIVE = start(); |
| | | |
| | | private final Path path; |
| | | private final OutputStream output; |
| | | private final CRC32 checksum = new CRC32(); |
| | | private long count; |
| | | private boolean finished; |
| | | private boolean failed; |
| | | |
| | | private static CsnAllocationTrace start() |
| | | { |
| | | String directory = System.getProperty(DIRECTORY); |
| | | if (directory == null) |
| | | { |
| | | return null; |
| | | } |
| | | try |
| | | { |
| | | String token = resolveToken(System.getProperty(TOKEN, ""), System.getProperty(TOKEN_FILE)); |
| | | CsnAllocationTrace trace = new CsnAllocationTrace(Paths.get(directory), token); |
| | | // DirectoryServer runs shutdown hooks concurrently. Its listener runs after the work |
| | | // queue, replication and shutdown plugins have stopped, including offline messages. |
| | | // A crash, or a shutdown that never reaches this point, leaves no valid footer. |
| | | DirectoryServer.registerShutdownListener(new ServerShutdownListener() |
| | | { |
| | | @Override |
| | | public String getShutdownListenerName() |
| | | { |
| | | return "CSN allocation trace"; |
| | | } |
| | | |
| | | @Override |
| | | public void processServerShutdown(LocalizableMessage reason) |
| | | { |
| | | trace.finish(); |
| | | } |
| | | }); |
| | | return trace; |
| | | } |
| | | catch (IOException e) |
| | | { |
| | | throw new IllegalStateException("Cannot start the requested CSN allocation trace", e); |
| | | } |
| | | } |
| | | |
| | | static String resolveToken(String defaultToken, String tokenFile) throws IOException |
| | | { |
| | | if (tokenFile == null || Files.notExists(Paths.get(tokenFile))) |
| | | { |
| | | return defaultToken; |
| | | } |
| | | return Files.readString(Paths.get(tokenFile), StandardCharsets.US_ASCII).trim(); |
| | | } |
| | | |
| | | CsnAllocationTrace(Path directory, String token) throws IOException |
| | | { |
| | | if (!token.matches("[a-zA-Z0-9_-]+")) |
| | | { |
| | | throw new IllegalArgumentException("A CSN trace requires a generation token"); |
| | | } |
| | | Files.createDirectories(directory); |
| | | path = Files.createTempFile(directory, "trace-", ".txt"); |
| | | output = new BufferedOutputStream(Files.newOutputStream(path), 65536); |
| | | output.write(("START 1 " + token + "\n").getBytes(StandardCharsets.US_ASCII)); |
| | | output.flush(); |
| | | } |
| | | |
| | | static String domain(ReplicationDomain domain) |
| | | { |
| | | return ACTIVE != null ? encodeDomain(domain.getBaseDN().toString()) : null; |
| | | } |
| | | |
| | | static String encodeDomain(String name) |
| | | { |
| | | return Base64.getEncoder().encodeToString(name.getBytes(StandardCharsets.UTF_8)); |
| | | } |
| | | |
| | | static CSN next(CSNGenerator generator, String domain, char kind) |
| | | { |
| | | return ACTIVE != null ? ACTIVE.allocate(generator, domain, kind) : generator.newCSN(); |
| | | } |
| | | |
| | | synchronized CSN allocate(CSNGenerator generator, String domain, char kind) |
| | | { |
| | | try |
| | | { |
| | | // Mark before allocating, so even a thread stopped immediately afterwards cannot |
| | | // make a completed trace conceal an allocation made during the shutdown hooks. |
| | | if (finished) |
| | | { |
| | | output.write("AFTER-END\n".getBytes(StandardCharsets.US_ASCII)); |
| | | output.flush(); |
| | | return generator.newCSN(); |
| | | } |
| | | if (failed) |
| | | { |
| | | throw new IllegalStateException("The CSN allocation trace has failed"); |
| | | } |
| | | CSN csn = generator.newCSN(); |
| | | byte[] line = (kind + " " + domain + " " + csn + "\n").getBytes(StandardCharsets.US_ASCII); |
| | | output.write(line); |
| | | checksum.update(line); |
| | | count++; |
| | | if (count % 4096 == 0) |
| | | { |
| | | output.flush(); |
| | | } |
| | | return csn; |
| | | } |
| | | catch (IOException e) |
| | | { |
| | | failed = true; |
| | | throw new IllegalStateException("Cannot write the CSN allocation trace", e); |
| | | } |
| | | } |
| | | |
| | | synchronized void finish() |
| | | { |
| | | if (finished) |
| | | { |
| | | return; |
| | | } |
| | | finished = true; |
| | | if (failed) |
| | | { |
| | | return; |
| | | } |
| | | try |
| | | { |
| | | output.write(String.format(Locale.ROOT, "END %d %08x\n", count, checksum.getValue()) |
| | | .getBytes(StandardCharsets.US_ASCII)); |
| | | output.flush(); |
| | | } |
| | | catch (IOException e) |
| | | { |
| | | // A missing or partial footer makes the trace invalid to its consumer. |
| | | System.err.println("Cannot finish the CSN allocation trace: " + e); |
| | | } |
| | | } |
| | | |
| | | Path path() |
| | | { |
| | | return path; |
| | | } |
| | | } |
| | |
| | | { |
| | | if (rsUpdater == this) |
| | | { |
| | | rsUpdater = null; |
| | | broker.setRecoveryRequired(false); |
| | | releasePublisher(); |
| | | startTheSessionAgain = true; |
| | | } |
| | | } |
| | |
| | | } |
| | | } |
| | | |
| | | /** Called under recoveryLock. Leaving the publisher does not prove delivery. */ |
| | | private void releasePublisher() |
| | | { |
| | | rsUpdater = null; |
| | | if (pendingChanges.isRecovering()) |
| | | { |
| | | broker.recoveryAborted(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Waits before the session restart a failed run asks for: one second more for each failure in a |
| | | * row, up to ten. A session which hands its start over meanwhile ends the wait, as it is the next |
| | |
| | | { |
| | | final RecoveryStart start = nextStart; |
| | | nextStart = null; |
| | | if (start == null || shutdown.get()) |
| | | if (start == null || stopRecoveryForShutdown()) |
| | | { |
| | | // RSUpdater thread has finished its work, let's remove it from memory |
| | | // so another RSUpdater thread can be started if needed. |
| | | rsUpdater = null; |
| | | broker.setRecoveryRequired(false); |
| | | releasePublisher(); |
| | | return null; |
| | | } |
| | | return start; |
| | |
| | | @Override |
| | | protected void importBackend(InputStream input) throws DirectoryException |
| | | { |
| | | importBackend(input, () -> { }); |
| | | } |
| | | |
| | | @Override |
| | | protected void importBackend(InputStream input, ImportPreparation onPrepared) throws DirectoryException |
| | | { |
| | | LocalBackend<?> backend = getBackend(); |
| | | |
| | | LDIFImportConfig importConfig = null; |
| | |
| | | ? ERR_INIT_PREPARATION_INTERRUPTED.get(getBaseDN()) |
| | | : ERR_INIT_OPERATIONS_NOT_DRAINED.get(getBaseDN()); |
| | | logger.error(reason); |
| | | ieCtx.setExceptionIfNoneSet(new DirectoryException(ResultCode.UNAVAILABLE, reason)); |
| | | ieCtx.failImportPreparation(new DirectoryException(ResultCode.UNAVAILABLE, reason)); |
| | | return; |
| | | } |
| | | onPrepared.reportReady(); |
| | | |
| | | if (!backend.supports(BackendOperation.LDIF_IMPORT)) |
| | | { |
| | |
| | | } |
| | | } |
| | | |
| | | /** A shutdown still announcing this replica may drain the replacement within the broker stop deadline. */ |
| | | private boolean stopRecoveryForShutdown() |
| | | { |
| | | return shutdown.get() && !pendingChanges.isPublishingOffline(); |
| | | } |
| | | |
| | | /** |
| | | * Has the changes of this replica which come after the provided CSN published on the session |
| | | * which starts: starts the thread which publishes them, or hands the start over to the one which |
| | |
| | | if (replServerMisses) |
| | | { |
| | | pendingChanges.setRecovering(true); |
| | | broker.setRecoveryRequired(true); |
| | | } |
| | | else if (!pendingChanges.isRecovering()) |
| | | { |
| | | // The publisher of an earlier session ended it since it was checked. |
| | | return; |
| | | } |
| | | broker.setRecoveryRequired(true); |
| | | if (rsUpdater == null) |
| | | { |
| | | rsUpdater = new RSUpdater(start); |
| | |
| | | boolean holdBackLocalChanges = false; |
| | | while (true) |
| | | { |
| | | if (shutdown.get() || missingChanges.startHandedOver()) |
| | | if (stopRecoveryForShutdown() || missingChanges.startHandedOver()) |
| | | { |
| | | return false; |
| | | } |
| | |
| | | MissingChangesRound round = publish(fromCSN, true); |
| | | while (round != null && round.succeeded && !round.caughtUp) |
| | | { |
| | | if (shutdown.get()) |
| | | if (stopRecoveryForShutdown()) |
| | | { |
| | | return null; |
| | | } |
| | |
| | | { |
| | | for (LDAPUpdateMsg msg : recent.messages) |
| | | { |
| | | if (shutdown.get()) |
| | | if (stopRecoveryForShutdown()) |
| | | { |
| | | return null; |
| | | } |
| | |
| | | |
| | | for (FakeOperation opToSend : opsToSend.values()) |
| | | { |
| | | if (shutdown.get()) |
| | | if (stopRecoveryForShutdown()) |
| | | { |
| | | return null; |
| | | } |
| | |
| | | CSN publishedUpTo = fromCSN; |
| | | for (LDAPUpdateMsg msg : kept) |
| | | { |
| | | if (shutdown.get()) |
| | | if (stopRecoveryForShutdown()) |
| | | { |
| | | return null; |
| | | } |
| | |
| | | */ |
| | | private final CSNGenerator csnGenerator; |
| | | |
| | | /** Encoded domain for the opt-in allocation trace; null when tracing is disabled. */ |
| | | private final String csnTraceDomain; |
| | | |
| | | /** The ReplicationDomain that will be used to send UpdateMsg. */ |
| | | private final ReplicationDomain domain; |
| | | |
| | |
| | | * this list as well - and read without either by {@link #isRecovering()}. |
| | | */ |
| | | private volatile boolean recoveringOldChanges; |
| | | /** While an offline marker is on its way, later commits stay queued behind it. */ |
| | | private volatile boolean publishingOffline; |
| | | |
| | | /** What the recovery which runs keeps of the local changes: {@code null} until it first needs it. */ |
| | | private Recovery recovery; |
| | | /** How many local changes a recovery keeps at most: fewer in the tests which make it run over. */ |
| | |
| | | { |
| | | this.csnGenerator = csnGenerator; |
| | | this.domain = domain; |
| | | this.csnTraceDomain = CsnAllocationTrace.domain(domain); |
| | | this.replicaOfflineAnnouncer = replicaOfflineAnnouncer; |
| | | } |
| | | |
| | |
| | | */ |
| | | synchronized CSN putLocalOperation(PluginOperation operation) |
| | | { |
| | | final CSN csn = csnGenerator.newCSN(); |
| | | final CSN csn = CsnAllocationTrace.next(csnGenerator, csnTraceDomain, 'L'); |
| | | if (!operation.isSynchronizationOperation()) |
| | | { |
| | | pendingChanges.put(csn, new PendingChange(csn, operation, null)); |
| | |
| | | return csn; |
| | | } |
| | | |
| | | boolean isPublishingOffline() |
| | | { |
| | | return publishingOffline; |
| | | } |
| | | |
| | | /** |
| | | * Add a replica offline message to the pending list and publish it, if the changes which |
| | | * come before it have all been published. |
| | |
| | | * @return the CSN of the message which was published, or {@code null} if it could not be: |
| | | * a change which is still in flight holds it back, or the broker refused it |
| | | */ |
| | | public synchronized CSN putReplicaOfflineMsg() |
| | | public CSN putReplicaOfflineMsg() |
| | | { |
| | | final CSN offlineCSN = csnGenerator.newCSN(); |
| | | final PendingChange pendingChange = |
| | | new PendingChange(offlineCSN, null, new ReplicaOfflineMsg(offlineCSN)); |
| | | pendingChange.setCommitted(true); |
| | | final CSN offlineCSN; |
| | | synchronized (this) |
| | | { |
| | | offlineCSN = CsnAllocationTrace.next(csnGenerator, csnTraceDomain, 'O'); |
| | | pushCommittedChanges(); |
| | | if (publishingOffline || !pendingChanges.isEmpty() || recoveringOldChanges) |
| | | { |
| | | return null; |
| | | } |
| | | publishingOffline = true; |
| | | } |
| | | |
| | | pendingChanges.put(offlineCSN, pendingChange); |
| | | /* |
| | | * The message is the last change of the queue, so a push which did not reach it, or which |
| | | * the broker refused, reports another CSN or none. |
| | | */ |
| | | final boolean published = offlineCSN.equals(pushCommittedChanges()); |
| | | // pushCommittedChanges() removes whatever it reached, so the message is still listed here |
| | | // if and only if a change before it held it back - it is dropped rather than left queued. |
| | | pendingChanges.remove(offlineCSN); |
| | | return published ? offlineCSN : null; |
| | | boolean published = false; |
| | | try |
| | | { |
| | | // Announce before the socket write: a collocated RS may forward the marker immediately. |
| | | replicaOfflineAnnouncer.announce(offlineCSN); |
| | | // A replacement's recovery needs this queue to read and publish the preceding changes. |
| | | published = domain.publish(new ReplicaOfflineMsg(offlineCSN)); |
| | | return published ? offlineCSN : null; |
| | | } |
| | | finally |
| | | { |
| | | try |
| | | { |
| | | if (!published) |
| | | { |
| | | replicaOfflineAnnouncer.withdraw(offlineCSN); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | synchronized (this) |
| | | { |
| | | publishingOffline = false; |
| | | pushCommittedChanges(); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Push all committed local changes to the replicationServer service. |
| | | * |
| | | * @return the CSN of the last {@link ReplicaOfflineMsg} the replication service accepted, or |
| | | * {@code null} if none was pushed or the broker refused it. The announcement that a |
| | | * replica goes offline is the one message whose delivery the caller must know about: |
| | | * it is stored nowhere, so nothing publishes it again, while a change the broker |
| | | * refuses is republished on the next session, from the message kept of it or, once that |
| | | * is dropped, from the historical information of its entry. |
| | | */ |
| | | synchronized CSN pushCommittedChanges() |
| | | /** Push committed local changes in CSN order. */ |
| | | synchronized void pushCommittedChanges() |
| | | { |
| | | CSN publishedOfflineCSN = null; |
| | | |
| | | if (publishingOffline) |
| | | { |
| | | return; |
| | | } |
| | | // peek the oldest change |
| | | Entry<CSN, PendingChange> firstEntry = pendingChanges.firstEntry(); |
| | | if (firstEntry == null) |
| | | { |
| | | return null; |
| | | return; |
| | | } |
| | | |
| | | PendingChange firstChange = firstEntry.getValue(); |
| | |
| | | domain.getServerState().update(msg.getCSN()); |
| | | } |
| | | } |
| | | else if (msg instanceof ReplicaOfflineMsg && recoveringOldChanges) |
| | | { |
| | | /* |
| | | * The announcement carries the newest CSN of this replica, past the changes the recovery |
| | | * has still to publish: the replication server would take this replica for offline from |
| | | * there - its changelog index past the changes which reach it afterwards. It is given up |
| | | * on, as one a change in flight holds back is, whatever the broker would refuse. |
| | | */ |
| | | if (logger.isTraceEnabled()) |
| | | { |
| | | logger.trace("The announcement that the replica goes offline at " + msg.getCSN() |
| | | + " is given up on: a recovery has changes before it to publish"); |
| | | } |
| | | } |
| | | else if (msg instanceof ReplicaOfflineMsg) |
| | | { |
| | | /* |
| | | * Announce the replica offline before the message reaches the wire, and not after: |
| | | * a collocated replication server forwards it as soon as it has it, and a forward |
| | | * which finds nothing announced leaves the shutdown waiting out the whole grace |
| | | * period of a message the topology already has. |
| | | */ |
| | | final CSN offlineCSN = msg.getCSN(); |
| | | replicaOfflineAnnouncer.announce(offlineCSN); |
| | | if (domain.publish(msg)) |
| | | { |
| | | publishedOfflineCSN = offlineCSN; |
| | | } |
| | | else |
| | | { |
| | | // The broker wrote it to no session, so nobody will forward what was announced. |
| | | replicaOfflineAnnouncer.withdraw(offlineCSN); |
| | | } |
| | | } |
| | | |
| | | // false warning: firstEntry will not be null if firstChange is not null |
| | | pendingChanges.remove(firstEntry.getKey()); |
| | | pendingAtDataReload.remove(firstChange.getCSN()); |
| | |
| | | firstEntry = pendingChanges.firstEntry(); |
| | | firstChange = firstEntry != null ? firstEntry.getValue() : null; |
| | | } |
| | | return publishedOfflineCSN; |
| | | } |
| | | |
| | | /** |
| | |
| | | final LDAPUpdateMsg accepted = listed.getLDAPUpdateMsg(); |
| | | accepted.setAssured(update.isAssured()); |
| | | accepted.setAssuredMode(update.getAssuredMode()); |
| | | accepted.setAcknowledgementSender(update.getAcknowledgementSender()); |
| | | accepted.setSafeDataLevel(update.getSafeDataLevel()); |
| | | return Admission.QUEUED_DUPLICATE; |
| | | } |
| | |
| | | * waiting for them. |
| | | * <p> |
| | | * The changes another thread parked are left alone: a change is given back by the thread |
| | | * which owns it and by nobody else (issue #922). That thread may be inside the dependency |
| | | * checks which parked it - they park a change once per dependency it has - so a change |
| | | * released under it would be listed as waiting again a moment later, and handed out while |
| | | * the delivery which took it over is being replayed. |
| | | * which owns it and by nobody else (issue #922). Its replay still has the road which |
| | | * hands parked changes out, so another thread unwinding must not make them eligible for |
| | | * redelivery as well. |
| | | * |
| | | * @return the CSNs of the changes it gave back, oldest first; empty when this thread owns |
| | | * no parked change - the changes a thread parked stay its own, whichever replay |
| | |
| | | } |
| | | |
| | | /** |
| | | * Mark the first pendingChange as dependent on the second PendingChange. |
| | | * @param dependentChange The PendingChange that depend on the second |
| | | * PendingChange. |
| | | * Park a change once a dependency is found. The caller must stop scanning after this |
| | | * transfer: another thread can take the change before the next predecessor is visited. |
| | | * {@link #getNextUpdate()} waits for all earlier pending changes, so one match suffices. |
| | | * |
| | | * @param dependentChange the change which must wait for an earlier change |
| | | */ |
| | | private void addDependency(PendingChange dependentChange) |
| | | { |
| | |
| | | try |
| | | { |
| | | /* |
| | | * A change which is not listed as pending anymore - the domain was disabled while |
| | | * its dependencies were computed - must not be listed as dependent either: |
| | | * getNextUpdate() reads both and would hand out a change nothing owns. The |
| | | * replication server sends it again when the domain is enabled back. |
| | | * The scan may outlive a domain clear and a new delivery of the same CSN. It must |
| | | * still refer to the same pending change, owned by this replay thread: parking an |
| | | * old delivery or another thread's change would hand the CSN out twice. |
| | | */ |
| | | if (pendingChanges.containsKey(dependentChange.getCSN())) |
| | | if (pendingChanges.get(dependentChange.getCSN()) == dependentChange |
| | | && dependentChange.isOwnedBy(Thread.currentThread())) |
| | | { |
| | | dependentChanges.add(dependentChange); |
| | | } |
| | | /* |
| | | * Whichever of the two it was, this thread is not replaying that change anymore: a |
| | | * parked one is handed to whichever thread calls getNextUpdate() first once the |
| | | * changes before it are gone - the clearing thread as a rule, this one when the |
| | | * clearing lands before it gets there - and one which is not listed here anymore is |
| | | * gone with the pending changes of a domain which was disabled. The owner stays as it |
| | | * is - it is what has getNextUpdate() hand the change over rather than leave it to |
| | | * nobody - and the give-back of the change a replay was unwound on leaves it alone |
| | | * (issue #922). What hands a parked change back is |
| | | * This thread no longer replays a parked change or a stale one which the registration |
| | | * refused. A parked change is handed to whichever thread calls getNextUpdate() first |
| | | * once its predecessors are gone. Its owner stays as it is until that hand-off, and |
| | | * the give-back of the change a replay was unwound on leaves it alone (issue #922). |
| | | * What hands a parked change back is |
| | | * releaseParkedChangesOwnedByCurrentThread(), which unparks it in the same step so |
| | | * that the two roads can not hand it out at once (issue #954). |
| | | */ |
| | |
| | | return false; |
| | | } |
| | | |
| | | boolean hasDependencies = false; |
| | | final DN targetDN = op.getEntryDN(); |
| | | for (PendingChange pendingChange : replayDependencies) |
| | | { |
| | |
| | | if (pendingMsg.getDN().equals(targetDN)) |
| | | { |
| | | // it is a deleteOperation on the same DN |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | else if (pendingMsg instanceof AddMsg) |
| | |
| | | if (pendingMsg.getDN().isSuperiorOrEqualTo(targetDN)) |
| | | { |
| | | // it is an addOperation on a parent of the current AddOperation |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | else if (pendingMsg instanceof ModifyDNMsg) |
| | |
| | | // or a ModifyDnOperation with new DN equals to the ADD DN parent? |
| | | if (pendingMsg.getDN().equals(targetDN)) |
| | | { |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | else |
| | | { |
| | | final ModifyDNMsg pendingModDn = (ModifyDNMsg) pendingMsg; |
| | | if (pendingModDn.newDNIsParent(targetDN)) |
| | | { |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | } |
| | | } |
| | | return hasDependencies; |
| | | return false; |
| | | } |
| | | |
| | | /** |
| | |
| | | return false; |
| | | } |
| | | |
| | | boolean hasDependencies = false; |
| | | final DN targetDN = change.getLDAPUpdateMsg().getDN(); |
| | | for (PendingChange pendingChange : replayDependencies) |
| | | { |
| | |
| | | if (pendingMsg.getDN().equals(targetDN)) |
| | | { |
| | | // it is an addOperation on a same DN |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | else if (pendingMsg instanceof ModifyDNMsg) |
| | | { |
| | | if (((ModifyDNMsg) pendingMsg).newDNIsEqual(targetDN)) |
| | | { |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | else if (pendingMsg instanceof ModifyMsg) |
| | |
| | | if (pendingMsg.getDN().equals(targetDN)) |
| | | { |
| | | // it is another modify on the same DN, they depend |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | } |
| | | return hasDependencies; |
| | | return false; |
| | | } |
| | | |
| | | /** |
| | |
| | | return false; |
| | | } |
| | | |
| | | boolean hasDependencies = false; |
| | | final DN targetDN = change.getLDAPUpdateMsg().getDN(); |
| | | for (PendingChange pendingChange : replayDependencies) |
| | | { |
| | |
| | | // as the new DN of this ModifyDN |
| | | if (msg.newDNIsEqual(pendingMsg.getDN())) |
| | | { |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | else if (pendingMsg instanceof AddMsg) |
| | |
| | | // the MODDN operation |
| | | if (msg.newParentIsEqual(pendingMsg.getDN())) |
| | | { |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | // Check if the AddOperation was done on the same DN as the |
| | | // target DN of the MODDN operation |
| | | if (pendingMsg.getDN().equals(targetDN)) |
| | | { |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | else if (pendingMsg instanceof ModifyDNMsg) |
| | |
| | | if (msg.newDNIsEqual(pendingMsg.getDN())) |
| | | { |
| | | // the ModifyDNOperation was done from the new DN of the MODDN operation |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | } |
| | | return hasDependencies; |
| | | return false; |
| | | } |
| | | |
| | | /** |
| | |
| | | return false; |
| | | } |
| | | |
| | | boolean hasDependencies = false; |
| | | final DN targetDN = op.getEntryDN(); |
| | | for (PendingChange pendingChange : replayDependencies) |
| | | { |
| | |
| | | */ |
| | | if (pendingMsg.getDN().isSubordinateOrEqualTo(targetDN)) |
| | | { |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | else if (pendingMsg instanceof AddMsg) |
| | |
| | | */ |
| | | if (pendingMsg.getDN().equals(targetDN)) |
| | | { |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | else if (pendingMsg instanceof ModifyDNMsg) |
| | |
| | | */ |
| | | if (pendingMsg.getDN().isSubordinateOrEqualTo(targetDN) || pendingModDn.newDNIsParent(targetDN)) |
| | | { |
| | | hasDependencies = true; |
| | | addDependency(change); |
| | | return true; |
| | | } |
| | | } |
| | | } |
| | | return hasDependencies; |
| | | return false; |
| | | } |
| | | |
| | | /** |
| | |
| | | * |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2013-2015 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.protocol; |
| | | |
| | |
| | | /** Specifies the complementary details about the error that was detected. */ |
| | | private final LocalizableMessage details; |
| | | |
| | | /** Identifies the initialization attempt that the importer refused, if available. */ |
| | | private final String initializationAttemptId; |
| | | |
| | | /** |
| | | * The time of creation of this message. |
| | | * <p> |
| | |
| | | */ |
| | | public ErrorMsg(int sender, int destination, LocalizableMessage details) |
| | | { |
| | | this(sender, destination, details, null); |
| | | } |
| | | |
| | | /** |
| | | * Creates an error tied to the exporter's initialization attempt. |
| | | * @param sender the server that refused the import |
| | | * @param destination the exporting server |
| | | * @param details the reason for the refusal |
| | | * @param initializationAttemptId the attempt identifier from the exporter's header, or null |
| | | */ |
| | | public ErrorMsg(int sender, int destination, LocalizableMessage details, String initializationAttemptId) |
| | | { |
| | | super(sender, destination); |
| | | this.msgID = getMessageId(details); |
| | | this.details = details; |
| | | this.initializationAttemptId = initializationAttemptId; |
| | | this.creationTime = System.currentTimeMillis(); |
| | | |
| | | if (logger.isTraceEnabled()) |
| | |
| | | { |
| | | creationTime = scanner.nextLongUTF8(); |
| | | } |
| | | initializationAttemptId = version >= ProtocolVersion.REPLICATION_PROTOCOL_V9 ? scanner.nextString() : null; |
| | | } |
| | | |
| | | /** |
| | |
| | | return msgID; |
| | | } |
| | | |
| | | /** @return the refused initialization attempt identifier, or null for an uncorrelated error */ |
| | | public String getInitializationAttemptId() |
| | | { |
| | | return initializationAttemptId; |
| | | } |
| | | |
| | | // ============ |
| | | // Msg encoding |
| | | // ============ |
| | |
| | | @Override |
| | | public byte[] getBytes(short version) |
| | | { |
| | | if (initializationAttemptId != null && version < ProtocolVersion.REPLICATION_PROTOCOL_V9) |
| | | { |
| | | // A peer without the identifier could apply this refusal to a different transfer. |
| | | return null; |
| | | } |
| | | final ByteArrayBuilder builder = new ByteArrayBuilder(); |
| | | builder.appendByte(MSG_TYPE_ERROR); |
| | | builder.appendIntUTF8(senderID); |
| | |
| | | { |
| | | builder.appendLongUTF8(creationTime); |
| | | } |
| | | if (version >= ProtocolVersion.REPLICATION_PROTOCOL_V9) |
| | | { |
| | | builder.appendString(initializationAttemptId); |
| | | } |
| | | return builder.toByteArray(); |
| | | } |
| | | |
| | |
| | | * |
| | | * Copyright 2010 Sun Microsystems, Inc. |
| | | * Portions copyright 2013-2014 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.protocol; |
| | | |
| | |
| | | public class InitializeRcvAckMsg extends RoutableMsg |
| | | { |
| | | private final int numAck; |
| | | /** Identifies a preparation acknowledgement, which carries no entry credit. */ |
| | | private final String initializationAttemptId; |
| | | |
| | | /** |
| | | * Create a new message.. |
| | |
| | | */ |
| | | public InitializeRcvAckMsg(int sender, int destination, int numAck) |
| | | { |
| | | this(sender, destination, numAck, null); |
| | | } |
| | | |
| | | /** |
| | | * Acknowledges readiness to receive the entries for a particular initialization. |
| | | * @param sender the prepared importer |
| | | * @param destination the exporter |
| | | * @param initializationAttemptId the attempt identifier from the initialization header |
| | | */ |
| | | public InitializeRcvAckMsg(int sender, int destination, String initializationAttemptId) |
| | | { |
| | | this(sender, destination, 0, initializationAttemptId); |
| | | } |
| | | |
| | | private InitializeRcvAckMsg(int sender, int destination, int numAck, String initializationAttemptId) |
| | | { |
| | | super(sender, destination); |
| | | this.numAck = numAck; |
| | | this.initializationAttemptId = initializationAttemptId; |
| | | } |
| | | |
| | | /** |
| | | * Creates a new message from its encoded form. |
| | | * |
| | | * @param in The byte array containing the encoded form of the message. |
| | | * @param protocolVersion the session's negotiated protocol version |
| | | * @throws DataFormatException If the byte array does not contain a valid |
| | | * encoded form of the message. |
| | | */ |
| | | InitializeRcvAckMsg(byte[] in) throws DataFormatException |
| | | InitializeRcvAckMsg(byte[] in, short protocolVersion) throws DataFormatException |
| | | { |
| | | final ByteArrayScanner scanner = new ByteArrayScanner(in); |
| | | if (scanner.nextByte() != MSG_TYPE_INITIALIZE_RCV_ACK) |
| | |
| | | senderID = scanner.nextIntUTF8(); |
| | | destination = scanner.nextIntUTF8(); |
| | | numAck = scanner.nextIntUTF8(); |
| | | initializationAttemptId = protocolVersion >= ProtocolVersion.REPLICATION_PROTOCOL_V9 ? scanner.nextString() : null; |
| | | } |
| | | |
| | | /** {@inheritDoc} */ |
| | | @Override |
| | | public byte[] getBytes(short protocolVersion) |
| | | { |
| | | if (initializationAttemptId != null && protocolVersion < ProtocolVersion.REPLICATION_PROTOCOL_V9) |
| | | { |
| | | return null; |
| | | } |
| | | final ByteArrayBuilder builder = new ByteArrayBuilder(); |
| | | builder.appendByte(MSG_TYPE_INITIALIZE_RCV_ACK); |
| | | builder.appendIntUTF8(senderID); |
| | | builder.appendIntUTF8(destination); |
| | | builder.appendIntUTF8(numAck); |
| | | if (protocolVersion >= ProtocolVersion.REPLICATION_PROTOCOL_V9) |
| | | { |
| | | builder.appendString(initializationAttemptId); |
| | | } |
| | | return builder.toByteArray(); |
| | | } |
| | | |
| | |
| | | { |
| | | return numAck; |
| | | } |
| | | |
| | | /** @return the preparation acknowledgement's attempt identifier, or null for an entry acknowledgement */ |
| | | public String getInitializationAttemptId() |
| | | { |
| | | return initializationAttemptId; |
| | | } |
| | | } |
| | |
| | | * |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2013-2016 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.protocol; |
| | | |
| | |
| | | |
| | | private int initWindow; |
| | | |
| | | /** Identifier supplied by the exporter for this initialization attempt, if available. */ |
| | | private final String initializationAttemptId; |
| | | |
| | | /** |
| | | * Creates a InitializeTargetMsg. |
| | | * |
| | |
| | | public InitializeTargetMsg(DN baseDN, int serverID, |
| | | int destination, int requestorID, long entryCount, int initWindow) |
| | | { |
| | | this(baseDN, serverID, destination, requestorID, entryCount, initWindow, null); |
| | | } |
| | | |
| | | /** |
| | | * Creates the header of an initialization that can accept a correlated preparation refusal. |
| | | * @param baseDN the replicated suffix |
| | | * @param serverID the exporting server |
| | | * @param destination the importing server |
| | | * @param requestorID the server initiating the export |
| | | * @param entryCount the count of entries to export |
| | | * @param initWindow the initialization window |
| | | * @param initializationAttemptId the exporter-assigned attempt identifier, or null |
| | | */ |
| | | public InitializeTargetMsg(DN baseDN, int serverID, int destination, int requestorID, |
| | | long entryCount, int initWindow, String initializationAttemptId) |
| | | { |
| | | super(serverID, destination); |
| | | this.requestorID = requestorID; |
| | | this.baseDN = baseDN; |
| | | this.entryCount = entryCount; |
| | | this.initWindow = initWindow; // V4 |
| | | this.initializationAttemptId = initializationAttemptId; |
| | | } |
| | | |
| | | /** |
| | |
| | | { |
| | | initWindow = scanner.nextIntUTF8(); |
| | | } |
| | | initializationAttemptId = version >= ProtocolVersion.REPLICATION_PROTOCOL_V9 ? scanner.nextString() : null; |
| | | } |
| | | |
| | | /** |
| | |
| | | return this.initWindow; |
| | | } |
| | | |
| | | /** @return the exporter-assigned attempt identifier, or null for an uncorrelated header */ |
| | | public String getInitializationAttemptId() |
| | | { |
| | | return initializationAttemptId; |
| | | } |
| | | |
| | | // ============ |
| | | // Msg encoding |
| | | // ============ |
| | |
| | | { |
| | | builder.appendIntUTF8(initWindow); |
| | | } |
| | | if (version >= ProtocolVersion.REPLICATION_PROTOCOL_V9) |
| | | { |
| | | builder.appendString(initializationAttemptId); |
| | | } |
| | | return builder.toByteArray(); |
| | | } |
| | | |
| | |
| | | * |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2011-2015 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.protocol; |
| | | |
| | |
| | | */ |
| | | public static final short REPLICATION_PROTOCOL_V8 = 8; |
| | | |
| | | /** Correlates import preparation acknowledgements and refusals with their initialization headers. */ |
| | | public static final short REPLICATION_PROTOCOL_V9 = 9; |
| | | |
| | | /** |
| | | * The replication protocol version used by the instance of RS/DS in this VM. |
| | | */ |
| | | private static final short CURRENT_VERSION = REPLICATION_PROTOCOL_V8; |
| | | private static final short CURRENT_VERSION = REPLICATION_PROTOCOL_V9; |
| | | |
| | | /** |
| | | * Gets the current version of the replication protocol. |
| | |
| | | |
| | | import org.forgerock.i18n.slf4j.LocalizedLogger; |
| | | import org.forgerock.opendj.config.server.ConfigException; |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.opends.server.core.DirectoryServer; |
| | | import org.opends.server.types.CryptoManager; |
| | | import org.opends.server.util.FailureLogThrottle; |
| | |
| | | |
| | | private static final String REPLICATION_CLIENT_NAME = "Replication Client"; |
| | | |
| | | private static final String TRACE_TLS_FAILURES = "org.opends.server.replication.traceTlsFailures"; |
| | | |
| | | private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass(); |
| | | |
| | | /** |
| | |
| | | public Session createClientSession(final Socket socket, |
| | | final int soTimeout) throws ConfigException, IOException |
| | | { |
| | | return createClientSession(socket, soTimeout, null, 0, null); |
| | | } |
| | | |
| | | /** |
| | | * Creates a client session with optional per-attempt TLS diagnostics. The |
| | | * diagnostic records the socket endpoints before closing the socket, even |
| | | * if the caller has already reported the outage. |
| | | * |
| | | * @param socket |
| | | * The connected socket. |
| | | * @param soTimeout |
| | | * The socket timeout option. |
| | | * @param role |
| | | * The client role (DS or RS). |
| | | * @param serverId |
| | | * The client ID for the attempted session. |
| | | * @param baseDN |
| | | * The domain for the attempted session, or null to omit diagnostics. |
| | | * @return The new protocol session. |
| | | * @throws ConfigException |
| | | * If the session configuration is invalid. |
| | | * @throws IOException |
| | | * If the session cannot be established. |
| | | */ |
| | | public Session createClientSession(final Socket socket, final int soTimeout, |
| | | final String role, final int serverId, final DN baseDN) throws ConfigException, IOException |
| | | { |
| | | boolean hasCompleted = false; |
| | | SSLSocket secureSocket = null; |
| | | |
| | |
| | | hasCompleted = true; |
| | | return new Session(socket, secureSocket); |
| | | } |
| | | catch (final SSLException e) |
| | | { |
| | | if (baseDN != null && Boolean.getBoolean(TRACE_TLS_FAILURES)) |
| | | { |
| | | logger.info(NOTE_REPLICATION_TLS_CLIENT_FAILURE, role, serverId, baseDN, |
| | | socket.getLocalSocketAddress(), socket.getRemoteSocketAddress()); |
| | | } |
| | | throw e; |
| | | } |
| | | finally |
| | | { |
| | | if (!hasCompleted) |
| | |
| | | case MSG_TYPE_STOP: |
| | | return new StopMsg(buffer); |
| | | case MSG_TYPE_INITIALIZE_RCV_ACK: |
| | | return new InitializeRcvAckMsg(buffer); |
| | | return new InitializeRcvAckMsg(buffer, protocolVersion); |
| | | case MSG_TYPE_REPLICA_OFFLINE: |
| | | return new ReplicaOfflineMsg(buffer); |
| | | default: |
| | |
| | | import java.net.Socket; |
| | | import java.net.SocketException; |
| | | import java.util.concurrent.CountDownLatch; |
| | | import java.util.concurrent.Executor; |
| | | import java.util.concurrent.LinkedBlockingQueue; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | |
| | | */ |
| | | private final Object stateLock = new Object(); |
| | | private volatile boolean closeInitiated; |
| | | /** A planned switch can leave the socket open for reads after its last write. */ |
| | | private volatile boolean closingForSwitch; |
| | | /** Set under publishLock before the switch writes its final frames. */ |
| | | private volatile boolean switchWritesEnded; |
| | | private volatile boolean socketCloseRequested; |
| | | private Throwable sessionError; |
| | | |
| | | /** |
| | |
| | | @Override |
| | | public void close() |
| | | { |
| | | close(false); |
| | | close(false, null, false); |
| | | } |
| | | |
| | | /** |
| | | * Closes the session, as {@link #close()} or as {@link #abort(IOException)} does. |
| | | * A planned switch allows time for the stop exchange and for the peer's queue to drain. |
| | | * |
| | | * @param abort |
| | | * whether the sockets are to be closed at once, before anything waits for the |
| | | * publisher thread or for {@code publishLock} - even when a close had begun already |
| | | * @param connectionTimeoutMillis the configured connection timeout |
| | | * @return the maximum time to wait for the old session to finish |
| | | */ |
| | | private void close(final boolean abort) |
| | | public static long plannedSwitchTimeoutMillis(int connectionTimeoutMillis) |
| | | { |
| | | Throwable localSessionError; |
| | | final boolean closing; |
| | | final long timeout = connectionTimeoutMillis > 0 ? connectionTimeoutMillis : DRAIN_BUDGET_MS; |
| | | return 2 * timeout + DRAIN_BUDGET_MS; |
| | | } |
| | | |
| | | /** |
| | | * Stops admitting ordinary publications before scheduling the final write. The broker |
| | | * stays on the receiver and closes this session on the peer's reply or aborts |
| | | * it at its deadline. |
| | | * |
| | | * @param sender executor for the remaining writes and the StopMsg |
| | | * @return whether the session entered the switch |
| | | */ |
| | | public boolean closeForSwitch(Executor sender) |
| | | { |
| | | synchronized (stateLock) |
| | | { |
| | | closing = closeInitiated; |
| | | localSessionError = sessionError; |
| | | if (closeInitiated) |
| | | { |
| | | return false; |
| | | } |
| | | closingForSwitch = true; |
| | | closeInitiated = true; |
| | | } |
| | | if (abort) |
| | | sender.execute(() -> finishClose(true)); |
| | | return true; |
| | | } |
| | | |
| | | /** Returns whether ordinary publication has ended for a planned switch. */ |
| | | public boolean isClosingForSwitch() |
| | | { |
| | | return closingForSwitch; |
| | | } |
| | | |
| | | /** Returns whether the local side requested closing the socket, including an abort. */ |
| | | public boolean isSocketCloseRequested() |
| | | { |
| | | return socketCloseRequested; |
| | | } |
| | | |
| | | /** |
| | | * @param abort whether to close the sockets before waiting for any writer |
| | | * @param cause the session failure, if any |
| | | * @param heartbeatExpired whether a planned switch can take ownership of the timeout |
| | | * @return whether the close was accepted |
| | | */ |
| | | private boolean close(final boolean abort, final IOException cause, final boolean heartbeatExpired) |
| | | { |
| | | final boolean closing; |
| | | synchronized (stateLock) |
| | | { |
| | | if (heartbeatExpired && closingForSwitch) |
| | | { |
| | | return false; |
| | | } |
| | | if (cause != null && sessionError == null) |
| | | { |
| | | sessionError = cause; |
| | | } |
| | | socketCloseRequested = true; |
| | | closing = closeInitiated; |
| | | closeInitiated = true; |
| | | } |
| | | if (abort || closing && closingForSwitch) |
| | | { |
| | | StaticUtils.close(plainSocket, secureSocket); |
| | | } |
| | | if (closing) |
| | | if (!closing) |
| | | { |
| | | return; |
| | | finishClose(false); |
| | | } |
| | | return true; |
| | | } |
| | | |
| | | private void finishClose(final boolean awaitReply) |
| | | { |
| | | Throwable localSessionError; |
| | | |
| | | try { |
| | | interrupt(); |
| | |
| | | publishLock.lock(); |
| | | try |
| | | { |
| | | switchWritesEnded = awaitReply; |
| | | isRunning.set(false); |
| | | sendWhatThePublisherLeftQueued(); |
| | | |
| | |
| | | { |
| | | try |
| | | { |
| | | publish(new StopMsg()); |
| | | send(new StopMsg().getBytes(protocolVersion)); |
| | | if (awaitReply) |
| | | { |
| | | return; |
| | | } |
| | | } |
| | | catch (final IOException ignored) |
| | | { |
| | |
| | | */ |
| | | public void abort(final IOException cause) |
| | | { |
| | | setSessionError(cause); |
| | | close(true); |
| | | close(true, cause, false); |
| | | } |
| | | |
| | | /** A planned switch uses its own deadline while the peer drains and stops sending heartbeats. */ |
| | | public boolean abortOnHeartbeatTimeout(final IOException cause) |
| | | { |
| | | return close(true, cause, true); |
| | | } |
| | | |
| | | |
| | |
| | | * The whole queue goes out under {@code publishLock}, because the publisher is not the only |
| | | * thread which writes this socket: a {@code ServerWriter} is joined only after the close which |
| | | * gets here (ServerHandler.shutdown() closes the session before joining it, and ServerReader's |
| | | * finally closes it before stopping the handler), and a {@code HeartbeatThread} is shut down |
| | | * after it too. Their {@code publish()} takes the synchronous branch once the session is off |
| | | * the queueing one, so without the lock a newer message could be written between two of these |
| | | * older ones - which a peer replication server answers by dropping the older ones at debug |
| | | * finally closes it before stopping the handler), and a {@code HeartbeatThread} may still be |
| | | * publishing when its shutdown is requested. Their {@code publish()} takes the synchronous |
| | | * branch once the session is off the queueing one, so without the lock a newer message could be |
| | | * written between two of these older ones - which a peer replication server answers by dropping them at debug |
| | | * level, its log file refusing a record which would break its key ordering. The close takes |
| | | * the session off the queueing branch under the same lock it holds here, so such a |
| | | * {@code publish()} either queues ahead of that and is drained here, or waits for the drain and |
| | |
| | | * this session is not. The budget is per close, and a shutdown closes its sessions one after |
| | | * another - ReplicationServerDomain.stopAllServers() stops each handler in turn on one thread - |
| | | * so a domain with several peers which are alive and not reading pays it once per such peer. |
| | | * On the road which does not shut the whole server down the wait is paid under the lock of the |
| | | * replication domain - ReplicationServerDomain.stopServer() holds it across the handler |
| | | * shutdown which closes this session - where a handshake meanwhile waiting on that lock times |
| | | * out and the broker retries. What is given up on is reported rather than dropped in silence, |
| | | * Runtime peer teardown releases the replication domain lock before closing this session, |
| | | * so this drain does not hold up another peer's handshake on the live server. |
| | | * What is given up on is reported rather than dropped in silence, |
| | | * that being the part of this which cost the most to diagnose. |
| | | */ |
| | | private void sendWhatThePublisherLeftQueued() |
| | |
| | | */ |
| | | public boolean publish(final ReplicationMsg msg, final Runnable whenWritten) throws IOException |
| | | { |
| | | if (refusedDuringSwitch(msg)) |
| | | { |
| | | return false; |
| | | } |
| | | final byte[] buffer = msg.getBytes(protocolVersion); |
| | | if (buffer == null) |
| | | { |
| | |
| | | } |
| | | return false; |
| | | } |
| | | send(buffer); |
| | | written(whenWritten); |
| | | return true; |
| | | if (send(buffer, msg)) |
| | | { |
| | | written(whenWritten); |
| | | return true; |
| | | } |
| | | return false; |
| | | } |
| | | |
| | | /** Runs what was to run once a message is written; a callback which fails takes nothing down. */ |
| | |
| | | */ |
| | | private void send(final byte[] buffer) throws IOException |
| | | { |
| | | send(buffer, null); |
| | | } |
| | | |
| | | /** Writes a frame, checking admission for a new synchronous publication under the write lock. */ |
| | | private boolean send(final byte[] buffer, final ReplicationMsg publication) throws IOException |
| | | { |
| | | final String str = String.format("%08x", buffer.length); |
| | | final byte[] sendLengthBuf = str.getBytes(); |
| | | |
| | | publishLock.lock(); |
| | | if (publication != null) |
| | | { |
| | | if (!lockForPublication(publication)) |
| | | { |
| | | return false; |
| | | } |
| | | } |
| | | else |
| | | { |
| | | publishLock.lock(); |
| | | } |
| | | try |
| | | { |
| | | if (publication != null && refusedDuringSwitch(publication)) |
| | | { |
| | | return false; |
| | | } |
| | | /* |
| | | * The buffered output stream ensures that the message is usually sent as |
| | | * a single TCP packet. |
| | |
| | | } |
| | | |
| | | lastPublishTime = System.currentTimeMillis(); |
| | | return true; |
| | | } |
| | | |
| | | |
| | | |
| | | private boolean refusedDuringSwitch(ReplicationMsg msg) |
| | | { |
| | | // The peer still reads replay acknowledgements and the shutdown announcement until StopMsg. |
| | | return closingForSwitch && (switchWritesEnded || socketCloseRequested |
| | | || !(msg instanceof AckMsg || msg instanceof ReplicaOfflineMsg)); |
| | | } |
| | | |
| | | /** |
| | | * A publication that began waiting before a switch must be able to leave |
| | | * without acquiring the lock held by the final write. Replay can hold the |
| | | * broker's receive-window monitor while publishing a credit. |
| | | */ |
| | | private boolean lockForPublication(ReplicationMsg publication) |
| | | { |
| | | if (publishLock.tryLock()) |
| | | { |
| | | return true; |
| | | } |
| | | boolean interrupted = false; |
| | | try |
| | | { |
| | | while (!refusedDuringSwitch(publication)) |
| | | { |
| | | try |
| | | { |
| | | if (publishLock.tryLock(100, TimeUnit.MILLISECONDS)) |
| | | { |
| | | return true; |
| | | } |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | interrupted = true; |
| | | } |
| | | } |
| | | return false; |
| | | } |
| | | finally |
| | | { |
| | | if (interrupted) |
| | | { |
| | | Thread.currentThread().interrupt(); |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Attempt to receive a ReplicationMsg. |
| | | * This method should block the calling thread until a |
| | |
| | | * |
| | | * Copyright 2006-2009 Sun Microsystems, Inc. |
| | | * Portions Copyright 2013-2015 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.protocol; |
| | | |
| | |
| | | /** True when the update must use assured replication. */ |
| | | protected boolean assuredFlag; |
| | | |
| | | /** Sends a replay acknowledgement to the RS session that requested it. */ |
| | | @FunctionalInterface |
| | | public interface AcknowledgementSender |
| | | { |
| | | /** Returns whether the session accepted the acknowledgement. */ |
| | | boolean send(AckMsg acknowledgement); |
| | | } |
| | | |
| | | /** Local to the receiving DS. Never encoded or forwarded. */ |
| | | private AcknowledgementSender acknowledgementSender; |
| | | |
| | | /** When assuredFlag is true, defines the requested assured mode. */ |
| | | protected AssuredMode assuredMode = AssuredMode.SAFE_DATA_MODE; |
| | | |
| | |
| | | return csn; |
| | | } |
| | | |
| | | /** Returns the reply path for this delivery, or null if no reply was requested from this DS. */ |
| | | public AcknowledgementSender getAcknowledgementSender() |
| | | { |
| | | return acknowledgementSender; |
| | | } |
| | | |
| | | /** Records where this delivery must be acknowledged after replay. */ |
| | | public void setAcknowledgementSender(AcknowledgementSender sender) |
| | | { |
| | | acknowledgementSender = sender; |
| | | } |
| | | |
| | | /** |
| | | * Get a boolean indicating if the Update must be processed as an |
| | | * Asynchronous or as an assured replication. |
| | |
| | | } |
| | | |
| | | /** |
| | | * Returns the newest update of this replica deliberately not handed to this queue. |
| | | * RS handlers use domain-wide peer receipts so a newly registered handler sees |
| | | * updates whose publication began before it registered. |
| | | * |
| | | * @param serverId the replica which produced the update |
| | | * @return its newest unqueued update, or {@code null} when none is known |
| | | */ |
| | | protected CSN getLatestUnqueuedUpdate(int serverId) |
| | | { |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * Whether the consumer has every change the queue may lack which the changelog still holds - see |
| | | * {@link #queueLacksUpTo} and {@link #consumerLacksFromTheChangelog(CSN, ServerState)}. |
| | | * <p> |
| | |
| | | { |
| | | replicationServerDomain = replicationServer.getReplicationServerDomain( |
| | | baseDN, true); |
| | | if (waitConnections) |
| | | // Let a bootstrapping domain learn its generation and topology before accepting |
| | | // a DS. A domain already serving a DS must be able to accept another while the |
| | | // connect thread is waiting for a peer RS. |
| | | if (waitConnections && (replicationServerDomain.getGenerationId() <= 0 |
| | | || replicationServerDomain.getConnectedDSs().isEmpty())) |
| | | { |
| | | replicationServer.waitConnections(); |
| | | } |
| | |
| | | */ |
| | | continue; |
| | | } |
| | | // A replica may have written through a peer since this queue was last used. |
| | | // Its next direct write must not advance our cursor past that unqueued prefix. |
| | | // Other replicas keep following normally: an RS does not relay idle peer traffic. |
| | | final CSN next = msgQueue.first().getCSN(); |
| | | final CSN unqueued = getLatestUnqueuedUpdate(next.getServerId()); |
| | | if (unqueued != null && !serverState.cover(next) && !serverState.cover(unqueued) |
| | | && consumerLacksFromTheChangelog(unqueued, replicationServerDomain.getLatestServerState())) |
| | | { |
| | | following = false; |
| | | continue; |
| | | } |
| | | UpdateMsg msg = msgQueue.removeFirst(); |
| | | if (updateServerState(msg)) |
| | | { |
| | |
| | | * |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2011-2016 ForgeRock AS. |
| | | * Portions Copyrighted 2026 3A Systems, LLC. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.server; |
| | | |
| | |
| | | throw new ConnectException("Connection to " + remoteServerAddress |
| | | + " is a TCP self-connect, no replication server is listening"); |
| | | } |
| | | session = replSessionSecurity.createClientSession(socket, timeoutMS); |
| | | session = replSessionSecurity.createClientSession(socket, timeoutMS, "RS", getServerId(), baseDN); |
| | | |
| | | ReplicationServerHandler rsHandler = new ReplicationServerHandler( |
| | | session, config.getQueueSize(), this, config.getWindowSize()); |
| | |
| | | listenThread.interrupt(); |
| | | } |
| | | |
| | | // Remote DSs may still write while this RS stops. End their readers first, then |
| | | // drain those accepted updates while the peer writers and their sessions remain up. |
| | | // Unlike a collocated DS, they need not send a ReplicaOfflineMsg at this shutdown. |
| | | for (ReplicationServerDomain domain : getReplicationServerDomains()) |
| | | { |
| | | domain.stopDirectoryServers(); |
| | | } |
| | | try |
| | | { |
| | | awaitDirectUpdatesForwarded(TimeUnit.SECONDS.toNanos(30)); |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | Thread.currentThread().interrupt(); |
| | | } |
| | | |
| | | for (ReplicationServerDomain domain : getReplicationServerDomains()) |
| | | { |
| | | domain.shutdown(); |
| | |
| | | allInstances.remove(this); |
| | | } |
| | | |
| | | /** Waits for all domains within one direct-update forwarding budget. */ |
| | | void awaitDirectUpdatesForwarded(long timeoutNanos) throws InterruptedException |
| | | { |
| | | final long deadline = System.nanoTime() + timeoutNanos; |
| | | for (ReplicationServerDomain domain : getReplicationServerDomains()) |
| | | { |
| | | domain.awaitDirectUpdatesForwarded(deadline); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Waits for the ReplicaOfflineMsg of every domain which has a replication server to forward it |
| | | * to. With no such server connected there is nobody to forward the message to, and waiting |
| | |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.atomic.AtomicReference; |
| | | import java.util.concurrent.locks.ReentrantLock; |
| | | import java.util.concurrent.locks.ReentrantReadWriteLock; |
| | | |
| | | import net.jcip.annotations.GuardedBy; |
| | | |
| | |
| | | import org.forgerock.opendj.ldap.ResultCode; |
| | | import org.opends.server.api.MonitorData; |
| | | import org.forgerock.opendj.server.config.server.MonitorProviderCfg; |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.opends.server.api.MonitorProvider; |
| | | import org.opends.server.core.DirectoryServer; |
| | | import org.opends.server.replication.common.CSN; |
| | |
| | | import org.opends.server.replication.protocol.ChangeStatusMsg; |
| | | import org.opends.server.replication.protocol.ChangeTimeHeartbeatMsg; |
| | | import org.opends.server.replication.protocol.ErrorMsg; |
| | | import org.opends.server.replication.protocol.InitializeRcvAckMsg; |
| | | import org.opends.server.replication.protocol.MonitorMsg; |
| | | import org.opends.server.replication.protocol.MonitorRequestMsg; |
| | | import org.opends.server.replication.protocol.ReplicaOfflineMsg; |
| | |
| | | import org.opends.server.replication.server.changelog.api.DBCursor; |
| | | import org.opends.server.replication.server.changelog.api.DBCursor.CursorOptions; |
| | | import org.opends.server.replication.server.changelog.api.ReplicationDomainDB; |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.opends.server.replication.service.DSRSShutdownSync.ForwardingPeer; |
| | | import org.opends.server.types.DirectoryException; |
| | | import org.opends.server.types.HostPort; |
| | | |
| | |
| | | |
| | | private final Object pendingStatusMessagesLock = new Object(); |
| | | |
| | | /** Changes accepted directly from DSs, which this RS owes to every peer in the mesh. */ |
| | | private final ServerState directUpdates = new ServerState(); |
| | | /** Peer history persisted without being queued to other RSs, including ones registering meanwhile. */ |
| | | private final ServerState peerUpdates = new ServerState(); |
| | | /** Covers puts whose DS handler may already have been removed by concurrent teardown. */ |
| | | private final ReentrantReadWriteLock directUpdateLock = new ReentrantReadWriteLock(); |
| | | private volatile boolean acceptDirectUpdates = true; |
| | | |
| | | @GuardedBy("pendingStatusMessagesLock") |
| | | private PendingStatusMessages pendingStatusMessages = new PendingStatusMessages(); |
| | | |
| | |
| | | */ |
| | | public void put(UpdateMsg updateMsg, ServerHandler sourceHandler) throws IOException |
| | | { |
| | | sourceHandler.updateServerState(updateMsg); |
| | | try |
| | | { |
| | | if (sourceHandler.isDataServer()) |
| | | { |
| | | putDirectUpdate(updateMsg, sourceHandler); |
| | | } |
| | | else |
| | | { |
| | | putUpdate(updateMsg, sourceHandler); |
| | | } |
| | | } |
| | | catch (ChangelogException e) |
| | | { |
| | | // A fatal changelog failure closes every connection. The shutdown drain needs |
| | | // the write lock on this domain, so the publisher must release its read lock first. |
| | | logger.error(ERR_CHANGELOG_SHUTDOWN_DATABASE_ERROR, stackTraceToSingleLineString(e)); |
| | | localReplicationServer.shutdown(); |
| | | } |
| | | } |
| | | |
| | | private void putDirectUpdate(UpdateMsg updateMsg, ServerHandler sourceHandler) throws IOException, ChangelogException |
| | | { |
| | | directUpdateLock.readLock().lock(); |
| | | try |
| | | { |
| | | if (!acceptDirectUpdates) |
| | | { |
| | | // Do not advance the source state or accept a late read after the shutdown fence. |
| | | throw new IOException("Replication server is closing its directory connections"); |
| | | } |
| | | putUpdate(updateMsg, sourceHandler); |
| | | } |
| | | finally |
| | | { |
| | | directUpdateLock.readLock().unlock(); |
| | | } |
| | | } |
| | | |
| | | private void putUpdate(UpdateMsg updateMsg, ServerHandler sourceHandler) throws IOException, ChangelogException |
| | | { |
| | | final long sourceGenerationId = sourceHandler.getGenerationId(); |
| | | sourceHandler.recordReceivedUpdate(updateMsg); |
| | | sourceHandler.incrementInCount(); |
| | | /* |
| | | * A directory server which already has changes does not give its generation id at the handshake to a |
| | |
| | | */ |
| | | final PreparedAssuredInfo preparedAssuredInfo = getPreparedAssuredInfo(updateMsg, sourceHandler); |
| | | |
| | | if (!publishUpdateMsg(updateMsg)) |
| | | if (!sourceHandler.isDataServer() && updateMsg.contributesToDomainState()) |
| | | { |
| | | return; |
| | | // Record before publication, independently of the current handler set: |
| | | // a peer can register while this update is being written to the changelog. |
| | | synchronized (generationIDLock) |
| | | { |
| | | if (generationId == sourceGenerationId) |
| | | { |
| | | peerUpdates.update(updateMsg.getCSN()); |
| | | } |
| | | } |
| | | } |
| | | |
| | | publishUpdateMsg(updateMsg); |
| | | |
| | | final List<Integer> assuredServers = getAssuredServers(updateMsg, preparedAssuredInfo); |
| | | |
| | | /** |
| | |
| | | // Push the message to the replication servers |
| | | if (sourceHandler.isDataServer()) |
| | | { |
| | | if (updateMsg.contributesToDomainState()) |
| | | { |
| | | synchronized (generationIDLock) |
| | | { |
| | | if (generationId == sourceGenerationId) |
| | | { |
| | | directUpdates.update(updateMsg.getCSN()); |
| | | } |
| | | } |
| | | } |
| | | if (updateMsg instanceof ReplicaOfflineMsg) |
| | | { |
| | | pushReplicaOfflineMsgToReplicationServers( |
| | |
| | | NotAssuredUpdateMsg notAssuredUpdateMsg, List<Integer> assuredServers) |
| | | { |
| | | final List<ReplicationServerHandler> recipients = new ArrayList<>(connectedRSs.size()); |
| | | final List<Integer> recipientIds = new ArrayList<>(connectedRSs.size()); |
| | | final List<ForwardingPeer> forwarders = new ArrayList<>(connectedRSs.size()); |
| | | for (ReplicationServerHandler rsHandler : connectedRSs.values()) |
| | | { |
| | | // Ignore updates to RS with bad gen id (no system managed status for a RS) |
| | | if (!isDifferentGenerationId(rsHandler, offlineMsg)) |
| | | { |
| | | recipients.add(rsHandler); |
| | | recipientIds.add(rsHandler.getServerId()); |
| | | forwarders.add(rsHandler.offlineForwarder()); |
| | | } |
| | | } |
| | | localReplicationServer.getDSRSShutdownSync() |
| | | .replicaOfflineMsgDispatched(baseDN, offlineMsg.getCSN(), recipientIds); |
| | | .replicaOfflineMsgDispatched(baseDN, offlineMsg.getCSN(), forwarders); |
| | | for (ReplicationServerHandler rsHandler : recipients) |
| | | { |
| | | /* |
| | |
| | | return expectedServers != null ? expectedServers : Collections.<Integer> emptyList(); |
| | | } |
| | | |
| | | private boolean publishUpdateMsg(UpdateMsg updateMsg) |
| | | private void publishUpdateMsg(UpdateMsg updateMsg) throws ChangelogException |
| | | { |
| | | try |
| | | if (updateMsg instanceof ReplicaOfflineMsg) |
| | | { |
| | | if (updateMsg instanceof ReplicaOfflineMsg) |
| | | { |
| | | final ReplicaOfflineMsg offlineMsg = (ReplicaOfflineMsg) updateMsg; |
| | | this.domainDB.notifyReplicaOffline(baseDN, offlineMsg.getCSN()); |
| | | return true; |
| | | } |
| | | |
| | | if (this.domainDB.publishUpdateMsg(baseDN, updateMsg)) |
| | | { |
| | | /* |
| | | * JNR: Matt and I had a hard time figuring out where to put this |
| | | * synchronized block. We elected to put it here, but without a strong |
| | | * conviction. |
| | | */ |
| | | synchronized (generationIDLock) |
| | | { |
| | | /* |
| | | * JNR: I think the generationIdSavedStatus is set to true because |
| | | * method above created a ReplicaDB which assumes the generationId was |
| | | * communicated to another server. Hence setting true on this field |
| | | * prevent the generationId from being reset. |
| | | */ |
| | | generationIdSavedStatus = true; |
| | | } |
| | | } |
| | | return true; |
| | | final ReplicaOfflineMsg offlineMsg = (ReplicaOfflineMsg) updateMsg; |
| | | this.domainDB.notifyReplicaOffline(baseDN, offlineMsg.getCSN()); |
| | | return; |
| | | } |
| | | catch (ChangelogException e) |
| | | |
| | | if (this.domainDB.publishUpdateMsg(baseDN, updateMsg)) |
| | | { |
| | | /* |
| | | * Because of database problem we can't save any more changes from at |
| | | * least one LDAP server. This replicationServer therefore can't do it's |
| | | * job properly anymore and needs to close all its connections and |
| | | * shutdown itself. |
| | | * JNR: Matt and I had a hard time figuring out where to put this |
| | | * synchronized block. We elected to put it here, but without a strong |
| | | * conviction. |
| | | */ |
| | | logger.error(ERR_CHANGELOG_SHUTDOWN_DATABASE_ERROR, stackTraceToSingleLineString(e)); |
| | | localReplicationServer.shutdown(); |
| | | return false; |
| | | synchronized (generationIDLock) |
| | | { |
| | | /* |
| | | * JNR: I think the generationIdSavedStatus is set to true because |
| | | * method above created a ReplicaDB which assumes the generationId was |
| | | * communicated to another server. Hence setting true on this field |
| | | * prevent the generationId from being reset. |
| | | */ |
| | | generationIdSavedStatus = true; |
| | | } |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | /** Stops DS readers before the peer RS writers which forward their last changes. */ |
| | | void stopDirectoryServers() |
| | | { |
| | | for (DataServerHandler handler : connectedDSs.values()) |
| | | { |
| | | stopServer(handler, true); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Drains changes received directly from DSs before the peer sessions are closed. A peer |
| | | * does not relay third-party changes, so a newer CSN received after failover cannot repair |
| | | * a hole left here. The deadline is shared by every peer and domain of one shutdown. |
| | | */ |
| | | void awaitDirectUpdatesForwarded(long deadline) throws InterruptedException |
| | | { |
| | | // A handler leaves connectedDSs before its reader finishes. Closing admission and |
| | | // crossing this barrier includes those readers too, without serializing live DS puts. |
| | | acceptDirectUpdates = false; |
| | | if (!directUpdateLock.writeLock().tryLock(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS)) |
| | | { |
| | | logger.warn(LocalizableMessage.raw("RS shutdown timed out waiting for direct DS updates for " + baseDN)); |
| | | return; |
| | | } |
| | | final ServerState target; |
| | | final long targetGenerationId; |
| | | try |
| | | { |
| | | synchronized (generationIDLock) |
| | | { |
| | | target = directUpdates.duplicate(); |
| | | targetGenerationId = generationId; |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | directUpdateLock.writeLock().unlock(); |
| | | } |
| | | for (ReplicationServerHandler handler : connectedRSs.values()) |
| | | { |
| | | if (targetGenerationId != getGenerationId()) |
| | | { |
| | | break; // A reset deliberately discarded the old generation's changelog. |
| | | } |
| | | if (handler.getGenerationId() == targetGenerationId |
| | | && !handler.awaitPublished(target, deadline)) |
| | | { |
| | | logger.warn(LocalizableMessage.raw("RS shutdown could not forward all direct DS updates for " |
| | | + baseDN + " to RS " + handler.getServerId() + "; target state: " + target)); |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Checks whether it is already connected to a DS with same id. |
| | | * |
| | |
| | | */ |
| | | public boolean isAlreadyConnectedToDS(DataServerHandler dsHandler) |
| | | { |
| | | if (connectedDSs.containsKey(dsHandler.getServerId())) |
| | | final DataServerHandler existing = connectedDSs.get(dsHandler.getServerId()); |
| | | if (existing == null) |
| | | { |
| | | // looks like two connected LDAP servers have the same serverId |
| | | logger.error(ERR_DUPLICATE_SERVER_ID, localReplicationServer.getMonitorInstanceName(), |
| | | connectedDSs.get(dsHandler.getServerId()), dsHandler, dsHandler.getServerId()); |
| | | return true; |
| | | return false; |
| | | } |
| | | return false; |
| | | |
| | | // A closing handler still owns its ID until teardown unregisters it. The session |
| | | // can start closing before stopServer marks the handler as shutting down. |
| | | if (!existing.shuttingDown() && !existing.session.closeInitiated()) |
| | | { |
| | | logger.error(ERR_DUPLICATE_SERVER_ID, localReplicationServer.getMonitorInstanceName(), |
| | | existing, dsHandler, dsHandler.getServerId()); |
| | | } |
| | | return true; |
| | | } |
| | | |
| | | /** |
| | |
| | | void noLongerAwaitTheForwardOf(ServerHandler rsHandler) |
| | | { |
| | | localReplicationServer.getDSRSShutdownSync() |
| | | .replicaOfflineMsgNotForwarded(baseDN, rsHandler.getServerId()); |
| | | .replicaOfflineMsgNotForwarded(baseDN, rsHandler.offlineForwarder()); |
| | | } |
| | | |
| | | private void unregisterServerHandler(ServerHandler sHandler, boolean shutdown, |
| | | boolean isDirectoryServer) |
| | | { |
| | | unregisterServerHandler(sHandler); |
| | | sHandler.shutdown(); |
| | | if (shutdown) |
| | | { |
| | | sHandler.shutdown(); |
| | | } |
| | | else |
| | | { |
| | | // Stop accepting work and remove name-based monitors before a replacement |
| | | // can register. Both Session.close() and thread joins run unlocked: closing |
| | | // may drain writes to a slow peer, and the reader may need this lock for its |
| | | // last TopologyMsg. Neither may block another peer's failover handshake. |
| | | sHandler.shutdownWithoutWaiting(); |
| | | release(); |
| | | try |
| | | { |
| | | sHandler.awaitShutdown(); |
| | | } |
| | | finally |
| | | { |
| | | // Include any new DS/replacement RS in the generation and topology decisions. |
| | | // Cleanup still owns this hold on return, including after an interrupt. |
| | | lock.lock(); |
| | | } |
| | | } |
| | | |
| | | resetGenerationIdIfPossible(); |
| | | if (!shutdown) |
| | |
| | | final LocalizableMessage message = mb.toMessage(); |
| | | logger.error(message); |
| | | |
| | | if (isScopedInitializationReply(msg)) |
| | | { |
| | | // An unscoped routing error could reach the importer during another initialization. |
| | | return; |
| | | } |
| | | ErrorMsg errMsg = new ErrorMsg(this.localReplicationServer.getServerId(), |
| | | msg.getSenderID(), message); |
| | | try |
| | |
| | | final LocalizableMessage message = mb.toMessage(); |
| | | logger.error(message); |
| | | |
| | | if (isScopedInitializationReply(msg)) |
| | | { |
| | | continue; |
| | | } |
| | | ErrorMsg errMsg = new ErrorMsg(msg.getSenderID(), message); |
| | | try |
| | | { |
| | |
| | | } |
| | | } |
| | | |
| | | private boolean isScopedInitializationReply(RoutableMsg msg) |
| | | { |
| | | return (msg instanceof ErrorMsg && ((ErrorMsg) msg).getInitializationAttemptId() != null) |
| | | || (msg instanceof InitializeRcvAckMsg && ((InitializeRcvAckMsg) msg).getInitializationAttemptId() != null); |
| | | } |
| | | |
| | | /** |
| | | * Creates a new monitor message including monitoring information for the |
| | | * whole topology. |
| | |
| | | return domainDB.getDomainNewestCSNs(baseDN); |
| | | } |
| | | |
| | | /** |
| | | * Returns peer history which an outgoing RS queue may not contain. |
| | | * |
| | | * @param serverId the replica which produced the history |
| | | * @return its newest peer update, or {@code null} when none is known |
| | | */ |
| | | CSN getLatestPeerUpdate(int serverId) |
| | | { |
| | | return peerUpdates.getCSN(serverId); |
| | | } |
| | | |
| | | @Override |
| | | public String toString() |
| | | { |
| | |
| | | if (this.generationId != generationId) |
| | | { |
| | | clearDbs(); |
| | | directUpdates.clear(); |
| | | peerUpdates.clear(); |
| | | |
| | | this.generationId = generationId; |
| | | this.generationIdSavedStatus = false; |
| | |
| | | } |
| | | catch (IOException e) |
| | | { |
| | | logger.error(ERR_EXCEPTION_CHANGING_STATUS_FROM_STATUS_ANALYZER, |
| | | baseDN, dsHandler.getServerId(), e.getMessage()); |
| | | logger.traceException(e); |
| | | // The reader can close the session before removing its handler from this domain. |
| | | if (!dsHandler.shuttingDown() && !dsHandler.session.closeInitiated()) |
| | | { |
| | | logger.error(ERR_EXCEPTION_CHANGING_STATUS_FROM_STATUS_ANALYZER, |
| | | baseDN, dsHandler.getServerId(), e.getMessage()); |
| | | } |
| | | } |
| | | |
| | | if (newStatus == ServerStatus.INVALID_STATUS || newStatus == oldStatus) |
| | |
| | | |
| | | try |
| | | { |
| | | // Teardown releases the domain lock while joining this reader. Its final |
| | | // message must not change the topology after its handler was removed or |
| | | // replaced by a new session with the same server id. |
| | | if (connectedRSs.get(rsHandler.getServerId()) != rsHandler) |
| | | { |
| | | return; |
| | | } |
| | | // Store DS connected to remote RS & update information about the peer RS |
| | | rsHandler.processTopoInfoFromRS(topoMsg); |
| | | |
| | |
| | | */ |
| | | private final ReentrantLock lock = new ReentrantLock(); |
| | | |
| | | private final ReentrantLock peerHandshakeLock = new ReentrantLock(); |
| | | |
| | | /** Orders competing peer RS handshakes without locking out directory servers. */ |
| | | ReentrantLock peerHandshakeLock() |
| | | { |
| | | return peerHandshakeLock; |
| | | } |
| | | |
| | | /** This lock is used to protect the generationId variable. */ |
| | | private final Object generationIDLock = new Object(); |
| | | |
| | |
| | | * |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2011-2016 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.server; |
| | | |
| | |
| | | import java.io.IOException; |
| | | import java.util.Arrays; |
| | | import java.util.Collections; |
| | | import java.util.HashMap; |
| | | import java.util.HashSet; |
| | | import java.util.LinkedHashSet; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.Set; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | import java.util.concurrent.ThreadLocalRandom; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.locks.ReentrantLock; |
| | | |
| | | import org.forgerock.i18n.LocalizableMessage; |
| | | import org.forgerock.i18n.slf4j.LocalizedLogger; |
| | |
| | | import org.forgerock.opendj.ldap.ResultCode; |
| | | import org.opends.server.api.MonitorData; |
| | | import org.opends.server.replication.common.DSInfo; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.opends.server.replication.common.RSInfo; |
| | | import org.opends.server.replication.common.ServerState; |
| | | import org.opends.server.replication.common.ServerStatus; |
| | |
| | | import org.opends.server.replication.protocol.Session; |
| | | import org.opends.server.replication.protocol.StopMsg; |
| | | import org.opends.server.replication.protocol.TopologyMsg; |
| | | import org.opends.server.replication.protocol.UpdateMsg; |
| | | import org.opends.server.types.DirectoryException; |
| | | import org.opends.server.types.HostPort; |
| | | |
| | |
| | | */ |
| | | private final Map<Integer, LightweightServerHandler> remoteDirectoryServers = new ConcurrentHashMap<>(); |
| | | |
| | | /** Incoming peer knowledge is useful to monitors, but cannot advance the outgoing cursor. */ |
| | | private final ServerState receivedState = new ServerState(); |
| | | |
| | | /** Exact recent receipts, bounded like the message queue. Guarded by publishedState. */ |
| | | private final Set<CSN> receivedUpdates = new LinkedHashSet<>(); |
| | | /** Selected updates and their local generation, awaiting a socket write. Guarded by publishedState. */ |
| | | private final Map<CSN, Long> pendingWrites = new HashMap<>(); |
| | | /** Filtered writes still awaiting an exact receipt. Guarded by publishedState. */ |
| | | private final Set<CSN> discardedWrites = new HashSet<>(); |
| | | /** Earliest discard per origin beyond the exact tracking capacity. Guarded by publishedState. */ |
| | | private final Map<Integer, CSN> firstOverflowDiscards = new HashMap<>(); |
| | | /** Origins with multiple distinct overflow discards whose individual CSNs were forgotten. */ |
| | | private final Set<Integer> ambiguousDiscardOrigins = new HashSet<>(); |
| | | /** Local changelog generation of the discarded writes. Guarded by publishedState. */ |
| | | private long discardedGenerationId = -1; |
| | | |
| | | @Override |
| | | void recordReceivedUpdate(UpdateMsg update) |
| | | { |
| | | // A DS may have moved to this peer while older updates are still queued here. |
| | | // Its newer CSN does not prove that this peer received that older history. |
| | | if (update.contributesToDomainState()) |
| | | { |
| | | synchronized (publishedState) |
| | | { |
| | | final CSN csn = update.getCSN(); |
| | | receivedState.update(csn); |
| | | final long localGenerationId = replicationServerDomain.getGenerationId(); |
| | | if (generationId != -1 && generationId == localGenerationId) |
| | | { |
| | | // The reader can confirm an exact CSN before or after the writer reports its drop. |
| | | final boolean confirmedDiscard = discardedGenerationId == localGenerationId && confirmDiscard(csn); |
| | | if (pendingWrites.remove(csn, localGenerationId) || confirmedDiscard) |
| | | { |
| | | publishedState.notifyAll(); |
| | | } |
| | | } |
| | | receivedUpdates.remove(csn); |
| | | receivedUpdates.add(csn); |
| | | if (receivedUpdates.size() > Math.max(1, maxQueueSize)) |
| | | { |
| | | // Forgetting a receipt may resend that record during a later catch-up. |
| | | // It must never turn an incoming maximum into proof of an older prefix. |
| | | receivedUpdates.remove(receivedUpdates.iterator().next()); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | protected CSN getLatestUnqueuedUpdate(int serverId) |
| | | { |
| | | return replicationServerDomain.getLatestPeerUpdate(serverId); |
| | | } |
| | | |
| | | @Override |
| | | boolean updateServerState(UpdateMsg update) |
| | | { |
| | | synchronized (publishedState) |
| | | { |
| | | if (!super.updateServerState(update)) |
| | | { |
| | | return false; |
| | | } |
| | | if (update.contributesToDomainState()) |
| | | { |
| | | final CSN csn = update.getCSN(); |
| | | if (receivedUpdates.remove(csn)) |
| | | { |
| | | // Only the ordered reader advances the cursor. Every older unknown |
| | | // record has been selected, and pendingWrites still fences its delivery. |
| | | publishedState.notifyAll(); |
| | | return false; |
| | | } |
| | | pendingWrites.put(csn, replicationServerDomain.getGenerationId()); |
| | | } |
| | | return true; |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public ServerState getServerState() |
| | | { |
| | | final ServerState knownState = super.getServerState().duplicate(); |
| | | knownState.update(receivedState); |
| | | return knownState; |
| | | } |
| | | |
| | | /** Peer handshake state plus updates actually written, rather than merely dequeued. */ |
| | | private final ServerState publishedState = new ServerState(); |
| | | |
| | | @Override |
| | | public void setInitialServerState(ServerState state) throws DirectoryException |
| | | { |
| | | synchronized (publishedState) |
| | | { |
| | | super.setInitialServerState(state); |
| | | receivedState.clear(); |
| | | receivedUpdates.clear(); |
| | | pendingWrites.clear(); |
| | | clearDiscardedWrites(-1); |
| | | publishedState.clear(); |
| | | publishedState.update(state); |
| | | } |
| | | } |
| | | |
| | | /** Records a successful socket write to this peer. */ |
| | | void updatePublishedState(CSN csn) |
| | | { |
| | | synchronized (publishedState) |
| | | { |
| | | pendingWrites.remove(csn); |
| | | publishedState.update(csn); |
| | | publishedState.notifyAll(); |
| | | } |
| | | } |
| | | |
| | | /** Releases bookkeeping for a selected update which the writer filters out. */ |
| | | void updateDiscardedState(CSN csn) |
| | | { |
| | | synchronized (publishedState) |
| | | { |
| | | final Long selectedGenerationId = pendingWrites.remove(csn); |
| | | final long localGenerationId = replicationServerDomain.getGenerationId(); |
| | | // A reset may occur between selection, filtering and reporting the drop. |
| | | // An old selection must not create a barrier in the new local generation. |
| | | if (selectedGenerationId != null && selectedGenerationId == localGenerationId) |
| | | { |
| | | if (discardedGenerationId != localGenerationId) |
| | | { |
| | | clearDiscardedWrites(localGenerationId); |
| | | } |
| | | if (discardedWrites.size() < Math.max(1, maxQueueSize)) |
| | | { |
| | | discardedWrites.add(csn); |
| | | } |
| | | else |
| | | { |
| | | // One overflow CSN per origin is still exact. After a second distinct one, |
| | | // retain the earliest barrier until reset: its receipt alone cannot prove the rest. |
| | | final int origin = csn.getServerId(); |
| | | final CSN first = firstOverflowDiscards.putIfAbsent(origin, csn); |
| | | if (first != null && !first.equals(csn)) |
| | | { |
| | | ambiguousDiscardOrigins.add(origin); |
| | | if (first.isNewerThan(csn)) |
| | | { |
| | | firstOverflowDiscards.put(origin, csn); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | publishedState.notifyAll(); |
| | | } |
| | | } |
| | | |
| | | private void clearDiscardedWrites(long localGenerationId) |
| | | { |
| | | discardedWrites.clear(); |
| | | firstOverflowDiscards.clear(); |
| | | ambiguousDiscardOrigins.clear(); |
| | | discardedGenerationId = localGenerationId; |
| | | } |
| | | |
| | | /** Called under publishedState for a receipt in the generation of the discarded writes. */ |
| | | private boolean confirmDiscard(CSN csn) |
| | | { |
| | | final int origin = csn.getServerId(); |
| | | return discardedWrites.remove(csn) |
| | | || (!ambiguousDiscardOrigins.contains(origin) && firstOverflowDiscards.remove(origin, csn)); |
| | | } |
| | | |
| | | /** Must be called under publishedState, like selecting a record and completing its write. */ |
| | | private boolean delivered(ServerState target) |
| | | { |
| | | for (CSN csn : target) |
| | | { |
| | | if (discardedGenerationId == replicationServerDomain.getGenerationId()) |
| | | { |
| | | final CSN firstOverflow = firstOverflowDiscards.get(csn.getServerId()); |
| | | if ((firstOverflow != null && !firstOverflow.isNewerThan(csn)) || blocksDelivery(discardedWrites, csn)) |
| | | { |
| | | return false; |
| | | } |
| | | } |
| | | if (blocksDelivery(pendingWrites.keySet(), csn)) |
| | | { |
| | | return false; |
| | | } |
| | | if (!publishedState.cover(csn) && !super.getServerState().cover(csn)) |
| | | { |
| | | return false; |
| | | } |
| | | } |
| | | return true; |
| | | } |
| | | |
| | | private static boolean blocksDelivery(Set<CSN> outstanding, CSN target) |
| | | { |
| | | for (CSN csn : outstanding) |
| | | { |
| | | if (csn.getServerId() == target.getServerId() && !csn.isNewerThan(target)) |
| | | { |
| | | return true; |
| | | } |
| | | } |
| | | return false; |
| | | } |
| | | |
| | | /** Waits within a shared monotonic deadline for this peer's outstanding direct updates. */ |
| | | boolean awaitPublished(ServerState target, long deadline) throws InterruptedException |
| | | { |
| | | synchronized (publishedState) |
| | | { |
| | | while (!delivered(target) && !shuttingDown()) |
| | | { |
| | | final long remaining = deadline - System.nanoTime(); |
| | | if (remaining <= 0) |
| | | { |
| | | break; |
| | | } |
| | | TimeUnit.NANOSECONDS.timedWait(publishedState, remaining); |
| | | } |
| | | return delivered(target); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void setGenerationId(long generationId) |
| | | { |
| | | synchronized (publishedState) |
| | | { |
| | | if (this.generationId != generationId) |
| | | { |
| | | receivedUpdates.clear(); |
| | | receivedState.clear(); |
| | | // Changing only the peer's generation does not deliver previously filtered history. |
| | | } |
| | | super.setGenerationId(generationId); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Starts this handler based on a start message received from remote server. |
| | | * @param inReplServerStartMsg The start msg provided by the remote server. |
| | |
| | | this.sslEncryption = sslEncryption; |
| | | |
| | | setBaseDNAndDomain(baseDN, false); |
| | | final ReentrantLock peerLock = replicationServerDomain.peerHandshakeLock(); |
| | | |
| | | try |
| | | { |
| | | peerLock.lockInterruptibly(); |
| | | lockDomainNoTimeout(); |
| | | |
| | | // Read under the domain lock so the start message advertises any change |
| | | // made by a previous handshake (handshakes serialize on this lock). The |
| | | // field itself is only guarded by generationIDLock and lock-free |
| | | // adopters can still move it — the arming CAS in |
| | | // setDomainGenerationIdOnStart handles that residual race. |
| | | localGenerationId = replicationServerDomain.getGenerationId(); |
| | | final ReplServerStartMsg outReplServerStartMsg = createReplServerStartMsg(); |
| | | releaseDomainLock(); |
| | | |
| | | ReplServerStartMsg outReplServerStartMsg = sendStartToRemote(); |
| | | |
| | | // Wait answer |
| | | // The peer lock still arbitrates crossed RS connections. DS handshakes can |
| | | // use the domain while this peer has yet to answer the start message. |
| | | send(outReplServerStartMsg); |
| | | ReplicationMsg msg = session.receive(); |
| | | |
| | | // Reject bad responses |
| | |
| | | return false; |
| | | } |
| | | |
| | | lockDomainNoTimeout(); |
| | | processStartFromRemote((ReplServerStartMsg) msg); |
| | | if (replicationServerDomain.getGenerationId() != localGenerationId) |
| | | { |
| | | // The peer saw the previous generation. Retry with the current state. |
| | | if (!this.sslEncryption) |
| | | { |
| | | session.stopEncryption(); |
| | | } |
| | | abortStart(null); |
| | | return false; |
| | | } |
| | | |
| | | if (replicationServerDomain.isAlreadyConnectedToRS(this)) |
| | | { |
| | |
| | | finally |
| | | { |
| | | releaseDomainLock(); |
| | | if (peerLock.isHeldByCurrentThread()) |
| | | { |
| | | peerLock.unlock(); |
| | | } |
| | | } |
| | | } |
| | | |
| | |
| | | public void startFromRemoteRS(ReplServerStartMsg inReplServerStartMsg) |
| | | { |
| | | localGenerationId = -1; |
| | | ReentrantLock peerLock = null; |
| | | try |
| | | { |
| | | // The initiator decides if the session is encrypted |
| | | sslEncryption = processStartFromRemote(inReplServerStartMsg); |
| | | peerLock = replicationServerDomain.peerHandshakeLock(); |
| | | |
| | | if (!lockDomainWithTimeout()) |
| | | if (!lockDomainWithTimeout(peerLock)) |
| | | { |
| | | // This server gives way to a cross connection, see lockDomainWithTimeout(). |
| | | abortStartWithWarning(WARN_TIMEOUT_WHEN_CROSS_CONNECTION.get(getBaseDN(), serverId, |
| | | session.getReadableRemoteAddress(), getReplicationServerId())); |
| | | return; |
| | |
| | | finally |
| | | { |
| | | releaseDomainLock(); |
| | | if (peerLock != null && peerLock.isHeldByCurrentThread()) |
| | | { |
| | | peerLock.unlock(); |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Acquire both locks within one randomized deadline. If two RSs dial each other, |
| | | * one incoming handshake can give way first so the other connection can finish. |
| | | */ |
| | | private boolean lockDomainWithTimeout(ReentrantLock peerLock) throws InterruptedException |
| | | { |
| | | final long timeout = ThreadLocalRandom.current().nextInt(3, 9) * 1000L; |
| | | final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout); |
| | | return peerLock.tryLock(timeout, TimeUnit.MILLISECONDS) |
| | | && replicationServerDomain.tryLock(Math.max(0, TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()))); |
| | | } |
| | | |
| | | /** |
| | | * Wait receiving the TopologyMsg from the remote RS and process it. |
| | | * @return the topologyMsg received or {@code null} if stop was received. |
| | | * @throws DirectoryException |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Shutdown This ServerHandler. |
| | | */ |
| | | @Override |
| | | public void shutdown() |
| | | void shutdownWithoutWaiting() |
| | | { |
| | | super.shutdown(); |
| | | super.shutdownWithoutWaiting(); |
| | | // These monitors share their names with a replacement session's monitors. |
| | | // Remove them while the domain lock still excludes that replacement. |
| | | clearRemoteLSHandlers(); |
| | | } |
| | | |
| | | @Override |
| | | void awaitShutdown() |
| | | { |
| | | super.awaitShutdown(); |
| | | clearReceivedUpdates(); |
| | | } |
| | | |
| | | private void clearReceivedUpdates() |
| | | { |
| | | synchronized (publishedState) |
| | | { |
| | | receivedUpdates.clear(); |
| | | publishedState.notifyAll(); |
| | | } |
| | | } |
| | | |
| | | private void clearRemoteLSHandlers() |
| | | { |
| | | synchronized (remoteDirectoryServers) |
| | |
| | | { |
| | | // List should only contain RS info for sender |
| | | final RSInfo rsInfo = topoMsg.getRsInfos().get(0); |
| | | generationId = rsInfo.getGenerationId(); |
| | | setGenerationId(rsInfo.getGenerationId()); |
| | | groupId = rsInfo.getGroupId(); |
| | | weight = rsInfo.getWeight(); |
| | | |
| | |
| | | * |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2011-2016 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.server; |
| | | |
| | |
| | | |
| | | import java.io.IOException; |
| | | import java.io.UnsupportedEncodingException; |
| | | import java.util.Random; |
| | | import java.util.concurrent.Semaphore; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.atomic.AtomicInteger; |
| | | import java.util.concurrent.atomic.AtomicReference; |
| | | |
| | | import org.forgerock.i18n.LocalizableMessage; |
| | | import org.forgerock.i18n.slf4j.LocalizedLogger; |
| | |
| | | import org.opends.server.replication.protocol.UpdateMsg; |
| | | import org.opends.server.replication.protocol.WindowMsg; |
| | | import org.opends.server.replication.server.changelog.api.ChangelogException; |
| | | import org.opends.server.replication.service.DSRSShutdownSync.ForwardingPeer; |
| | | import org.opends.server.types.DirectoryException; |
| | | import org.opends.server.types.InitializationException; |
| | | |
| | |
| | | */ |
| | | protected final Session session; |
| | | |
| | | private final AtomicReference<ForwardingPeer> offlineForwarder = new AtomicReference<>(); |
| | | |
| | | /** |
| | | * The serverURL of the remote server. |
| | | */ |
| | |
| | | return serverId; |
| | | } |
| | | |
| | | /** Returns this connection's offline-forwarding token after the peer ID is known. */ |
| | | final ForwardingPeer offlineForwarder() |
| | | { |
| | | return offlineForwarder.updateAndGet(peer -> peer != null ? peer : new ForwardingPeer(serverId)); |
| | | } |
| | | |
| | | /** |
| | | * Retrieves the URL for this server handler. |
| | | * |
| | |
| | | } |
| | | |
| | | /** |
| | | * Lock the domain with a timeout. |
| | | * <p> |
| | | * Take the lock on the domain. WARNING: Here we try to acquire the lock with |
| | | * a timeout. This is for preventing a deadlock that may happen if there are |
| | | * cross connection attempts (for same domain) from this replication server |
| | | * and from a peer one. |
| | | * <p> |
| | | * Here is the scenario: |
| | | * <ol> |
| | | * <li>RS1 connect thread takes the domain lock and starts connection to RS2 |
| | | * </li> |
| | | * <li>at the same time RS2 connect thread takes his domain lock and start |
| | | * connection to RS2</li> |
| | | * <li>RS2 listen thread starts processing received ReplServerStartMsg from |
| | | * RS1 and wants to acquire the lock on the domain (here) but cannot as RS2 |
| | | * connect thread already has it</li> |
| | | * <li>RS1 listen thread starts processing received ReplServerStartMsg from |
| | | * RS2 and wants to acquire the lock on the domain (here) but cannot as RS1 |
| | | * connect thread already has it</li> |
| | | * </ol> |
| | | * => Deadlock: 4 threads are locked. |
| | | * <p> |
| | | * To prevent threads locking in such situation, the listen threads here will |
| | | * both timeout trying to acquire the lock. The random time for the timeout |
| | | * should allow on connection attempt to be aborted whereas the other one |
| | | * should have time to finish in the same time. |
| | | * <p> |
| | | * Warning: the minimum time (3s) should be big enough to allow normal |
| | | * situation connections to terminate. The added random time should represent |
| | | * a big enough range so that the chance to have one listen thread timing out |
| | | * a lot before the peer one is great. When the first listen thread times out, |
| | | * the remote connect thread should release the lock and allow the peer listen |
| | | * thread to take the lock it was waiting for and process the connection |
| | | * attempt. |
| | | * |
| | | * @return {@code true} if the lock was acquired, {@code false} if the wait |
| | | * timed out, which is the connection attempt to abort |
| | | * @throws InterruptedException |
| | | * If the current thread was interrupted while waiting for the lock. |
| | | */ |
| | | public boolean lockDomainWithTimeout() throws InterruptedException |
| | | { |
| | | final Random random = new Random(); |
| | | final int randomTime = random.nextInt(6); // Random from 0 to 5 |
| | | // Wait at least 3 seconds + (0 to 5 seconds) |
| | | final long timeout = 3000 + randomTime * 1000L; |
| | | return replicationServerDomain.tryLock(timeout); |
| | | } |
| | | |
| | | /** |
| | | * Processes a routable message. |
| | | * |
| | | * @param msg The message to be processed. |
| | |
| | | @Override |
| | | public void shutdown() |
| | | { |
| | | shutdownWithoutWaiting(); |
| | | awaitShutdown(); |
| | | } |
| | | |
| | | /** Stops accepting work and removes monitors before a replacement can register. */ |
| | | void shutdownWithoutWaiting() |
| | | { |
| | | shutdownWriter = true; |
| | | setConsumerActive(false); |
| | | super.shutdown(); |
| | | |
| | | if (session != null) |
| | | { |
| | | session.close(); |
| | | } |
| | | if (heartbeatThread != null) |
| | | { |
| | | heartbeatThread.shutdown(); |
| | | } |
| | | |
| | | DirectoryServer.deregisterMonitorProvider(this); |
| | | } |
| | | |
| | | /** Waits for accepted work to finish without retaining the replication domain lock. */ |
| | | void awaitShutdown() |
| | | { |
| | | // Closing drains accepted writes and may block on a slow peer. Runtime |
| | | // teardown must release the domain lock before this phase, just as for joins. |
| | | if (session != null) |
| | | { |
| | | session.close(); |
| | | } |
| | | joinShutdownThreads(); |
| | | } |
| | | |
| | | private void joinShutdownThreads() |
| | | { |
| | | /* |
| | | * Be sure to wait for ServerWriter and ServerReader death |
| | | * It does not matter if we try to stop a thread which is us (reader |
| | |
| | | } |
| | | } |
| | | |
| | | /** Records an update received from the remote server, separately from delivery where needed. */ |
| | | void recordReceivedUpdate(UpdateMsg update) |
| | | { |
| | | updateServerState(update); |
| | | } |
| | | |
| | | /** |
| | | * Select the next update that must be sent to the server managed by this |
| | | * ServerHandler. |
| | |
| | | * that this handler is stopped. |
| | | */ |
| | | logException(e); |
| | | if (!handler.shuttingDown()) |
| | | // A local close can wake receive() with SocketException as well as EOF. |
| | | // The writer closes the session before stopServer marks the handler. |
| | | if (!handler.shuttingDown() && !session.closeInitiated()) |
| | | { |
| | | errMessage = handler.getBadlyDisconnectedErrorMessage(); |
| | | logger.error(errMessage); |
| | |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.opends.server.api.DirectoryThread; |
| | | import org.forgerock.i18n.slf4j.LocalizedLogger; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.opends.server.replication.common.ServerStatus; |
| | | import org.opends.server.replication.protocol.ReplicaOfflineMsg; |
| | | import org.opends.server.replication.protocol.Session; |
| | | import org.opends.server.replication.protocol.UpdateMsg; |
| | | import org.opends.server.replication.service.DSRSShutdownSync; |
| | | import org.opends.server.replication.service.DSRSShutdownSync.ForwardingPeer; |
| | | |
| | | import static org.opends.messages.ReplicationMessages.*; |
| | | import static org.opends.server.replication.common.ServerStatus.*; |
| | |
| | | * as sent (issue #1080). |
| | | */ |
| | | handler.releasePermitInSendWindow(); |
| | | if (handler instanceof ReplicationServerHandler && updateMsg.contributesToDomainState()) |
| | | { |
| | | ((ReplicationServerHandler) handler).updateDiscardedState(updateMsg.getCSN()); |
| | | } |
| | | if (updateMsg instanceof ReplicaOfflineMsg && !handler.isDataServer()) |
| | | { |
| | | dsrsShutdownSync.replicaOfflineMsgNotForwarded( |
| | | replicationServerDomain.getBaseDN(), handler.getServerId()); |
| | | replicationServerDomain.getBaseDN(), handler.offlineForwarder()); |
| | | } |
| | | } |
| | | else |
| | |
| | | { |
| | | forwardReplicaOfflineMsg((ReplicaOfflineMsg) updateMsg); |
| | | } |
| | | else if (handler instanceof ReplicationServerHandler && updateMsg.contributesToDomainState()) |
| | | { |
| | | // take() already advanced the handler state, while publish() may only enqueue. |
| | | // A shutdown must wait until the session publisher has written the change. |
| | | final CSN csn = updateMsg.getCSN(); |
| | | session.publish(updateMsg, |
| | | () -> ((ReplicationServerHandler) handler).updatePublishedState(csn)); |
| | | } |
| | | else |
| | | { |
| | | // Publish the update to the remote server using a protocol version it supports |
| | |
| | | private void forwardReplicaOfflineMsg(final ReplicaOfflineMsg msg) throws IOException |
| | | { |
| | | final DN baseDN = replicationServerDomain.getBaseDN(); |
| | | final int serverId = handler.getServerId(); |
| | | final ForwardingPeer peer = handler.offlineForwarder(); |
| | | final boolean accepted = session.publish(msg, |
| | | () -> dsrsShutdownSync.replicaOfflineMsgForwarded(baseDN, msg.getCSN(), serverId)); |
| | | () -> dsrsShutdownSync.replicaOfflineMsgForwarded(baseDN, msg.getCSN(), peer)); |
| | | if (!accepted) |
| | | { |
| | | dsrsShutdownSync.replicaOfflineMsgNotForwarded(baseDN, serverId); |
| | | dsrsShutdownSync.replicaOfflineMsgNotForwarded(baseDN, peer); |
| | | } |
| | | } |
| | | |
| | |
| | | public class DSRSShutdownSync |
| | | { |
| | | /** |
| | | * Identifies one connection to a peer RS without retaining the handler or session. |
| | | * Connections with the same server ID have distinct tokens. |
| | | */ |
| | | public static final class ForwardingPeer |
| | | { |
| | | private final int serverId; |
| | | |
| | | /** |
| | | * Creates the token for one connection. |
| | | * |
| | | * @param serverId the peer's server ID, for diagnostics |
| | | */ |
| | | public ForwardingPeer(int serverId) |
| | | { |
| | | this.serverId = serverId; |
| | | } |
| | | |
| | | /** Returns the peer's server ID. */ |
| | | public int getServerId() |
| | | { |
| | | return serverId; |
| | | } |
| | | |
| | | @Override |
| | | public String toString() |
| | | { |
| | | return "RS(" + serverId + ")"; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * How long a ReplicaOfflineMsg may hold back the shutdown of the collocated |
| | | * RS, in milliseconds, counted from the moment the message was announced. |
| | | */ |
| | |
| | | * the domain for which the message has been sent |
| | | * @param offlineCSN |
| | | * the CSN of the message which is being queued |
| | | * @param replicationServerIds |
| | | * the server ids of the replication servers the message is being queued for |
| | | * @param peers |
| | | * the peer connections the message is being queued for |
| | | */ |
| | | public void replicaOfflineMsgDispatched( |
| | | DN baseDN, CSN offlineCSN, Collection<Integer> replicationServerIds) |
| | | DN baseDN, CSN offlineCSN, Collection<ForwardingPeer> peers) |
| | | { |
| | | final ConcurrentMap<Integer, PendingOfflineMsg> msgs = replicaOfflineMsgs.get(baseDN); |
| | | if (msgs == null) |
| | |
| | | * nothing about the announcement the shutdown is waiting for. |
| | | */ |
| | | if (pending != null && pending.csn.equals(offlineCSN) |
| | | && pending.awaitForwardsFrom(replicationServerIds)) |
| | | && pending.awaitForwardsFrom(peers)) |
| | | { |
| | | // queued for nobody: there is nothing to wait for |
| | | msgs.remove(serverId, pending); |
| | |
| | | * the domain for which the message has been sent |
| | | * @param forwardedCSN |
| | | * the CSN of the forwarded message |
| | | * @param replicationServerId |
| | | * the server id of the replication server the message has been forwarded to |
| | | * @param peer |
| | | * the peer connection through which the message was forwarded |
| | | */ |
| | | public void replicaOfflineMsgForwarded(DN baseDN, CSN forwardedCSN, int replicationServerId) |
| | | public void replicaOfflineMsgForwarded(DN baseDN, CSN forwardedCSN, ForwardingPeer peer) |
| | | { |
| | | final ConcurrentMap<Integer, PendingOfflineMsg> msgs = replicaOfflineMsgs.get(baseDN); |
| | | if (msgs != null) |
| | |
| | | * not consume its grace period. |
| | | */ |
| | | if (pending != null && pending.csn.isOlderThanOrEqualTo(forwardedCSN) |
| | | && pending.forwardedBy(replicationServerId)) |
| | | && pending.forwardedBy(peer)) |
| | | { |
| | | msgs.remove(serverId, pending); |
| | | } |
| | |
| | | * |
| | | * @param baseDN |
| | | * the domain the replication server is connected to |
| | | * @param replicationServerId |
| | | * the server id of the replication server which will not forward the message |
| | | * @param peer |
| | | * the peer connection which will not forward the message |
| | | */ |
| | | public void replicaOfflineMsgNotForwarded(DN baseDN, int replicationServerId) |
| | | public void replicaOfflineMsgNotForwarded(DN baseDN, ForwardingPeer peer) |
| | | { |
| | | final ConcurrentMap<Integer, PendingOfflineMsg> msgs = replicaOfflineMsgs.get(baseDN); |
| | | if (msgs != null) |
| | |
| | | for (Entry<Integer, PendingOfflineMsg> entry : msgs.entrySet()) |
| | | { |
| | | final PendingOfflineMsg pending = entry.getValue(); |
| | | if (pending.giveUpOn(replicationServerId)) |
| | | if (pending.giveUpOn(peer)) |
| | | { |
| | | msgs.remove(entry.getKey(), pending); |
| | | } |
| | |
| | | * The replication servers the message was queued for and which have not forwarded it yet, |
| | | * null as long as it has not been queued for anybody. |
| | | */ |
| | | private volatile Set<Integer> awaitedForwarders; |
| | | private volatile Set<ForwardingPeer> awaitedForwarders; |
| | | |
| | | private PendingOfflineMsg(CSN csn, long sentTime, PendingOfflineMsg displaced) |
| | | { |
| | |
| | | * Records the replication servers the message is being queued for, and returns whether there |
| | | * is none of them, i.e. nothing left to wait for. |
| | | */ |
| | | private boolean awaitForwardsFrom(Collection<Integer> replicationServerIds) |
| | | private boolean awaitForwardsFrom(Collection<ForwardingPeer> peers) |
| | | { |
| | | final Set<Integer> awaited = ConcurrentHashMap.newKeySet(); |
| | | awaited.addAll(replicationServerIds); |
| | | final Set<ForwardingPeer> awaited = ConcurrentHashMap.newKeySet(); |
| | | awaited.addAll(peers); |
| | | awaitedForwarders = awaited; |
| | | return awaited.isEmpty(); |
| | | } |
| | |
| | | * Records the forward of one replication server, and returns whether nothing is left to wait |
| | | * for. |
| | | */ |
| | | private boolean forwardedBy(int replicationServerId) |
| | | private boolean forwardedBy(ForwardingPeer peer) |
| | | { |
| | | final Set<Integer> awaited = awaitedForwarders; |
| | | final Set<ForwardingPeer> awaited = awaitedForwarders; |
| | | if (awaited == null) |
| | | { |
| | | /* |
| | |
| | | */ |
| | | return true; |
| | | } |
| | | awaited.remove(replicationServerId); |
| | | awaited.remove(peer); |
| | | return awaited.isEmpty(); |
| | | } |
| | | |
| | |
| | | * wait for. Unlike a forward, this releases nothing while no recipient is known: a peer going |
| | | * away says nothing about a message it was never given. |
| | | */ |
| | | private boolean giveUpOn(int replicationServerId) |
| | | private boolean giveUpOn(ForwardingPeer peer) |
| | | { |
| | | final Set<Integer> awaited = awaitedForwarders; |
| | | return awaited != null && awaited.remove(replicationServerId) && awaited.isEmpty(); |
| | | final Set<ForwardingPeer> awaited = awaitedForwarders; |
| | | return awaited != null && awaited.remove(peer) && awaited.isEmpty(); |
| | | } |
| | | |
| | | /** |
| | |
| | | */ |
| | | private boolean isFullyForwarded() |
| | | { |
| | | final Set<Integer> awaited = awaitedForwarders; |
| | | final Set<ForwardingPeer> awaited = awaitedForwarders; |
| | | return awaited != null && awaited.isEmpty(); |
| | | } |
| | | |
| | | @Override |
| | | public String toString() |
| | | { |
| | | final Set<Integer> awaited = awaitedForwarders; |
| | | final Set<ForwardingPeer> awaited = awaitedForwarders; |
| | | return "PendingOfflineMsg(" + csn |
| | | + (awaited != null ? ", awaiting the forward of " + awaited : "") + ")"; |
| | | } |
| | |
| | | { |
| | | if (gotOneFailure) |
| | | { |
| | | // Heartbeat is well overdue so the server is assumed to be dead. |
| | | logger.warn(WARN_HEARTBEAT_FAILURE, serverID, |
| | | replicationServerID, session.getReadableRemoteAddress(), baseDN); |
| | | |
| | | // Exit monitor and close session. |
| | | // Heartbeat is well overdue. Finish monitoring and let the session decide how to close. |
| | | shutdown = true; |
| | | heartbeatsStopped = true; |
| | | break; |
| | |
| | | * that write, nor the read of the listener, which neither data nor a reset ends: the |
| | | * session is closed as a failed one, with no StopMsg the replication server would not read. |
| | | */ |
| | | session.abort(new IOException("No heartbeat came from replication server RS(" |
| | | final IOException cause = new IOException("No heartbeat came from replication server RS(" |
| | | + replicationServerID + ") at " + session.getReadableRemoteAddress() + " for twice " |
| | | + heartbeatInterval + " ms")); |
| | | + heartbeatInterval + " ms"); |
| | | if (session.abortOnHeartbeatTimeout(cause)) |
| | | { |
| | | logger.warn(WARN_HEARTBEAT_FAILURE, serverID, |
| | | replicationServerID, session.getReadableRemoteAddress(), baseDN); |
| | | } |
| | | } |
| | | else |
| | | { |
| | |
| | | import java.util.Set; |
| | | import java.util.TreeMap; |
| | | import java.util.concurrent.ConcurrentSkipListMap; |
| | | import java.util.concurrent.ScheduledFuture; |
| | | import java.util.concurrent.Semaphore; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | |
| | | import org.forgerock.util.Utils; |
| | | import org.opends.server.api.DirectoryThread; |
| | | import org.opends.server.core.DirectoryServer; |
| | | import org.opends.server.replication.common.AssuredMode; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.opends.server.replication.common.DSInfo; |
| | | import org.opends.server.replication.common.RSInfo; |
| | |
| | | import org.opends.server.replication.common.ServerStatus; |
| | | import org.opends.server.replication.plugin.MultimasterReplication; |
| | | import org.opends.server.replication.protocol.ChangeStatusMsg; |
| | | import org.opends.server.replication.protocol.ErrorMsg; |
| | | import org.opends.server.replication.protocol.InitializeTargetMsg; |
| | | import org.opends.server.replication.protocol.MonitorMsg; |
| | | import org.opends.server.replication.protocol.MonitorRequestMsg; |
| | | import org.opends.server.replication.protocol.ProtocolVersion; |
| | | import org.opends.server.replication.protocol.ReplServerStartDSMsg; |
| | | import org.opends.server.replication.protocol.ReplServerStartMsg; |
| | | import org.opends.server.replication.protocol.ReplSessionSecurity; |
| | | import org.opends.server.replication.protocol.ReplicaOfflineMsg; |
| | | import org.opends.server.replication.protocol.ReplicationMsg; |
| | | import org.opends.server.replication.protocol.ServerStartMsg; |
| | | import org.opends.server.replication.protocol.Session; |
| | |
| | | { |
| | | private static final ConnectedRS NO_CONNECTED_RS = new ConnectedRS(NO_CONNECTED_SERVER); |
| | | private static final ConnectedRS CONNECTION_REFUSED = new ConnectedRS(NO_CONNECTED_SERVER); |
| | | /** Handshake result only. Never installed as the broker's current RS. */ |
| | | private static final ConnectedRS START_REPLY_TIMED_OUT = new ConnectedRS(NO_CONNECTED_SERVER); |
| | | |
| | | /** The info of the RS we are connected to. */ |
| | | private final ReplicationServerInfo rsInfo; |
| | |
| | | * while it closes the session, so that the close never comes after the end of the stop. |
| | | */ |
| | | private boolean ended; |
| | | /** Socket of the replacement handshake, before it becomes the broker's published session. */ |
| | | @GuardedBy("this") |
| | | private Socket replacementSocket; |
| | | /** The connection timeout the deadlines were set from, in milliseconds. */ |
| | | private final long connectionTimeoutMS; |
| | | |
| | |
| | | */ |
| | | // @NotNull // for the reference |
| | | private final AtomicReference<ConnectedRS> connectedRS = new AtomicReference<>(ConnectedRS.noConnectedRS()); |
| | | |
| | | /** Preparation refusals awaiting a route to the exporter, owned by the receiver thread. */ |
| | | private final Map<Integer, PendingInitializationRefusal> pendingInitializationRefusals = new HashMap<>(); |
| | | |
| | | private static final class PendingInitializationRefusal |
| | | { |
| | | private final ErrorMsg message; |
| | | private final long createdNanos = System.nanoTime(); |
| | | private Session lastSession; |
| | | |
| | | private PendingInitializationRefusal(ErrorMsg message) |
| | | { |
| | | this.message = message; |
| | | } |
| | | } |
| | | /** Our replication domain. */ |
| | | private final ReplicationDomain domain; |
| | | /** |
| | |
| | | private final AtomicReference<Topology> topology = new AtomicReference<>(new Topology()); |
| | | @GuardedBy("this") |
| | | private volatile int updateDoneCount; |
| | | private volatile boolean connectRequiresRecovery; |
| | | |
| | | private enum RecoveryState { READY, RUNNING, ABORTED } |
| | | |
| | | private final Object recoveryMonitor = new Object(); |
| | | private volatile RecoveryState recoveryState = RecoveryState.READY; |
| | | |
| | | /** |
| | | * This integer defines when the best replication server checking algorithm |
| | |
| | | */ |
| | | private int mustRunBestServerCheckingAlgorithm; |
| | | |
| | | /** Owned by the receiver, which continues replay while the old session finishes writing. */ |
| | | private PlannedSwitch plannedSwitch; |
| | | |
| | | private static final class PlannedSwitch |
| | | { |
| | | private final Session session; |
| | | private final AtomicBoolean completed = new AtomicBoolean(); |
| | | private ScheduledFuture<?> deadline; |
| | | |
| | | PlannedSwitch(Session session) |
| | | { |
| | | this.session = session; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * The monitor provider for this replication domain. |
| | | * <p> |
| | |
| | | } |
| | | |
| | | /** |
| | | * Contacts all replication servers to get information from them and being |
| | | * able to choose the more suitable. |
| | | * @return the collected information. |
| | | * Collects replies for server selection and remembers an RS that did not answer its start message. |
| | | * Prefer a different RS from the one whose session just ended. |
| | | */ |
| | | private Map<Integer, ReplicationServerInfo> collectReplicationServersInfo() |
| | | private String collectReplicationServersInfo(Map<Integer, ReplicationServerInfo> rsInfos, String previousRS) |
| | | { |
| | | final Map<Integer, ReplicationServerInfo> rsInfos = new ConcurrentSkipListMap<>(); |
| | | |
| | | String timedOutRS = null; |
| | | for (String serverUrl : getReplicationServerUrls()) |
| | | { |
| | | // Connect to server + get and store info about it |
| | | final ConnectedRS rs = performPhaseOneHandshake(serverUrl, false); |
| | | final ReplicationServerInfo rsInfo = rs.rsInfo; |
| | | if (rsInfo != null) |
| | | final ConnectedRS probe = performPhaseOneHandshake(serverUrl, false, false); |
| | | if (probe.rsInfo != null) |
| | | { |
| | | rsInfos.put(rsInfo.getServerId(), rsInfo); |
| | | rsInfos.put(probe.getServerId(), probe.rsInfo); |
| | | } |
| | | else if (probe == ConnectedRS.START_REPLY_TIMED_OUT && (timedOutRS == null || timedOutRS.equals(previousRS))) |
| | | { |
| | | timedOutRS = serverUrl; |
| | | } |
| | | } |
| | | |
| | | return rsInfos; |
| | | return timedOutRS; |
| | | } |
| | | |
| | | /** |
| | |
| | | * decide with which RS the full handshake (phase 1 then phase 2) will be |
| | | * finally performed. |
| | | * |
| | | * @param formerServerURL the previous server on the first reconnect after losing its session, or null |
| | | * @param previousRS the RS whose established session just ended, or null outside the first failover attempt |
| | | * @throws NumberFormatException address was invalid |
| | | */ |
| | | private void connectAsDataServer(String formerServerURL) |
| | | private void connectAsDataServer(String previousRS) |
| | | { |
| | | /* |
| | | * If a first connect or a connection failure occur, we go through here. |
| | |
| | | } |
| | | |
| | | // Get info from every available replication servers |
| | | Map<Integer, ReplicationServerInfo> rsInfos = |
| | | collectReplicationServersInfo(); |
| | | final Map<Integer, ReplicationServerInfo> rsInfos = new ConcurrentSkipListMap<>(); |
| | | final String timedOutRS = collectReplicationServersInfo(rsInfos, previousRS); |
| | | computeNewTopology(toRSInfos(rsInfos)); |
| | | |
| | | if (rsInfos.isEmpty()) |
| | | final boolean hasReplies = !rsInfos.isEmpty(); |
| | | final boolean canRetry = previousRS != null && stopping == null && !permanentlyStopped; |
| | | String electedURL = null; |
| | | if (hasReplies) |
| | | { |
| | | final RSEvaluations evals = computeBestReplicationServer(true, -1, state, |
| | | rsInfos, serverId, getGroupId(), getGenerationID()); |
| | | if (logger.isTraceEnabled()) |
| | | { |
| | | debugInfo("phase 2 : will perform PhaseOneH with the preferred RS=" + evals.getBestRS()); |
| | | } |
| | | electedURL = evals.getBestRS().getServerURL(); |
| | | } |
| | | else if (canRetry) |
| | | { |
| | | // A live RS can miss one start reply under load. Use the retry to establish the |
| | | // actual session before declaring isolation and rejecting LDAP writes. |
| | | electedURL = timedOutRS; |
| | | } |
| | | |
| | | if (electedURL == null) |
| | | { |
| | | setConnectedRS(ConnectedRS.noConnectedRS()); |
| | | } |
| | | else |
| | | { |
| | | // At least one server answered, find the best one. |
| | | RSEvaluations evals = computeBestReplicationServer(true, -1, state, |
| | | rsInfos, serverId, getGroupId(), getGenerationID()); |
| | | |
| | | // Best found, now initialize connection to this one (handshake phase 1) |
| | | if (logger.isTraceEnabled()) |
| | | final boolean canRetryElected = canRetry && hasReplies; |
| | | ConnectedRS electedRS = performPhaseOneHandshake(electedURL, true, canRetryElected); |
| | | if (electedRS.rsInfo == null && canRetryElected && stopping == null && !permanentlyStopped) |
| | | { |
| | | debugInfo("phase 2 : will perform PhaseOneH with the preferred RS=" + evals.getBestRS()); |
| | | } |
| | | |
| | | final ReplicationServerInfo preferred = evals.getBestRS(); |
| | | ConnectedRS electedRS = performPhaseOneHandshake(preferred.getServerURL(), true); |
| | | if (electedRS == ConnectedRS.CONNECTION_REFUSED && preferred.getServerURL().equals(formerServerURL) |
| | | && stopping == null && !permanentlyStopped) |
| | | { |
| | | // Discovery can still see the former RS while its listener is closing. |
| | | electedRS = tryAnotherDiscoveryResponder(rsInfos, preferred.getServerId()); |
| | | } |
| | | final ReplicationServerInfo electedRsInfo = electedRS.rsInfo; |
| | | if (electedRsInfo != null) |
| | | { |
| | | /* |
| | | Update replication server info with potentially more up to date |
| | | data (server state for instance may have changed) |
| | | */ |
| | | rsInfos.put(electedRsInfo.getServerId(), electedRsInfo); |
| | | |
| | | // Handshake phase 1 exchange went well |
| | | |
| | | // Compute in which status we are starting the session to tell the RS |
| | | final ServerStatus initStatus = computeInitialServerStatus( |
| | | electedRsInfo.getGenerationId(), electedRsInfo.getServerState(), |
| | | electedRsInfo.getDegradedStatusThreshold(), getGenerationID()); |
| | | |
| | | // Perform session start (handshake phase 2) |
| | | final TopologyMsg topologyMsg = |
| | | performPhaseTwoHandshake(electedRS, initStatus); |
| | | |
| | | if (topologyMsg != null) // Handshake phase 2 exchange went well |
| | | if (electedRS == ConnectedRS.START_REPLY_TIMED_OUT) |
| | | { |
| | | connectToReplicationServer(electedRS, initStatus, topologyMsg); |
| | | } // Could perform handshake phase 2 with best |
| | | } // Could perform handshake phase 1 with best |
| | | electedRS = performPhaseOneHandshake(electedURL, true, false); |
| | | } |
| | | else if (electedURL.equals(previousRS)) |
| | | { |
| | | final ReplicationServerInfo responder = electedRS == ConnectedRS.CONNECTION_REFUSED |
| | | ? selectDiscoveryResponder(rsInfos, previousRS) : null; |
| | | if (responder != null) |
| | | { |
| | | electedRS = connectToDiscoveryResponder(responder); |
| | | } |
| | | else if (timedOutRS != null && !electedURL.equals(timedOutRS)) |
| | | { |
| | | // The other RS can still accept a session after missing its discovery reply. |
| | | electedRS = performPhaseOneHandshake(timedOutRS, true, false); |
| | | } |
| | | } |
| | | } |
| | | final StopInProgress stop = stopping; |
| | | if (electedRS.rsInfo != null) |
| | | { |
| | | finishElectedConnection(electedRS, rsInfos); |
| | | } |
| | | else if (stop != null && electedURL.equals(previousRS)) |
| | | { |
| | | connectToReplacementForStop(stop, previousRS, rsInfos); |
| | | } |
| | | } |
| | | |
| | | // connectedRS has been updated by calls above, reload it |
| | |
| | | } |
| | | } |
| | | |
| | | /** Tries one compatible discovery responder before publishing isolation. */ |
| | | private ConnectedRS tryAnotherDiscoveryResponder(Map<Integer, ReplicationServerInfo> rsInfos, int refusedServerId) |
| | | /** Opens the selected RS session using the fresh state returned by its start reply. */ |
| | | private void finishElectedConnection(ConnectedRS electedRS, Map<Integer, ReplicationServerInfo> rsInfos) |
| | | { |
| | | final ReplicationServerInfo info = electedRS.rsInfo; |
| | | rsInfos.put(info.getServerId(), info); |
| | | final ServerStatus status = computeInitialServerStatus(info.getGenerationId(), info.getServerState(), |
| | | info.getDegradedStatusThreshold(), getGenerationID()); |
| | | final TopologyMsg topologyMsg = performPhaseTwoHandshake(electedRS, status); |
| | | if (topologyMsg != null) |
| | | { |
| | | connectToReplicationServer(electedRS, status, topologyMsg); |
| | | } |
| | | } |
| | | |
| | | /** Selects a compatible discovery responder other than the former replication server. */ |
| | | private ReplicationServerInfo selectDiscoveryResponder(Map<Integer, ReplicationServerInfo> rsInfos, String formerURL) |
| | | { |
| | | final Map<Integer, ReplicationServerInfo> candidates = new TreeMap<>(rsInfos); |
| | | candidates.remove(refusedServerId); |
| | | candidates.values().removeIf(info -> !hasCompatibleGeneration(info)); |
| | | candidates.values().removeIf(info -> formerURL.equals(info.getServerURL()) || !hasCompatibleGeneration(info)); |
| | | if (candidates.isEmpty()) |
| | | { |
| | | return ConnectedRS.noConnectedRS(); |
| | | return null; |
| | | } |
| | | return computeBestReplicationServer(true, -1, state, candidates, getServerId(), getGroupId(), |
| | | getGenerationID()).getBestRS(); |
| | | } |
| | | |
| | | final RSEvaluations evals = computeBestReplicationServer(true, -1, state, candidates, getServerId(), getGroupId(), |
| | | getGenerationID()); |
| | | final ConnectedRS replacement = performPhaseOneHandshake(evals.getBestRS().getServerURL(), true); |
| | | private ConnectedRS connectToDiscoveryResponder(ReplicationServerInfo responder) |
| | | { |
| | | final ConnectedRS replacement = performPhaseOneHandshake(responder.getServerURL(), true, false); |
| | | // The generation may have changed since discovery. |
| | | if (replacement.rsInfo != null && !hasCompatibleGeneration(replacement.rsInfo)) |
| | | { |
| | |
| | | return replacement; |
| | | } |
| | | |
| | | /** Tries one discovery responder when the former RS can no longer take the offline marker. */ |
| | | private void connectToReplacementForStop(StopInProgress stop, String formerURL, |
| | | Map<Integer, ReplicationServerInfo> rsInfos) |
| | | { |
| | | final ReplicationServerInfo responder = selectDiscoveryResponder(rsInfos, formerURL); |
| | | if (responder == null) |
| | | { |
| | | return; |
| | | } |
| | | |
| | | final Socket socket = new Socket(); |
| | | synchronized (stop) |
| | | { |
| | | if (stop.gaveUp || stop.ended || permanentlyStopped |
| | | || stop.bounded && System.nanoTime() - stop.writeDeadline >= 0) |
| | | { |
| | | close(socket); |
| | | return; |
| | | } |
| | | stop.replacementSocket = socket; |
| | | } |
| | | |
| | | boolean connected = false; |
| | | try |
| | | { |
| | | final ConnectedRS replacement = performPhaseOneHandshake(responder.getServerURL(), true, false, socket); |
| | | // A reset between discovery and the new start reply can change the RS generation. |
| | | if (hasCompatibleGeneration(replacement.rsInfo) && !stop.gaveUp) |
| | | { |
| | | finishElectedConnection(replacement, rsInfos); |
| | | connected = connectedRS.get() == replacement; |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | synchronized (stop) |
| | | { |
| | | stop.replacementSocket = null; |
| | | } |
| | | if (!connected) |
| | | { |
| | | close(socket); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private boolean hasCompatibleGeneration(ReplicationServerInfo info) |
| | | { |
| | | return info.getGenerationId() == -1 || info.getGenerationId() == getGenerationID(); |
| | | return info != null && (info.getGenerationId() == -1 || info.getGenerationId() == getGenerationID()); |
| | | } |
| | | |
| | | private void computeNewTopology(List<RSInfo> newRSInfos) |
| | |
| | | * Do we keep session opened or not after handshake. Use true if want |
| | | * to perform handshake phase 2 with the same session and keep the |
| | | * session to create as the current one. |
| | | * @return The answer from the server . Null if could not get an answer. |
| | | * @param retryStartTimeout whether a start reply timeout on this attempt can be retried |
| | | * @return The result of the handshake, including whether the start reply timed out |
| | | */ |
| | | private ConnectedRS performPhaseOneHandshake(String serverURL, boolean keepSession) |
| | | private ConnectedRS performPhaseOneHandshake(String serverURL, boolean keepSession, boolean retryStartTimeout) |
| | | { |
| | | return performPhaseOneHandshake(serverURL, keepSession, retryStartTimeout, new Socket()); |
| | | } |
| | | |
| | | private ConnectedRS performPhaseOneHandshake(String serverURL, boolean keepSession, boolean retryStartTimeout, |
| | | Socket socket) |
| | | { |
| | | Session newSession = null; |
| | | Socket socket = null; |
| | | boolean hasConnected = false; |
| | | ConnectedRS failure = ConnectedRS.noConnectedRS(); |
| | | boolean waitingForStartReply = false; |
| | | boolean startReplyTimedOut = false; |
| | | LocalizableMessage errorMessage = null; |
| | | |
| | | try |
| | | { |
| | | // Open a socket connection to the next candidate. |
| | | socket = new Socket(); |
| | | socket.setReuseAddress(true); |
| | | socket.setReceiveBufferSize(1000000); |
| | | socket.setTcpNoDelay(true); |
| | |
| | | throw new ConnectException("Connection to " + serverURL |
| | | + " is a TCP self-connect, no replication server is listening"); |
| | | } |
| | | newSession = replSessionSecurity.createClientSession(socket, timeoutMS); |
| | | newSession = replSessionSecurity.createClientSession(socket, timeoutMS, "DS", getServerId(), getBaseDN()); |
| | | boolean isSslEncryption = replSessionSecurity.isSslEncryption(); |
| | | |
| | | // Send our ServerStartMsg. |
| | |
| | | |
| | | // Read the ReplServerStartMsg or ReplServerStartDSMsg that should |
| | | // come back. |
| | | waitingForStartReply = true; |
| | | ReplicationMsg msg = newSession.receive(); |
| | | waitingForStartReply = false; |
| | | if (logger.isTraceEnabled()) |
| | | { |
| | | debugInfo("RB HANDSHAKE SENT:\n" + serverStartMsg + "\nAND RECEIVED:\n" |
| | |
| | | catch (SocketTimeoutException e) |
| | | { |
| | | logger.traceException(e); |
| | | startReplyTimedOut = waitingForStartReply; |
| | | errorMessage = WARN_TIMEOUT_CONNECTING_TO_RS.get(getServerId(), serverURL, getBaseDN()); |
| | | } |
| | | catch (Exception e) |
| | |
| | | * a schedule, and a server which cannot be reached over several reconnections is |
| | | * a server whose configuration or certificate needs looking at. |
| | | * |
| | | * The severity says what the failure cost this broker, not what the message is |
| | | * named: the elected server keeps the error it was reported with, and a server |
| | | * which was only contacted is a warning, so that a broker which does find a |
| | | * server to work with does not raise an error over the one it did not need. |
| | | * An unsuccessful attempt to establish the elected session is an error. |
| | | * A discovery probe or a start reply timeout scheduled for retry is a warning. |
| | | * ERR_DS_DN_DOES_NOT_MATCH is the one message which reaches the second branch |
| | | * under an ERR_ name -- it is set without setting hasConnected -- and it is a |
| | | * permanent misconfiguration rather than a transient. It still goes out as an |
| | |
| | | * without, and where it is only contacted the broker has another server to work |
| | | * with. Before this, that path logged nothing above trace either way. |
| | | */ |
| | | if (keepSession) |
| | | if (keepSession && !(startReplyTimedOut && retryStartTimeout)) |
| | | { |
| | | logger.error(errorMessage); |
| | | } |
| | |
| | | } |
| | | } |
| | | setConnectedRS(ConnectedRS.noConnectedRS()); |
| | | return failure; |
| | | return startReplyTimedOut ? ConnectedRS.START_REPLY_TIMED_OUT : failure; |
| | | } |
| | | |
| | | /** |
| | |
| | | } |
| | | |
| | | ConnectedRS rs = connectedRS.get(); |
| | | String formerServerURL = infiniteTry && failingSession != null && failingSession == rs.session && !connectionError |
| | | String previousRS = infiniteTry && failingSession != null && failingSession == rs.session && !connectionError |
| | | ? rs.rsInfo.getServerURL() : null; |
| | | if (failingSession == rs.session && !rs.equals(ConnectedRS.noConnectedRS())) |
| | | { |
| | |
| | | { |
| | | try |
| | | { |
| | | final String previousServerURL = formerServerURL; |
| | | formerServerURL = null; |
| | | connectAsDataServer(previousServerURL); |
| | | final String failedRS = previousRS; |
| | | previousRS = null; |
| | | connectAsDataServer(failedRS); |
| | | rs = connectedRS.get(); |
| | | } |
| | | catch (Exception e) |
| | |
| | | return publish(msg, false, retryOnFailure, null); |
| | | } |
| | | |
| | | /** Publishes the message on the supplied session while it is still current. */ |
| | | boolean publishOnSession(ReplicationMsg msg, Session session) |
| | | { |
| | | return session != null && publish(msg, false, false, session); |
| | | } |
| | | |
| | | /** Retains a refusal if the receiver has to retry the reconnect after finishing the import. */ |
| | | void publishInitializationRefusalAfterReconnect(ErrorMsg refusal) |
| | | { |
| | | pendingInitializationRefusals.put(refusal.getDestination(), new PendingInitializationRefusal(refusal)); |
| | | } |
| | | |
| | | private void publishPendingInitializationRefusals(Session session, int rsServerId) |
| | | { |
| | | if (pendingInitializationRefusals.isEmpty()) |
| | | { |
| | | return; |
| | | } |
| | | final long now = System.nanoTime(); |
| | | final Map<Integer, DSInfo> replicas = getReplicaInfos(); |
| | | final Iterator<PendingInitializationRefusal> refusals = pendingInitializationRefusals.values().iterator(); |
| | | while (refusals.hasNext()) |
| | | { |
| | | final PendingInitializationRefusal refusal = refusals.next(); |
| | | // The exporter's wait for preparation is bounded to two minutes. |
| | | if (now - refusal.createdNanos >= TimeUnit.MINUTES.toNanos(2)) |
| | | { |
| | | refusals.remove(); |
| | | continue; |
| | | } |
| | | final DSInfo exporter = replicas.get(refusal.message.getDestination()); |
| | | if (exporter != null && session != refusal.lastSession && session.getProtocolVersion() >= REPLICATION_PROTOCOL_V9 |
| | | && publishOnSession(refusal.message, session)) |
| | | { |
| | | refusal.lastSession = session; |
| | | if (exporter.getRsId() == rsServerId) |
| | | { |
| | | refusals.remove(); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Returns the session this broker publishes on, which a recovery started for it publishes on: |
| | | * see {@link #publishRecovery(ReplicationMsg, Session)}. |
| | |
| | | * @param msg the message to publish |
| | | * @param session the session the recovery publishes on, as {@link #getSession()} returned it |
| | | * when the recovery was started for it |
| | | * @return {@code false} if the broker refused the message: no replication |
| | | * server was reachable, the session is not the one the broker publishes |
| | | * on anymore, or the broker was stopped; {@code true} once the session |
| | | * took it - which still drops it if it is closing, as it does any |
| | | * message the broker publishes. |
| | | * @return {@code true} if the session accepted the message, or {@code false} if |
| | | * the broker no longer publishes on that session, was stopped, or the |
| | | * session refused the message. |
| | | */ |
| | | public boolean publishRecovery(ReplicationMsg msg, Session session) |
| | | { |
| | | return publish(msg, true, true, session); |
| | | return session != null && publish(msg, true, true, session); |
| | | } |
| | | |
| | | /** |
| | | * Publish a message to the other servers. |
| | | * @param msg the message to publish |
| | | * @param recoveryMsg the message is a recovery LocalizableMessage |
| | | * @param recoveryMsg whether the message belongs to recovery |
| | | * @param retryOnFailure whether retry should be done on failure |
| | | * @param recoverySession the only session a recovery message may be published on |
| | | * @return whether the message was successfully sent. |
| | | * @param requiredSession the only session that may receive this message, or null for an unbound publication |
| | | * @return whether the session accepted the message. |
| | | */ |
| | | private boolean publish(ReplicationMsg msg, boolean recoveryMsg, |
| | | boolean retryOnFailure, Session recoverySession) |
| | | boolean retryOnFailure, Session requiredSession) |
| | | { |
| | | boolean done = false; |
| | | |
| | | while (!done && !shutdown && !permanentlyStopped && !gaveUpForTheStop()) |
| | | while (!shutdown && !permanentlyStopped && !gaveUpForTheStop()) |
| | | { |
| | | if (connectionError) |
| | | { |
| | |
| | | announcement that the replica goes offline, which carries its newest |
| | | CSN, would get to the replication server ahead of the changes it misses. |
| | | */ |
| | | if (!recoveryMsg && connectRequiresRecovery && msg instanceof UpdateMsg) |
| | | if (!recoveryMsg && msg instanceof UpdateMsg && recoveryState != RecoveryState.READY) |
| | | { |
| | | return false; |
| | | final StopInProgress stop = stopping; |
| | | // The old window can run out before its session ever sees the offline write. |
| | | // This admitted marker can wait because its caller released the pending-change lock. |
| | | if (!(msg instanceof ReplicaOfflineMsg) || !retryOnFailure || stop == null || !awaitRecoveryForStop(stop)) |
| | | { |
| | | return false; |
| | | } |
| | | // A reconnect while waiting may have replaced both the session and its send window. |
| | | continue; |
| | | } |
| | | /* |
| | | A recovery message is for the session the recovery was started for: |
| | | the one which replaced it has a recovery of its own, from what its |
| | | replication server holds. The write below takes the message only on |
| | | the session read here. |
| | | */ |
| | | if (recoveryMsg && (recoverySession == null || currentSession != recoverySession)) |
| | | // Recovery belongs to the session that requested it. A replay acknowledgement |
| | | // likewise belongs to the RS that delivered the update, even if its ID reconnects. |
| | | if (requiredSession != null && currentSession != requiredSession) |
| | | { |
| | | return false; |
| | | } |
| | |
| | | final Session session = connectedRS.get().session; |
| | | if (session != null && session == currentSession) |
| | | { |
| | | session.publish(msg); |
| | | done = true; |
| | | final boolean published = session.publish(msg, null); |
| | | if (!published && msg instanceof UpdateMsg) |
| | | { |
| | | // A refused update cannot be acknowledged by the peer. |
| | | currentWindowSemaphore.release(); |
| | | if (retryOnFailure && !recoveryMsg && session.isClosingForSwitch() |
| | | && (((UpdateMsg) msg).contributesToDomainState() || (stop != null && msg instanceof ReplicaOfflineMsg))) |
| | | { |
| | | // The next RS can choose its recovery start before this publication |
| | | // advances the local CSN. Retry on that session to keep this change |
| | | // ahead of subsequent local writes. A shutdown announcement likewise |
| | | // needs a writable session before the stop's existing deadline. |
| | | connectPhaseLock.wait(100); |
| | | continue; |
| | | } |
| | | } |
| | | return published; |
| | | } |
| | | } |
| | | } |
| | |
| | | } |
| | | } |
| | | } |
| | | /* |
| | | * The loop also ends when the broker is stopped, or gave a message up for the stop, and then |
| | | * nothing was written to any session: a caller told the message was published would report as |
| | | * sent a message which never reached the wire. |
| | | */ |
| | | return done; |
| | | return false; |
| | | } |
| | | |
| | | /** Tells whether a publish gave its message up for the stop in progress, if there is one. */ |
| | |
| | | { |
| | | while (!shutdown && !permanentlyStopped) |
| | | { |
| | | ConnectedRS rs = connectedRS.get(); |
| | | if (!rs.isConnected()) |
| | | final ConnectedRS rs = connectedRS.get(); |
| | | final Session session = rs.session; |
| | | if (plannedSwitch != null && plannedSwitch.session != session) |
| | | { |
| | | finishPlannedSwitch(plannedSwitch.session); |
| | | } |
| | | if (session == null) |
| | | { |
| | | if (reconnectOnFailure) |
| | | { |
| | |
| | | final int serverId = getServerId(); |
| | | final DN baseDN = getBaseDN(); |
| | | final int previousRsServerID = rs.getServerId(); |
| | | publishPendingInitializationRefusals(session, previousRsServerID); |
| | | try |
| | | { |
| | | ReplicationMsg msg = rs.session.receive(); |
| | | ReplicationMsg msg = session.receive(); |
| | | if (msg instanceof UpdateMsg) |
| | | { |
| | | final UpdateMsg update = (UpdateMsg) msg; |
| | | if (update.isAssured() && update.getAssuredMode() == AssuredMode.SAFE_READ_MODE |
| | | && rs.getGroupId() == getGroupId() && session.getProtocolVersion() >= REPLICATION_PROTOCOL_V2) |
| | | { |
| | | update.setAcknowledgementSender(ack -> publish(ack, false, false, session)); |
| | | } |
| | | synchronized (this) |
| | | { |
| | | rcvWindow--; |
| | |
| | | } |
| | | else if (msg instanceof StopMsg) |
| | | { |
| | | // RS performs a proper disconnection |
| | | logger.warn(WARN_REPLICATION_SERVER_PROPERLY_DISCONNECTED, previousRsServerID, rs.replicationServer, |
| | | serverId, baseDN); |
| | | if (!finishPlannedSwitch(session)) |
| | | { |
| | | logger.warn(WARN_REPLICATION_SERVER_PROPERLY_DISCONNECTED, previousRsServerID, rs.replicationServer, |
| | | serverId, baseDN); |
| | | } |
| | | |
| | | // Try to find a suitable RS |
| | | reStart(rs.session, true); |
| | | reStart(session, true); |
| | | } |
| | | else if (msg instanceof MonitorMsg) |
| | | { |
| | |
| | | disconnect properly and let the connection algorithm re-connect to |
| | | best replication server |
| | | */ |
| | | if (reconnectToTheBestRS) |
| | | if (reconnectToTheBestRS && plannedSwitch == null) |
| | | { |
| | | mustRunBestServerCheckingAlgorithm++; |
| | | if (mustRunBestServerCheckingAlgorithm == 2) |
| | |
| | | { |
| | | debugInfo("best replication servers evaluation results: " + evals); |
| | | } |
| | | reStart(true); |
| | | switchReplicationServer(session); |
| | | } |
| | | |
| | | // Reset wait time before next computation of best server |
| | |
| | | } |
| | | } |
| | | } |
| | | else if (msg instanceof InitializeTargetMsg && session.isClosingForSwitch()) |
| | | { |
| | | // A full import needs a session that can still publish FULL_UPDATE. |
| | | continue; |
| | | } |
| | | else |
| | | { |
| | | return msg; |
| | |
| | | } |
| | | catch (SocketTimeoutException e) |
| | | { |
| | | throw e; |
| | | if (!finishPlannedSwitch(session)) |
| | | { |
| | | throw e; |
| | | } |
| | | abortPlannedSwitch(session, e); |
| | | if (reconnectOnFailure) |
| | | { |
| | | reStart(session, true); |
| | | } |
| | | else |
| | | { |
| | | break; |
| | | } |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | final boolean wasSwitching = finishPlannedSwitch(session); |
| | | logger.traceException(e); |
| | | |
| | | if (!shutdown) |
| | | { |
| | | if (rs.session == null || !rs.session.closeInitiated()) |
| | | final boolean locallyClosed = wasSwitching ? session.isSocketCloseRequested() : session.closeInitiated(); |
| | | if (!locallyClosed) |
| | | { |
| | | // We did not initiate the close on our side, log an error message. |
| | | logger.error(WARN_REPLICATION_SERVER_BADLY_DISCONNECTED, |
| | |
| | | break; // does not seem necessary to explicitly disconnect .. |
| | | } |
| | | |
| | | reStart(rs.session, true); |
| | | reStart(session, true); |
| | | } |
| | | } |
| | | } |
| | | if (plannedSwitch != null) |
| | | { |
| | | finishPlannedSwitch(plannedSwitch.session); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | private void switchReplicationServer(Session session) |
| | | { |
| | | if (session.getProtocolVersion() < REPLICATION_PROTOCOL_V4) |
| | | { |
| | | reStart(session, true); |
| | | return; |
| | | } |
| | | |
| | | final long timeout = Session.plannedSwitchTimeoutMillis(MultimasterReplication.getConnectionTimeoutMS()); |
| | | final PlannedSwitch pending = new PlannedSwitch(session); |
| | | pending.deadline = DirectoryServer.getInstance().getServerContext().getCronExecutorService().schedule(() -> { |
| | | if (pending.completed.compareAndSet(false, true)) |
| | | { |
| | | abortPlannedSwitch(session, new SocketTimeoutException("Timed out closing the old replication session")); |
| | | } |
| | | }, timeout, TimeUnit.MILLISECONDS); |
| | | plannedSwitch = pending; |
| | | |
| | | // The old RS can be writing to this DS while it reads our final StopMsg. |
| | | // Keep the receiver running even if writing the StopMsg blocks. |
| | | if (!session.closeForSwitch(send -> { |
| | | final DirectoryThread sender = new DirectoryThread(send, |
| | | "Replication switch from " + session.getReadableRemoteAddress()); |
| | | sender.setDaemon(true); |
| | | sender.start(); |
| | | })) |
| | | { |
| | | finishPlannedSwitch(session); |
| | | reStart(session, true); |
| | | } |
| | | } |
| | | |
| | | private boolean finishPlannedSwitch(Session session) |
| | | { |
| | | if (plannedSwitch == null || plannedSwitch.session != session) |
| | | { |
| | | return false; |
| | | } |
| | | plannedSwitch.completed.set(true); |
| | | plannedSwitch.deadline.cancel(false); |
| | | plannedSwitch = null; |
| | | return true; |
| | | } |
| | | |
| | | private void abortPlannedSwitch(Session session, SocketTimeoutException cause) |
| | | { |
| | | if (session.isSocketCloseRequested()) |
| | | { |
| | | return; |
| | | } |
| | | logger.warn(LocalizableMessage.raw("Timed out switching from replication server %s for domain \"%s\".", |
| | | session.getReadableRemoteAddress(), getBaseDN())); |
| | | session.abort(cause); |
| | | } |
| | | |
| | | /** |
| | | * Gets the States of all the Replicas currently in the Topology. When this |
| | | * method is called, a Monitoring message will be sent to the Replication |
| | |
| | | // End blocked writes too: closing in order could wait for the peer to read forever. |
| | | // stop.end() takes this monitor, so this close cannot reach a later session. |
| | | stop.gaveUp = true; |
| | | close(stop.replacementSocket); |
| | | final Session session = connectedRS.get().session; |
| | | if (session != null) |
| | | { |
| | |
| | | } |
| | | |
| | | stop.gaveUp = true; |
| | | // The replacement's socket is still private until both handshake phases finish. |
| | | close(stop.replacementSocket); |
| | | /* |
| | | * Read after the mark: a connection under way leaves no session to close here, and publish() |
| | | * writes nothing to the one it then opens, as it reads the mark again under the lock that |
| | |
| | | } |
| | | |
| | | /** |
| | | * Set the connectRequiresRecovery to the provided value. |
| | | * This flag is used to indicate if a recovery of Update is necessary |
| | | * after a reconnection to a RS. |
| | | * It is the responsibility of the ReplicationDomain to set it during the |
| | | * sessionInitiated phase. |
| | | * |
| | | * @param b the new value of the connectRequiresRecovery. |
| | | * Sets the recovery state when a session requests missing changes or their publication completes. |
| | | * @param required whether the session is waiting for its missing changes |
| | | */ |
| | | public void setRecoveryRequired(boolean b) |
| | | public void setRecoveryRequired(boolean required) |
| | | { |
| | | connectRequiresRecovery = b; |
| | | setRecoveryState(required ? RecoveryState.RUNNING : RecoveryState.READY); |
| | | } |
| | | |
| | | /** The publisher exited with changes still missing. Only a successful recovery releases the fence. */ |
| | | public void recoveryAborted() |
| | | { |
| | | setRecoveryState(RecoveryState.ABORTED); |
| | | } |
| | | |
| | | private void setRecoveryState(RecoveryState state) |
| | | { |
| | | synchronized (recoveryMonitor) |
| | | { |
| | | recoveryState = state; |
| | | recoveryMonitor.notifyAll(); |
| | | } |
| | | } |
| | | |
| | | private boolean awaitRecoveryForStop(StopInProgress stop) throws InterruptedException |
| | | { |
| | | synchronized (recoveryMonitor) |
| | | { |
| | | while (recoveryState == RecoveryState.RUNNING && !stop.gaveUp) |
| | | { |
| | | if (stop.bounded) |
| | | { |
| | | final long left = stop.writeDeadline - System.nanoTime(); |
| | | if (left <= 0) |
| | | { |
| | | return false; |
| | | } |
| | | TimeUnit.NANOSECONDS.timedWait(recoveryMonitor, left); |
| | | } |
| | | else |
| | | { |
| | | recoveryMonitor.wait(); |
| | | } |
| | | } |
| | | return recoveryState == RecoveryState.READY && !stop.gaveUp; |
| | | } |
| | | } |
| | | |
| | | /** |
| | |
| | | import java.util.Map; |
| | | import java.util.Map.Entry; |
| | | import java.util.Set; |
| | | import java.util.UUID; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | import java.util.concurrent.ExecutorService; |
| | | import java.util.concurrent.Executors; |
| | |
| | | import org.opends.server.replication.protocol.ReplicationMsg; |
| | | import org.opends.server.replication.protocol.ResetGenerationIdMsg; |
| | | import org.opends.server.replication.protocol.RoutableMsg; |
| | | import org.opends.server.replication.protocol.Session; |
| | | import org.opends.server.replication.protocol.TopologyMsg; |
| | | import org.opends.server.replication.protocol.UpdateMsg; |
| | | import org.opends.server.tasks.InitializeTargetTask; |
| | |
| | | " Error Msg received: " + errorMsg); |
| | | } |
| | | |
| | | // consider only ErrorMsg that relate to the current import/export. |
| | | // ">=" and not ">": with all servers on one host the whole |
| | | // request/rejection round-trip can complete within the millisecond |
| | | // this context was created in (issue #861) |
| | | if (errorMsg.getCreationTime() >= ieCtx.startTime) |
| | | // Consider only errors that relate to the current import or export. |
| | | if (isCurrentInitializationError(errorMsg, ieCtx)) |
| | | { |
| | | processErrorMsg(errorMsg, ieCtx); |
| | | } |
| | |
| | | if (ieCtx != null) |
| | | { |
| | | InitializeRcvAckMsg ackMsg = (InitializeRcvAckMsg) msg; |
| | | ieCtx.setAckVal(ackMsg.getSenderID(), ackMsg.getNumAck()); |
| | | final String attemptId = ackMsg.getInitializationAttemptId(); |
| | | if (attemptId == null) |
| | | { |
| | | ieCtx.setAckVal(ackMsg.getSenderID(), ackMsg.getNumAck()); |
| | | } |
| | | else if (ieCtx.matchesExportAttempt(attemptId, ackMsg.getSenderID())) |
| | | { |
| | | ieCtx.remotePreparationReady = true; |
| | | } |
| | | } |
| | | // Trash this msg When no input/export is running/should never happen |
| | | } |
| | |
| | | } |
| | | |
| | | numRcvdUpdates.incrementAndGet(); |
| | | if (update.isAssured() |
| | | && broker.getRsGroupId() == getGroupId() |
| | | && update.getAssuredMode() == AssuredMode.SAFE_READ_MODE) |
| | | if (update.getAcknowledgementSender() != null) |
| | | { |
| | | assuredSrReceivedUpdates.incrementAndGet(); |
| | | } |
| | |
| | | private Task initializeTask; |
| | | /** The destination in the case of an export. */ |
| | | private int exportTarget = RoutableMsg.UNKNOWN_SERVER; |
| | | /** Identifies a single-target export initiated on this server. */ |
| | | private volatile String exportAttemptId; |
| | | /** Whether the importer completed preparation for that export. */ |
| | | private volatile boolean remotePreparationReady; |
| | | /** The source in the case of an import. */ |
| | | private int importSource = RoutableMsg.UNKNOWN_SERVER; |
| | | |
| | |
| | | private long entryLeftCount; |
| | | |
| | | /** Exception raised during the initialization. */ |
| | | private DirectoryException exception; |
| | | private volatile DirectoryException exception; |
| | | |
| | | /** Refusal received from the importer before it touched its backend. */ |
| | | private volatile DirectoryException remotePreparationRefusal; |
| | | |
| | | /** Whether the import failed while draining replay and state saves before replacement. */ |
| | | private boolean importPreparationFailed; |
| | | |
| | | /** Whether the context is related to an import or an export. */ |
| | | private final boolean importInProgress; |
| | |
| | | */ |
| | | public DirectoryException getException() |
| | | { |
| | | return exception; |
| | | final DirectoryException refusal = remotePreparationRefusal; |
| | | return refusal != null ? refusal : exception; |
| | | } |
| | | |
| | | private boolean matchesExportAttempt(String attemptId, int senderId) |
| | | { |
| | | return attemptId.equals(exportAttemptId) && senderId == exportTarget; |
| | | } |
| | | |
| | | /** |
| | |
| | | } |
| | | |
| | | /** |
| | | * Records a failure while draining replay and state saves before replacing the backend. |
| | | * @param failure the preparation failure |
| | | */ |
| | | public void failImportPreparation(DirectoryException failure) |
| | | { |
| | | if (exception == null) |
| | | { |
| | | exception = failure; |
| | | importPreparationFailed = true; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Set the id of the EntryMsg acknowledged from a receiver (importer)server. |
| | | * (updated via the listener thread) |
| | | * @param serverId serverId of the acknowledger/receiver/importer server. |
| | |
| | | getBaseDN(), getServerId(), serverToInitialize); |
| | | |
| | | ieCtx.startList.add(serverToInitialize); |
| | | ieCtx.setAckVal(targetDsi.getDsId(), 0); |
| | | ieCtx.setAckVal(serverToInitialize, 0); |
| | | } |
| | | |
| | | DirectoryException exportRootException = null; |
| | |
| | | try |
| | | { |
| | | ieCtx.exportTarget = serverToInitialize; |
| | | final Session exportSession = broker.getSession(); |
| | | ieCtx.remotePreparationReady = false; |
| | | ieCtx.exportAttemptId = targetDsi != null && serverRunningTheTask == getServerId() |
| | | && targetDsi.getProtocolVersion() >= ProtocolVersion.REPLICATION_PROTOCOL_V9 |
| | | && exportSession != null && exportSession.getProtocolVersion() >= ProtocolVersion.REPLICATION_PROTOCOL_V9 |
| | | ? UUID.randomUUID().toString() : null; |
| | | if (initTask != null) |
| | | { |
| | | ieCtx.initializeTask = initTask; |
| | |
| | | // Send start message to the peer |
| | | InitializeTargetMsg initTargetMsg = new InitializeTargetMsg( |
| | | getBaseDN(), getServerId(), serverToInitialize, |
| | | serverRunningTheTask, ieCtx.entryCount, initWindow); |
| | | serverRunningTheTask, ieCtx.entryCount, initWindow, ieCtx.exportAttemptId); |
| | | |
| | | broker.publish(initTargetMsg); |
| | | |
| | |
| | | |
| | | exportBackend(new BufferedOutputStream(new ReplOutputStream(this))); |
| | | |
| | | // A backend can swallow the exception from the final buffered write. |
| | | final DirectoryException refusal = ieCtx.remotePreparationRefusal; |
| | | if (refusal != null) |
| | | { |
| | | throw refusal; |
| | | } |
| | | |
| | | // Notify the peer of the success |
| | | broker.publish( |
| | | new DoneMsg(getServerId(), initTargetMsg.getDestination())); |
| | |
| | | catch(DirectoryException exportException) |
| | | { |
| | | // Give priority to the first exception raised - stored in the context |
| | | final DirectoryException ieEx = ieCtx.exception; |
| | | final DirectoryException ieEx = ieCtx.getException(); |
| | | exportRootException = ieEx != null ? ieEx : exportException; |
| | | } |
| | | |
| | |
| | | + " exportRootException=" + exportRootException); |
| | | } |
| | | |
| | | if (exportRootException != null) |
| | | if (exportRootException != null && ieCtx.remotePreparationRefusal == null) |
| | | { |
| | | try |
| | | { |
| | |
| | | } // attempt loop |
| | | |
| | | // Wait for all servers to be ok, and build the failure list |
| | | waitForRemoteEndOfInit(ieCtx); |
| | | if (ieCtx.remotePreparationRefusal == null) |
| | | { |
| | | waitForRemoteEndOfInit(ieCtx); |
| | | } |
| | | final DirectoryException refusal = ieCtx.remotePreparationRefusal; |
| | | if (refusal != null) |
| | | { |
| | | exportRootException = refusal; |
| | | } |
| | | |
| | | // Servers that left in the list are those for which we could not test |
| | | // that they have been successfully initialized. |
| | |
| | | private void waitForRemoteStartOfInit(ImportExportContext ieCtx) |
| | | { |
| | | final Set<Integer> replicasWeAreWaitingFor = new HashSet<>(ieCtx.startList); |
| | | final boolean awaitPreparation = ieCtx.exportAttemptId != null; |
| | | |
| | | if (logger.isTraceEnabled()) |
| | | { |
| | |
| | | boolean done; |
| | | do |
| | | { |
| | | done = true; |
| | | for (DSInfo dsi : getReplicaInfos().values()) |
| | | if (awaitPreparation) |
| | | { |
| | | if (logger.isTraceEnabled()) |
| | | // FULL_UPDATE excludes the importer from assured replay before it is ready to receive entries. |
| | | final boolean ready = ieCtx.remotePreparationReady; |
| | | if (ready) |
| | | { |
| | | logger.trace( |
| | | "[IE] wait for start dsId " + dsi.getDsId() |
| | | + " " + dsi.getStatus() |
| | | + " " + dsi.getGenerationId() |
| | | + " " + getGenerationID()); |
| | | replicasWeAreWaitingFor.clear(); |
| | | } |
| | | if (ieCtx.startList.contains(dsi.getDsId())) |
| | | done = ready || ieCtx.getException() != null; |
| | | } |
| | | else |
| | | { |
| | | done = true; |
| | | for (DSInfo dsi : getReplicaInfos().values()) |
| | | { |
| | | if (dsi.getStatus() != ServerStatus.FULL_UPDATE_STATUS) |
| | | if (logger.isTraceEnabled()) |
| | | { |
| | | // this one is still not doing the Full Update ... retry later |
| | | done = false; |
| | | try { Thread.sleep(100); |
| | | } |
| | | catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); |
| | | } |
| | | waitResultAttempt++; |
| | | break; |
| | | logger.trace("[IE] wait for start dsId " + dsi.getDsId() + " " + dsi.getStatus() |
| | | + " " + dsi.getGenerationId() + " " + getGenerationID()); |
| | | } |
| | | else |
| | | if (ieCtx.startList.contains(dsi.getDsId())) |
| | | { |
| | | // this one is ok |
| | | if (dsi.getStatus() != ServerStatus.FULL_UPDATE_STATUS) |
| | | { |
| | | done = false; |
| | | break; |
| | | } |
| | | replicasWeAreWaitingFor.remove(dsi.getDsId()); |
| | | } |
| | | } |
| | | } |
| | | if (!done) |
| | | { |
| | | try |
| | | { |
| | | Thread.sleep(100); |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | Thread.currentThread().interrupt(); |
| | | } |
| | | waitResultAttempt++; |
| | | } |
| | | } |
| | | while (!done && waitResultAttempt < 1200 && !broker.shuttingDown()); |
| | | |
| | |
| | | } // 1sec |
| | | } |
| | | } |
| | | while (!done && !broker.shuttingDown()); // infinite wait |
| | | while (!done && ieCtx.remotePreparationRefusal == null && !broker.shuttingDown()); // infinite wait |
| | | |
| | | ieCtx.failureList.addAll(replicasWeAreWaitingFor); |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | private boolean isCurrentInitializationError(ErrorMsg errorMsg, ImportExportContext ieCtx) |
| | | { |
| | | final String attemptId = errorMsg.getInitializationAttemptId(); |
| | | // An uncorrelated request and its refusal may use the same millisecond (issue #861). |
| | | return attemptId != null |
| | | ? ieCtx.matchesExportAttempt(attemptId, errorMsg.getSenderID()) |
| | | : errorMsg.getCreationTime() >= ieCtx.startTime; |
| | | } |
| | | |
| | | /** |
| | | * Processes an error message received while an export is |
| | | * on going, or an import will start. |
| | |
| | | if (ieCtx != null && ieCtx.exportTarget != RoutableMsg.ALL_SERVERS) |
| | | { |
| | | // The ErrorMsg is received while we have started an initialization |
| | | ieCtx.setExceptionIfNoneSet(new DirectoryException( |
| | | ResultCode.OTHER, errorMsg.getDetails())); |
| | | final DirectoryException refusal = new DirectoryException(ResultCode.OTHER, errorMsg.getDetails()); |
| | | if (errorMsg.getInitializationAttemptId() != null) |
| | | { |
| | | ieCtx.remotePreparationRefusal = refusal; |
| | | } |
| | | else |
| | | { |
| | | ieCtx.setExceptionIfNoneSet(refusal); |
| | | } |
| | | |
| | | /* |
| | | * This can happen : |
| | |
| | | if (ieCtx.getException() == null) |
| | | { |
| | | ErrorMsg errMsg = (ErrorMsg)msg; |
| | | if (errMsg.getCreationTime() >= ieCtx.startTime) |
| | | if (isCurrentInitializationError(errMsg, ieCtx)) |
| | | { |
| | | ieCtx.setException( |
| | | new DirectoryException(ResultCode.OTHER,errMsg.getDetails())); |
| | |
| | | logger.trace("[IE] Entering initializeFromRemote for " + this); |
| | | } |
| | | |
| | | LocalizableMessage errMsg = !broker.isConnected() |
| | | ? ERR_INITIALIZATION_FAILED_NOCONN.get(getBaseDN()) |
| | | : null; |
| | | LocalizableMessage errMsg = null; |
| | | |
| | | /* |
| | | We must not test here whether the remote source is connected to |
| | |
| | | ieCtx.initReqMsgSent = new InitializeRequestMsg( |
| | | getBaseDN(), getServerId(), source, getInitWindow()); |
| | | ieCtx.markInitRequestSent(); |
| | | // A reconnect can finish before the request is sent. Keep the context when |
| | | // publish succeeds, even if the broker was disconnected on entry. |
| | | // The broker silently drops the message when it is caught between two |
| | | // sessions (connection error, recovery pending after a reconnect) and |
| | | // only replays UpdateMsgs on reconnect: an unpublished request would |
| | |
| | | |
| | | InitializeTask initFromTask = null; |
| | | final int source = initTargetMsgReceived.getSenderID(); |
| | | final Session importSession = broker.getSession(); |
| | | final boolean locallyInitiated = initTargetMsgReceived.getInitiatorID() == getServerId(); |
| | | final ImportExportContext ieCtx; |
| | | final Runnable hook = importClaimHook; |
| | | if (hook != null) |
| | | { |
| | | hook.run(); |
| | | } |
| | | if (initTargetMsgReceived.getInitiatorID() == getServerId()) |
| | | if (locallyInitiated) |
| | | { |
| | | ieCtx = getImportExportContext(); |
| | | if (ieCtx == null || !ieCtx.markInitStartReceived()) |
| | |
| | | return; |
| | | } |
| | | } |
| | | ErrorMsg preparationRefusal = null; |
| | | boolean refusalAccepted = false; |
| | | try |
| | | { |
| | | // Log starting |
| | | logger.info(NOTE_FULL_UPDATE_ENGAGED_FROM_REMOTE_START, getBaseDN(), |
| | | initTargetMsgReceived.getSenderID(), getServerId()); |
| | | |
| | | // Go into full update status |
| | | final String attemptId = initTargetMsgReceived.getInitializationAttemptId(); |
| | | setNewStatus(StatusMachineEvent.TO_FULL_UPDATE_STATUS_EVENT); |
| | | |
| | | // Initialize stuff |
| | |
| | | initFromTask = (InitializeTask) ieCtx.initializeTask; |
| | | |
| | | // Launch the import |
| | | importBackend(new ReplInputStream(this)); |
| | | try (ReplInputStream input = new ReplInputStream(this)) |
| | | { |
| | | if (attemptId != null) |
| | | { |
| | | importBackend(input, () -> |
| | | { |
| | | if (!broker.publishOnSession( |
| | | new InitializeRcvAckMsg(getServerId(), requesterServerId, attemptId), importSession)) |
| | | { |
| | | final DirectoryException failure = |
| | | new DirectoryException(ResultCode.UNAVAILABLE, ERR_INITIALIZATION_FAILED_NOCONN.get(getBaseDN())); |
| | | ieCtx.failImportPreparation(failure); |
| | | throw failure; |
| | | } |
| | | }); |
| | | } |
| | | else |
| | | { |
| | | importBackend(input); |
| | | } |
| | | } |
| | | if (!locallyInitiated && ieCtx.importPreparationFailed && !Thread.currentThread().isInterrupted() |
| | | && !isServicePermanentlyStopped()) |
| | | { |
| | | // The RS can still be unregistering this session when the reconnect below runs. |
| | | // Send the preflight refusal while the original session can still carry it. |
| | | final LocalizableMessage reason = ieCtx.getException().getMessageObject(); |
| | | preparationRefusal = attemptId != null |
| | | ? new ErrorMsg(getServerId(), requesterServerId, reason, attemptId) |
| | | : new ErrorMsg(requesterServerId, reason); |
| | | refusalAccepted = broker.publishOnSession(preparationRefusal, importSession); |
| | | } |
| | | } |
| | | catch (DirectoryException e) |
| | | { |
| | |
| | | |
| | | try |
| | | { |
| | | if (!isServicePermanentlyStopped() && broker.isConnected() && ieCtx.getException() != null) |
| | | if (!isServicePermanentlyStopped() && ieCtx.getException() != null) |
| | | { |
| | | // Let's notify the exporter |
| | | ErrorMsg errorMsg = new ErrorMsg(requesterServerId, |
| | | ieCtx.getException().getMessageObject()); |
| | | broker.publish(errorMsg); |
| | | if (preparationRefusal != null && preparationRefusal.getInitializationAttemptId() != null) |
| | | { |
| | | // The old RS can accept the refusal after losing its route to the exporter. |
| | | // Keep the correlated refusal until a replacement session can carry it. |
| | | if (!refusalAccepted || broker.getSession() != importSession) |
| | | { |
| | | broker.publishInitializationRefusalAfterReconnect(preparationRefusal); |
| | | } |
| | | } |
| | | else if (!refusalAccepted && broker.isConnected()) |
| | | { |
| | | broker.publish(preparationRefusal != null ? preparationRefusal |
| | | : new ErrorMsg(requesterServerId, ieCtx.getException().getMessageObject())); |
| | | } |
| | | } |
| | | } |
| | | finally |
| | |
| | | throws DirectoryException; |
| | | |
| | | /** |
| | | * Imports data and announces when preparation has completed and the exporter can start streaming. |
| | | * @param input the stream of entries |
| | | * @param onPrepared reports readiness before reading the stream |
| | | * @throws DirectoryException if the import fails |
| | | */ |
| | | protected void importBackend(InputStream input, ImportPreparation onPrepared) throws DirectoryException |
| | | { |
| | | onPrepared.reportReady(); |
| | | importBackend(input); |
| | | } |
| | | |
| | | /** Reports that the importer is ready to receive entries. */ |
| | | @FunctionalInterface |
| | | protected interface ImportPreparation |
| | | { |
| | | /** @throws DirectoryException if the acknowledgement cannot be published */ |
| | | void reportReady() throws DirectoryException; |
| | | } |
| | | |
| | | /** |
| | | * This method should return the total number of objects in the |
| | | * replicated domain. |
| | | * This count will be used for reporting. |
| | |
| | | { |
| | | broker.updateWindowAfterReplay(); |
| | | |
| | | /* |
| | | Send an ack if it was requested and the group id is the same of the RS |
| | | one. Only Safe Read mode makes sense in DS for returning an ack. |
| | | */ |
| | | // Assured feature is supported starting from replication protocol V2 |
| | | if (msg.isAssured() |
| | | && broker.getProtocolVersion() >= ProtocolVersion.REPLICATION_PROTOCOL_V2) |
| | | if (msg.isAssured()) |
| | | { |
| | | if (msg.getAssuredMode() == AssuredMode.SAFE_READ_MODE) |
| | | // Eligibility and the return session belong to the delivery, even if replay |
| | | // finishes after a reconnect to another group or to the same RS on a new socket. |
| | | final UpdateMsg.AcknowledgementSender sender = msg.getAcknowledgementSender(); |
| | | if (sender != null) |
| | | { |
| | | if (broker.getRsGroupId() == getGroupId()) |
| | | final AckMsg ackMsg = new AckMsg(msg.getCSN()); |
| | | if (replayErrorMsg != null) |
| | | { |
| | | // Send the ack |
| | | AckMsg ackMsg = new AckMsg(msg.getCSN()); |
| | | if (replayErrorMsg != null) |
| | | { |
| | | // Mark the error in the ack |
| | | // -> replay error occurred |
| | | ackMsg.setHasReplayError(true); |
| | | // -> replay error occurred in our server |
| | | ackMsg.setFailedServers(newArrayList(getServerId())); |
| | | } |
| | | broker.publish(ackMsg); |
| | | if (replayErrorMsg != null) |
| | | { |
| | | assuredSrReceivedUpdatesNotAcked.incrementAndGet(); |
| | | } |
| | | else |
| | | { |
| | | assuredSrReceivedUpdatesAcked.incrementAndGet(); |
| | | } |
| | | ackMsg.setHasReplayError(true); |
| | | ackMsg.setFailedServers(newArrayList(getServerId())); |
| | | } |
| | | if (sender.send(ackMsg) && replayErrorMsg == null) |
| | | { |
| | | assuredSrReceivedUpdatesAcked.incrementAndGet(); |
| | | } |
| | | else |
| | | { |
| | | assuredSrReceivedUpdatesNotAcked.incrementAndGet(); |
| | | } |
| | | } |
| | | else if (getAssuredMode() != AssuredMode.SAFE_DATA_MODE) |
| | | else if (msg.getAssuredMode() != AssuredMode.SAFE_READ_MODE |
| | | && getAssuredMode() != AssuredMode.SAFE_DATA_MODE |
| | | && broker.getProtocolVersion() >= ProtocolVersion.REPLICATION_PROTOCOL_V2) |
| | | { |
| | | logger.error(ERR_DS_UNKNOWN_ASSURED_MODE, getServerId(), msg.getAssuredMode(), getBaseDN(), msg); |
| | | } |
| | | // Nothing to do in Assured safe data mode, only RS ack updates. |
| | | } |
| | | |
| | | incProcessedUpdates(); |
| | |
| | | filter.addBaseDNsToSearch(uData.getBaseDNs()); |
| | | } |
| | | ServerDescriptor server = createStandalone(conn, filter); |
| | | Set<DN> suffixesToDisable = uData.disableAll() |
| | | ? getConfiguredReplicationBaseDNs(conn) |
| | | : new HashSet<>(uData.getBaseDNs()); |
| | | |
| | | ADSContext adsCtx = new ADSContext(conn); |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | Set<DN> suffixesToDisable; |
| | | if (uData.disableAll()) |
| | | if (!uData.disableAll()) |
| | | { |
| | | suffixesToDisable = findAllReplicatedSuffixDNs(server.getReplicas()); |
| | | } |
| | | else |
| | | { |
| | | suffixesToDisable = new HashSet<>(uData.getBaseDNs()); |
| | | |
| | | if (disableAllBaseDns && |
| | | (disableReplicationServer || !server.isReplicationServer())) |
| | | { |
| | |
| | | } |
| | | |
| | | /** |
| | | * Reads configured domains directly: a domain base DN can be below a backend's base DN |
| | | * and will not appear in the server descriptor's replicas. |
| | | */ |
| | | private Set<DN> getConfiguredReplicationBaseDNs(ConnectionWrapper conn) throws ReplicationCliException |
| | | { |
| | | try |
| | | { |
| | | final ReplicationSynchronizationProviderCfgClient sync; |
| | | try |
| | | { |
| | | sync = getMultimasterSynchronization(conn); |
| | | } |
| | | catch (ManagedObjectNotFoundException e) |
| | | { |
| | | return Collections.emptySet(); |
| | | } |
| | | |
| | | final Set<DN> baseDNs = new LinkedHashSet<>(); |
| | | final String[] domainNames = sync.listReplicationDomains(); |
| | | if (domainNames != null) |
| | | { |
| | | for (String domainName : domainNames) |
| | | { |
| | | baseDNs.add(sync.getReplicationDomain(domainName).getBaseDN()); |
| | | } |
| | | } |
| | | return baseDNs; |
| | | } |
| | | catch (OperationsException | LdapException e) |
| | | { |
| | | throw new ReplicationCliException( |
| | | ERR_REPLICATION_ERROR_READING_CONFIGURATION.get(conn.getHostPort(), e.getMessage()), |
| | | ERROR_READING_CONFIGURATION, e); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Deletes a replication domain in a server for a given base DN (disable |
| | | * replication of the base DN). |
| | | * @param conn the connection to the server. |
| | |
| | | ERR_INIT_DOMAIN_RESTORE_FAILED_340=Automatic restoration of replication for domain "%s" after \ |
| | | an aborted total update failed for backend "%s": %s. Correct the failure and disable \ |
| | | then enable the backend, or restart the server process |
| | | NOTE_REPLICATION_TLS_CLIENT_FAILURE_341=Replication TLS client handshake failed for %s(%d) \ |
| | | for domain "%s" from %s to %s |
| | |
| | | */ |
| | | package org.opends.server; |
| | | |
| | | import static java.nio.charset.StandardCharsets.UTF_8; |
| | | |
| | | import static org.forgerock.opendj.server.embedded.ConfigParameters.configParams; |
| | | import static org.forgerock.opendj.server.embedded.ConnectionParameters.connectionParams; |
| | | import static org.forgerock.opendj.server.embedded.EmbeddedDirectoryServer.manageEmbeddedDirectoryServer; |
| | |
| | | clearSystemErrContents(); |
| | | } |
| | | |
| | | private static final int AUDIT_LOG_TAIL_BYTES = 16 * 1024; |
| | | |
| | | /** |
| | | * Append the contents of the Access Log, Error Log, Debug Loggers, |
| | | * System.out, System.err to the specified buffer. |
| | | * Append logger, stdout, stderr and on-disk log diagnostics to the specified buffer. |
| | | */ |
| | | public static void appendLogsContents(StringBuilder logsContents) |
| | | { |
| | |
| | | appendStreamContent(logsContents, TestCaseUtils.getSystemOutContents(), "System.out"); |
| | | appendStreamContent(logsContents, TestCaseUtils.getSystemErrContents(), "System.err"); |
| | | |
| | | if (new File(paths.testInstanceRoot, "logs").listFiles()!=null) { |
| | | for (final File logFile : Arrays.asList(new File(paths.testInstanceRoot, "logs").listFiles())) { |
| | | try { |
| | | appendStreamContent(logsContents, readFile(logFile.getPath()), logFile.getPath()); |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | final File logDirectory = new File(paths.testInstanceRoot, "logs"); |
| | | final File[] logFiles = logDirectory.listFiles(); |
| | | if (logFiles == null) |
| | | { |
| | | return; |
| | | } |
| | | |
| | | boolean hasRotatedAuditLogs = false; |
| | | for (final File logFile : logFiles) |
| | | { |
| | | final String name = logFile.getName(); |
| | | if (name.startsWith("audit.")) |
| | | { |
| | | hasRotatedAuditLogs = true; |
| | | continue; |
| | | } |
| | | try |
| | | { |
| | | final String content = "audit".equals(name) ? readAuditLogTail(logFile) : readFile(logFile); |
| | | appendStreamContent(logsContents, content, logFile.getPath()); |
| | | } |
| | | catch (IOException e) |
| | | { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | if (hasRotatedAuditLogs) |
| | | { |
| | | logsContents.append(EOL).append("Rotated audit logs are available in ").append(logDirectory).append(EOL); |
| | | } |
| | | } |
| | | |
| | | private static String readAuditLogTail(File auditLog) throws IOException |
| | | { |
| | | try (FileInputStream input = new FileInputStream(auditLog)) |
| | | { |
| | | final long size = input.getChannel().size(); |
| | | final int length = (int) Math.min(size, AUDIT_LOG_TAIL_BYTES); |
| | | final long start = size - length; |
| | | input.getChannel().position(start); |
| | | final byte[] tail = input.readNBytes(length); |
| | | if (start == 0) |
| | | { |
| | | return new String(tail, UTF_8); |
| | | } |
| | | |
| | | // The byte limit can start inside a UTF-8 character. |
| | | int offset = 0; |
| | | while (offset < tail.length && (tail[offset] & 0xc0) == 0x80) |
| | | { |
| | | offset++; |
| | | } |
| | | return "[truncated " + (start + offset) + " bytes. Full audit log on disk.]" + EOL |
| | | + new String(tail, offset, tail.length - offset, UTF_8); |
| | | } |
| | | } |
| | | |
| New file |
| | |
| | | /* |
| | | * 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. |
| | | */ |
| | | package org.opends.server; |
| | | |
| | | import static java.nio.charset.StandardCharsets.UTF_8; |
| | | import static java.nio.file.StandardOpenOption.CREATE_NEW; |
| | | import static org.testng.Assert.assertFalse; |
| | | import static org.testng.Assert.assertTrue; |
| | | |
| | | import java.io.IOException; |
| | | import java.nio.file.Files; |
| | | import java.nio.file.Path; |
| | | |
| | | import org.testng.annotations.Test; |
| | | |
| | | /** Tests for the audit logs included in test failure diagnostics. */ |
| | | @SuppressWarnings("javadoc") |
| | | public class TestCaseUtilsAuditLogTest extends DirectoryServerTestCase |
| | | { |
| | | @Test |
| | | public void shortAuditLogIsIncludedInFull() throws IOException |
| | | { |
| | | final String audit = "dn: cn=Jos\u00e9\nchangetype: add\n"; |
| | | |
| | | assertTrue(getAuditDiagnostics(appendDiagnosticsForLog("audit", audit)).startsWith(audit)); |
| | | } |
| | | |
| | | @Test |
| | | public void oversizedAuditRecordIsTruncatedByBytes() throws IOException |
| | | { |
| | | final String ending = " last value"; |
| | | final String audit = "old audit record\n" + "\u00e9".repeat(128 * 1024) + ending; |
| | | |
| | | final String diagnostics = getAuditDiagnostics(appendDiagnosticsForLog("audit", audit)); |
| | | final int suffix = diagnostics.indexOf(ending); |
| | | assertTrue(suffix >= 0, "Missing audit log suffix"); |
| | | final String excerpt = diagnostics.substring(0, suffix + ending.length()); |
| | | final int bytes = excerpt.getBytes(UTF_8).length; |
| | | assertTrue(bytes <= 16 * 1024 + 128, "Audit diagnostics printed " + bytes + " bytes"); |
| | | assertTrue(excerpt.startsWith("[truncated"), "Missing audit truncation notice"); |
| | | assertFalse(excerpt.contains("\ufffd"), "Audit log suffix starts inside a UTF-8 character"); |
| | | } |
| | | |
| | | @Test |
| | | public void rotatedAuditLogIsKeptOnDisk() throws IOException |
| | | { |
| | | final String audit = "previous audit record\n"; |
| | | |
| | | final String diagnostics = appendDiagnosticsForLog("audit.20261127163239Z", audit); |
| | | assertFalse(diagnostics.contains(audit), "Rotated audit record was printed"); |
| | | assertTrue(diagnostics.contains("Rotated audit logs"), "Missing rotated audit log notice"); |
| | | } |
| | | |
| | | private String getAuditDiagnostics(String diagnostics) |
| | | { |
| | | final String header = "audit contents:" + System.lineSeparator(); |
| | | final int start = diagnostics.indexOf(header); |
| | | assertTrue(start >= 0, "Missing diagnostics for audit"); |
| | | return diagnostics.substring(start + header.length()); |
| | | } |
| | | |
| | | private String appendDiagnosticsForLog(String fileName, String audit) throws IOException |
| | | { |
| | | final Path logDirectory = Files.createDirectories(TestCaseUtils.paths.testInstanceRoot.toPath().resolve("logs")); |
| | | final Path auditFile = Files.writeString(logDirectory.resolve(fileName), audit, UTF_8, CREATE_NEW); |
| | | try |
| | | { |
| | | final StringBuilder diagnostics = new StringBuilder(); |
| | | TestCaseUtils.appendLogsContents(diagnostics); |
| | | assertTrue(audit.equals(Files.readString(auditFile, UTF_8)), "Diagnostic changed the audit log"); |
| | | return diagnostics.toString(); |
| | | } |
| | | finally |
| | | { |
| | | Files.deleteIfExists(auditFile); |
| | | } |
| | | } |
| | | } |
| | |
| | | * |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2011-2016 ForgeRock AS. |
| | | * Portions Copyright 2023-2025 3A Systems, LLC. |
| | | * Portions Copyright 2023-2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication; |
| | | |
| | |
| | | import org.opends.server.replication.protocol.DoneMsg; |
| | | import org.opends.server.replication.protocol.EntryMsg; |
| | | import org.opends.server.replication.protocol.ErrorMsg; |
| | | import org.opends.server.replication.protocol.InitializeRcvAckMsg; |
| | | import org.opends.server.replication.protocol.InitializeTargetMsg; |
| | | import org.opends.server.replication.protocol.ReplicationMsg; |
| | | import org.opends.server.replication.server.ReplServerFakeConfiguration; |
| | |
| | | if (msg instanceof InitializeTargetMsg) |
| | | { |
| | | debugInfo("Broker " + serverID + " receives InitializeTargetMessage "); |
| | | final InitializeTargetMsg header = (InitializeTargetMsg) msg; |
| | | if (header.getInitializationAttemptId() != null) |
| | | { |
| | | broker.publish(new InitializeRcvAckMsg(serverID, header.getSenderID(), header.getInitializationAttemptId())); |
| | | } |
| | | entriesReceived = 0; |
| | | } |
| | | else if (msg instanceof EntryMsg) |
| | |
| | | * |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2011-2016 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication; |
| | | |
| | |
| | | import org.opends.server.replication.protocol.DoneMsg; |
| | | import org.opends.server.replication.protocol.EntryMsg; |
| | | import org.opends.server.replication.protocol.ErrorMsg; |
| | | import org.opends.server.replication.protocol.InitializeRcvAckMsg; |
| | | import org.opends.server.replication.protocol.InitializeRequestMsg; |
| | | import org.opends.server.replication.protocol.InitializeTargetMsg; |
| | | import org.opends.server.replication.protocol.ReplicationMsg; |
| | |
| | | waitForRemoteReplicas(server2ID); |
| | | addTask(taskInitTargetS2, ResultCode.SUCCESS, null); |
| | | |
| | | // Signal RS we just entered the full update status |
| | | server2.signalStatusChange(ServerStatus.FULL_UPDATE_STATUS); |
| | | acknowledgeTargetExport(testCase, server2); |
| | | |
| | | // Tests that entries have been received by S2 |
| | | receiveUpdatedEntries(server2); |
| | |
| | | addTask(taskInitTargetS2, ResultCode.SUCCESS, null); |
| | | |
| | | log(testCase + " " + server2.getServerId() + " wait target " + Thread.currentThread()); |
| | | waitForInitializeTargetMsg(testCase, server2); |
| | | |
| | | // Signal RS we just entered the full update status |
| | | log(testCase + " change status"); |
| | | server2.signalStatusChange(ServerStatus.FULL_UPDATE_STATUS); |
| | | acknowledgeTargetExport(testCase, server2); |
| | | |
| | | // Tests that entries have been received by S2 |
| | | log(testCase + " receive entries"); |
| | |
| | | } |
| | | } |
| | | |
| | | private void waitForInitializeTargetMsg(String testCase, |
| | | private void acknowledgeTargetExport(String testCase, ReplicationBroker importer) throws Exception |
| | | { |
| | | final InitializeTargetMsg header = waitForInitializeTargetMsg(testCase, importer); |
| | | importer.signalStatusChange(ServerStatus.FULL_UPDATE_STATUS); |
| | | if (header.getInitializationAttemptId() != null) |
| | | { |
| | | importer.publish(new InitializeRcvAckMsg(importer.getServerId(), header.getSenderID(), |
| | | header.getInitializationAttemptId())); |
| | | } |
| | | } |
| | | |
| | | private InitializeTargetMsg waitForInitializeTargetMsg(String testCase, |
| | | ReplicationBroker server) throws Exception |
| | | { |
| | | // Fail fast when the initialization is lost or failed: looping until the |
| | |
| | | log(testCase + " " + server.getServerId() + " receives " + msgrcv); |
| | | if (msgrcv instanceof InitializeTargetMsg) |
| | | { |
| | | return; |
| | | return (InitializeTargetMsg) msgrcv; |
| | | } |
| | | if (msgrcv == null || msgrcv instanceof ErrorMsg) |
| | | { |
| New file |
| | |
| | | /* |
| | | * 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. |
| | | */ |
| | | package org.opends.server.replication.plugin; |
| | | |
| | | import static org.testng.Assert.*; |
| | | |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.nio.file.Files; |
| | | import java.nio.file.Path; |
| | | import java.util.List; |
| | | import java.util.zip.CRC32; |
| | | |
| | | import org.opends.server.DirectoryServerTestCase; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.opends.server.replication.common.CSNGenerator; |
| | | import org.testng.annotations.Test; |
| | | |
| | | @SuppressWarnings("javadoc") |
| | | @Test(groups = { "precommit", "replication" }, sequential = true) |
| | | public class CsnAllocationTraceTest extends DirectoryServerTestCase |
| | | { |
| | | @Test |
| | | public void recordsBothKindsAndClosesWithAChecksum() throws Exception |
| | | { |
| | | Path dir = Files.createTempDirectory("csn-trace-test"); |
| | | CsnAllocationTrace trace = new CsnAllocationTrace(dir, "token0"); |
| | | CSNGenerator generator = new CSNGenerator(14800, 1); |
| | | String domain = CsnAllocationTrace.encodeDomain("dc=example"); |
| | | CSN offline = trace.allocate(generator, domain, 'O'); |
| | | CSN local = trace.allocate(generator, domain, 'L'); |
| | | trace.finish(); |
| | | List<String> lines = Files.readAllLines(trace.path(), StandardCharsets.US_ASCII); |
| | | assertEquals(lines.size(), 4); |
| | | assertEquals(lines.get(0), "START 1 token0"); |
| | | assertEquals(lines.get(1), "O " + domain + " " + offline); |
| | | assertEquals(lines.get(2), "L " + domain + " " + local); |
| | | CRC32 crc = new CRC32(); |
| | | crc.update((lines.get(1) + "\n" + lines.get(2) + "\n").getBytes(StandardCharsets.US_ASCII)); |
| | | assertEquals(lines.get(3), String.format("END 2 %08x", crc.getValue())); |
| | | } |
| | | |
| | | @Test |
| | | public void anAllocationAfterShutdownInvalidatesTheTrace() throws Exception |
| | | { |
| | | CsnAllocationTrace trace = new CsnAllocationTrace(Files.createTempDirectory("csn-trace-test"), "token0"); |
| | | trace.finish(); |
| | | trace.allocate(new CSNGenerator(42, 1), CsnAllocationTrace.encodeDomain("dc=example"), 'L'); |
| | | String data = Files.readString(trace.path(), StandardCharsets.US_ASCII); |
| | | assertTrue(data.endsWith("AFTER-END\n")); |
| | | } |
| | | |
| | | @Test |
| | | public void aRestartTokenOverridesOnlyItsOwnContainerToken() throws Exception |
| | | { |
| | | Path file = Files.createTempDirectory("csn-token-test").resolve("token"); |
| | | assertEquals(CsnAllocationTrace.resolveToken("first", file.toString()), "first"); |
| | | Files.writeString(file, "second\n", StandardCharsets.US_ASCII); |
| | | assertEquals(CsnAllocationTrace.resolveToken("first", file.toString()), "second"); |
| | | assertEquals(CsnAllocationTrace.resolveToken("third", null), "third"); |
| | | } |
| | | } |
| | |
| | | import org.opends.server.replication.protocol.AddMsg; |
| | | import org.opends.server.replication.protocol.DeleteMsg; |
| | | import org.opends.server.replication.protocol.LDAPUpdateMsg; |
| | | import org.opends.server.replication.protocol.ReplSessionSecurity; |
| | | import org.opends.server.replication.protocol.ReplicationMsg; |
| | | import org.opends.server.replication.service.ReplicationBroker; |
| | | import org.opends.server.replication.service.ReplicationDomain; |
| | | import org.opends.server.types.Entry; |
| | |
| | | public void queuedRedeliveryAcknowledgesOnlyTheReplayResult( |
| | | boolean firstAssured, boolean lastAssured, boolean failReplay) throws Exception |
| | | { |
| | | final Field brokerField = ReplicationDomain.class.getDeclaredField("broker"); |
| | | brokerField.setAccessible(true); |
| | | final ReplicationBroker originalBroker = (ReplicationBroker) brokerField.get(domain); |
| | | final List<AckMsg> acks = new ArrayList<>(); |
| | | // A non-started broker retains real completion accounting but records the wire ack. |
| | | // No domain is passed to its constructor, so it registers no second monitor. |
| | | final ReplicationBroker recordingBroker = new ReplicationBroker(null, domain.getServerState(), |
| | | new DomainFakeCfg(baseDN, 1, new TreeSet<String>()), new ReplSessionSecurity()) |
| | | { |
| | | @Override |
| | | public byte getRsGroupId() |
| | | { |
| | | return domain.getGroupId(); |
| | | } |
| | | |
| | | @Override |
| | | public void publish(ReplicationMsg msg) |
| | | { |
| | | if (msg instanceof AckMsg) |
| | | { |
| | | acks.add((AckMsg) msg); |
| | | } |
| | | } |
| | | }; |
| | | brokerField.set(domain, recordingBroker); |
| | | final AtomicBoolean recovering = (AtomicBoolean) domainField("replayFailureRecovery"); |
| | | final SessionRestartRequests restarts = (SessionRestartRequests) domainField("sessionRestarts"); |
| | | recovering.set(true); |
| | |
| | | final AddMsg duplicate = addMsg(); |
| | | duplicate.setAssured(lastAssured); |
| | | duplicate.setAssuredMode(AssuredMode.SAFE_READ_MODE); |
| | | if (lastAssured) |
| | | { |
| | | if (i == 0) |
| | | { |
| | | duplicate.setAcknowledgementSender(ack -> { |
| | | throw new AssertionError("ack sent to superseded delivery"); |
| | | }); |
| | | } |
| | | else |
| | | { |
| | | duplicate.setAcknowledgementSender(acks::add); |
| | | } |
| | | } |
| | | domain.processUpdate(duplicate); |
| | | assertTrue(acks.isEmpty(), "queued redelivery must not acknowledge unapplied data"); |
| | | assertEquals(completedUpdates(), 0); |
| | |
| | | } |
| | | finally |
| | | { |
| | | brokerField.set(domain, originalBroker); |
| | | restarts.clear(); |
| | | recovering.set(false); |
| | | } |
| | |
| | | } |
| | | |
| | | /** |
| | | * Compare the actual changelogs after switching to an RS which missed two overwrites. Once |
| | | * the recent-message cache has discarded them, entry history can reconstruct the final |
| | | * value but not the overwritten operation. The last-CSN monitor alone cannot show this. |
| | | */ |
| | | @Test |
| | | public void switchingToABehindRSAfterRecentMessagesWereDiscardedLosesAnOverwrite() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | ReplicationServer first = createReplicationServer(); |
| | | final SortedSet<String> towardsFirst = new TreeSet<>(replServers); |
| | | final int secondPort = TestCaseUtils.findFreePort(); |
| | | final SortedSet<String> towardsSecond = towards(secondPort); |
| | | ReplicationServer second = null; |
| | | LDAPReplicationDomain domain = createReplicationDomain(serverId); |
| | | try |
| | | { |
| | | second = createIsolatedReplicationServer(secondPort, "HistoricalCsnOrderingEmptyHistory", SECOND_RS_ID); |
| | | final DN dn = addPerson("empty-history"); |
| | | aChangeBothReplicationServersHold(domain, dn, first, towardsFirst, second, towardsSecond); |
| | | pendingChangesOf(domain).setMaxRecentChanges(0); |
| | | |
| | | replace(dn, "description", "overwritten"); |
| | | final CSN overwritten = domain.getLastLocalChange(); |
| | | replace(dn, "description", "final"); |
| | | final CSN last = domain.getLastLocalChange(); |
| | | assertInTheChangelog(first, baseDN, overwritten); |
| | | assertInTheChangelog(first, baseDN, last); |
| | | |
| | | connectTo(domain, towardsSecond, SECOND_RS_ID); |
| | | assertInTheChangelog(second, baseDN, last); |
| | | waitUntilTheRecoveryIsOver(domain); |
| | | assertOverwriteMissing(second, baseDN, overwritten, last); |
| | | } |
| | | finally |
| | | { |
| | | MultimasterReplication.deleteDomain(baseDN); |
| | | remove(first, second); |
| | | } |
| | | } |
| | | |
| | | /** Both RSs can miss the same overwrite when neither accepted it before the recovery. */ |
| | | @Test |
| | | public void aRecoveryFromHistoryCanLeaveTheSameGapOnBothReplicationServers() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | ReplicationServer first = createReplicationServer(); |
| | | final SortedSet<String> towardsFirst = new TreeSet<>(replServers); |
| | | final int secondPort = TestCaseUtils.findFreePort(); |
| | | final SortedSet<String> towardsSecond = towards(secondPort); |
| | | ReplicationServer second = null; |
| | | LDAPReplicationDomain domain = createReplicationDomain(serverId); |
| | | try |
| | | { |
| | | second = createIsolatedReplicationServer(secondPort, "HistoricalCsnOrderingCommonGap", SECOND_RS_ID); |
| | | final DN dn = addPerson("common-gap"); |
| | | aChangeBothReplicationServersHold(domain, dn, first, towardsFirst, second, towardsSecond); |
| | | // The broker refuses both writes, and the domain retains neither message. |
| | | refuseTheLocalChanges(domain); |
| | | replace(dn, "description", "overwritten"); |
| | | final CSN overwritten = domain.getLastLocalChange(); |
| | | replace(dn, "description", "final"); |
| | | final CSN last = domain.getLastLocalChange(); |
| | | |
| | | connectTo(domain, towardsSecond, SECOND_RS_ID); |
| | | assertInTheChangelog(second, baseDN, last); |
| | | waitUntilTheRecoveryIsOver(domain); |
| | | connectTo(domain, towardsFirst, FIRST_RS_ID); |
| | | assertInTheChangelog(first, baseDN, last); |
| | | waitUntilTheRecoveryIsOver(domain); |
| | | assertOverwriteMissing(first, baseDN, overwritten, last); |
| | | assertOverwriteMissing(second, baseDN, overwritten, last); |
| | | } |
| | | finally |
| | | { |
| | | MultimasterReplication.deleteDomain(baseDN); |
| | | remove(first, second); |
| | | } |
| | | } |
| | | |
| | | private static void assertOverwriteMissing(ReplicationServer rs, DN baseDN, CSN overwritten, CSN last) |
| | | throws Exception |
| | | { |
| | | try (DBCursor<UpdateMsg> cursor = rs.getChangelogDB().getReplicationDomainDB().getCursorFrom( |
| | | baseDN, overwritten.getServerId(), overwritten, |
| | | new CursorOptions(GREATER_THAN_OR_EQUAL_TO_KEY, ON_MATCHING_KEY))) |
| | | { |
| | | assertTrue(cursor.next()); |
| | | assertEquals(cursor.getRecord().getCSN(), last, |
| | | "the RS has the later change, but not the overwritten operation"); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * A replication server further behind than the messages the domain kept of its last local changes go |
| | | * back gets the changes before the first of them rebuilt from the historical information, and the |
| | | * others as they were done - a change a later one replaced included - and the domain says so, once |
| | |
| | | * information: "Portions copyright [year] [name of copyright owner]". |
| | | * |
| | | * Copyright 2026 3A Systems, LLC. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.plugin; |
| | | |
| | |
| | | import org.opends.server.replication.protocol.ReplicaOfflineMsg; |
| | | import org.opends.server.replication.protocol.UpdateMsg; |
| | | import org.opends.server.replication.service.DSRSShutdownSync; |
| | | import org.opends.server.replication.service.DSRSShutdownSync.ForwardingPeer; |
| | | import org.opends.server.replication.service.ReplicationDomain; |
| | | import org.opends.server.types.operation.PluginOperation; |
| | | import org.testng.annotations.BeforeClass; |
| | |
| | | { |
| | | assertFalse(shutdownSync.canShutdown(baseDN), |
| | | "the message must be announced before it is published"); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN, msg.getCSN(), RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN, msg.getCSN(), new ForwardingPeer(RS_ID)); |
| | | } |
| | | return true; |
| | | }).when(domain).publish(any(UpdateMsg.class)); |
| | |
| | | import static java.util.Collections.*; |
| | | import static org.testng.Assert.*; |
| | | |
| | | import java.lang.reflect.Proxy; |
| | | import java.util.Iterator; |
| | | import java.util.NoSuchElementException; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | import java.util.concurrent.ConcurrentSkipListSet; |
| | | import java.util.concurrent.CountDownLatch; |
| | | import java.util.concurrent.ExecutionException; |
| | | import java.util.concurrent.FutureTask; |
| | | import java.util.concurrent.LinkedBlockingQueue; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicReference; |
| | | import java.util.concurrent.locks.ReentrantLock; |
| | |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.opends.server.DirectoryServerTestCase; |
| | | import org.opends.server.TestCaseUtils; |
| | | import org.opends.server.core.AddOperation; |
| | | import org.opends.server.core.DeleteOperation; |
| | | import org.opends.server.core.ModifyOperation; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.opends.server.replication.common.CSNGenerator; |
| | | import org.opends.server.replication.common.ServerState; |
| | | import org.opends.server.replication.protocol.AddContext; |
| | | import org.opends.server.replication.protocol.AddMsg; |
| | | import org.opends.server.replication.protocol.DeleteContext; |
| | | import org.opends.server.replication.protocol.DeleteMsg; |
| | | import org.opends.server.replication.protocol.LDAPUpdateMsg; |
| | | import org.opends.server.replication.protocol.ModifyContext; |
| | | import org.opends.server.replication.protocol.ModifyDNMsg; |
| | | import org.opends.server.replication.protocol.ModifyMsg; |
| | | import org.opends.server.replication.protocol.OperationContext; |
| | | import org.opends.server.types.Operation; |
| | | import org.testng.annotations.BeforeClass; |
| | | import org.testng.annotations.DataProvider; |
| | | import org.testng.annotations.Test; |
| | |
| | | * Test case for [Issue 954]: the changes another thread parked are left alone. |
| | | * <p> |
| | | * A change is given back by the thread which owns it and by nobody else, here as |
| | | * everywhere else (issue #922). The thread which parked a change is the one which may |
| | | * still be inside the dependency checks which parked it - they park a change once per |
| | | * dependency it has - so a change released under it would be listed as waiting again a |
| | | * moment later, and handed out while the delivery which took it over is being replayed. |
| | | * everywhere else (issue #922). The thread which parked a change still has the road |
| | | * which hands it out after its predecessors commit. Another thread unwinding must not |
| | | * also make it eligible for redelivery. |
| | | */ |
| | | @Test |
| | | public void theParkedChangesOfAnotherThreadAreLeftAlone() throws Exception |
| | |
| | | assertSame(pendingChanges.getNextUpdate(), rename); |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] dependencyOperations() |
| | | { |
| | | return new Object[][] { { "add" }, { "modify" }, { "delete" }, { "rename" } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "dependencyOperations") |
| | | public void aDependencyScanCannotHandOutTheSameChangeTwice(String operation) throws Exception |
| | | { |
| | | final CSN firstCSN = new CSN(1000, 1, SERVER_ID); |
| | | final CSN secondCSN = new CSN(1000, 2, SERVER_ID); |
| | | final CSN targetCSN = new CSN(1000, 3, SERVER_ID); |
| | | final PausingDependencies dependencies = new PausingDependencies(secondCSN); |
| | | final ServerState state = new ServerState(); |
| | | final RemotePendingChanges pendingChanges = new RemotePendingChanges(state, -1, |
| | | new ConcurrentHashMap<Thread, CSN>(), dependencies); |
| | | final LDAPUpdateMsg first = dependencyMessage(operation, firstCSN, true); |
| | | final LDAPUpdateMsg second = dependencyMessage(operation, secondCSN, true); |
| | | final LDAPUpdateMsg target = dependencyMessage(operation, targetCSN, false); |
| | | assertTrue(pendingChanges.putRemoteUpdate(first)); |
| | | assertTrue(pendingChanges.putRemoteUpdate(second)); |
| | | assertTrue(pendingChanges.putRemoteUpdate(target)); |
| | | assertTrue(pendingChanges.markInProgress(first)); |
| | | assertTrue(pendingChanges.markInProgress(second)); |
| | | |
| | | final FutureTask<Boolean> scan = new FutureTask<>(() -> |
| | | { |
| | | try |
| | | { |
| | | assertTrue(pendingChanges.markInProgress(target)); |
| | | return checkDependencies(pendingChanges, target); |
| | | } |
| | | finally |
| | | { |
| | | // A scan which stops at its first dependency has already finished. Otherwise, |
| | | // the iterator holds its second predecessor across the concurrent commits. |
| | | dependencies.reached.countDown(); |
| | | } |
| | | }); |
| | | dependencies.scanningThread = new Thread(scan, "dependency scan"); |
| | | dependencies.scanningThread.start(); |
| | | try |
| | | { |
| | | awaitDependencyScan(dependencies.reached); |
| | | pendingChanges.commit(firstCSN); |
| | | assertNull(pendingChanges.getNextUpdate(), "the second predecessor must still hold back replay"); |
| | | pendingChanges.commit(secondCSN); |
| | | assertSame(pendingChanges.getNextUpdate(), target); |
| | | dependencies.resume.countDown(); |
| | | assertTrue(scan.get(10, TimeUnit.SECONDS)); |
| | | |
| | | runAndJoin(() -> assertNull(pendingChanges.getNextUpdate(), |
| | | "a stale predecessor must not park a change which has already been handed out")); |
| | | assertEquals(pendingChanges.getChangeOwnedByCurrentThread(), targetCSN); |
| | | pendingChanges.commit(targetCSN); |
| | | assertTrue(state.cover(targetCSN)); |
| | | assertEquals(pendingChanges.getQueueSize(), 0); |
| | | } |
| | | finally |
| | | { |
| | | dependencies.resume.countDown(); |
| | | dependencies.scanningThread.join(10000); |
| | | assertFalse(dependencies.scanningThread.isAlive(), "dependency scan did not finish"); |
| | | } |
| | | } |
| | | |
| | | @Test(dataProvider = "dependencyOperations") |
| | | public void aDependencyScanCannotParkAChangeFromBeforeClear(String operation) throws Exception |
| | | { |
| | | final CSN firstCSN = new CSN(1000, 1, SERVER_ID); |
| | | final CSN targetCSN = new CSN(1000, 2, SERVER_ID); |
| | | final PausingDependencies dependencies = new PausingDependencies(firstCSN); |
| | | final RemotePendingChanges pendingChanges = new RemotePendingChanges(new ServerState(), -1, |
| | | new ConcurrentHashMap<Thread, CSN>(), dependencies); |
| | | final LDAPUpdateMsg target = dependencyMessage(operation, targetCSN, false); |
| | | assertTrue(pendingChanges.putRemoteUpdate(dependencyMessage(operation, firstCSN, true))); |
| | | assertTrue(pendingChanges.putRemoteUpdate(target)); |
| | | final FutureTask<Boolean> scan = new FutureTask<>(() -> |
| | | { |
| | | assertTrue(pendingChanges.markInProgress(target)); |
| | | return checkDependencies(pendingChanges, target); |
| | | }); |
| | | dependencies.scanningThread = new Thread(scan, "dependency scan before clear"); |
| | | dependencies.scanningThread.start(); |
| | | try |
| | | { |
| | | awaitDependencyScan(dependencies.reached); |
| | | pendingChanges.clear(); |
| | | final LDAPUpdateMsg replacement = dependencyMessage(operation, targetCSN, false); |
| | | assertTrue(pendingChanges.putRemoteUpdate(replacement)); |
| | | dependencies.resume.countDown(); |
| | | assertTrue(scan.get(10, TimeUnit.SECONDS)); |
| | | |
| | | assertNull(pendingChanges.getNextUpdate(), "the old scan must not hand out the discarded delivery"); |
| | | assertTrue(pendingChanges.markInProgress(replacement)); |
| | | pendingChanges.commit(targetCSN); |
| | | assertEquals(pendingChanges.getQueueSize(), 0); |
| | | } |
| | | finally |
| | | { |
| | | dependencies.resume.countDown(); |
| | | dependencies.scanningThread.join(10000); |
| | | assertFalse(dependencies.scanningThread.isAlive(), "dependency scan did not finish"); |
| | | } |
| | | } |
| | | |
| | | @Test(dataProvider = "dependencyOperations") |
| | | public void aStaleDependencyCheckCannotParkAnotherThreadsChange(String operation) throws Exception |
| | | { |
| | | final CSN firstCSN = new CSN(1000, 1, SERVER_ID); |
| | | final CSN targetCSN = new CSN(1000, 2, SERVER_ID); |
| | | final RemotePendingChanges pendingChanges = new RemotePendingChanges(new ServerState()); |
| | | final LDAPUpdateMsg target = dependencyMessage(operation, targetCSN, false); |
| | | assertTrue(pendingChanges.putRemoteUpdate(dependencyMessage(operation, firstCSN, true))); |
| | | assertTrue(pendingChanges.putRemoteUpdate(target)); |
| | | assertTrue(pendingChanges.markInProgress(target)); |
| | | |
| | | runAndJoin(() -> assertTrue(checkDependencies(pendingChanges, target))); |
| | | pendingChanges.commit(firstCSN); |
| | | runAndJoin(() -> assertNull(pendingChanges.getNextUpdate(), |
| | | "dependency checks must not take a change away from its current replay owner")); |
| | | pendingChanges.commit(targetCSN); |
| | | assertEquals(pendingChanges.getQueueSize(), 0); |
| | | } |
| | | |
| | | private static LDAPUpdateMsg dependencyMessage(String operation, CSN csn, boolean predecessor) |
| | | { |
| | | final DN dn = DN.valueOf("cn=dependency,dc=example,dc=com"); |
| | | if ("modify".equals(operation)) |
| | | { |
| | | return new ModifyMsg(csn, dn, emptyList(), "dependency"); |
| | | } |
| | | if (predecessor || "add".equals(operation)) |
| | | { |
| | | return new AddMsg(csn, dn, "dependency", "parent", emptyMap(), emptyMap(), emptyMap()); |
| | | } |
| | | if ("delete".equals(operation)) |
| | | { |
| | | return new DeleteMsg(dn, csn, "dependency"); |
| | | } |
| | | return new ModifyDNMsg(dn, csn, "dependency", null, false, null, "cn=renamed"); |
| | | } |
| | | |
| | | private static boolean checkDependencies(RemotePendingChanges pendingChanges, LDAPUpdateMsg msg) |
| | | { |
| | | if (msg instanceof ModifyDNMsg) |
| | | { |
| | | return pendingChanges.checkDependencies((ModifyDNMsg) msg); |
| | | } |
| | | final Class<? extends Operation> type = msg instanceof AddMsg ? AddOperation.class |
| | | : msg instanceof DeleteMsg ? DeleteOperation.class : ModifyOperation.class; |
| | | final OperationContext context = msg instanceof AddMsg ? new AddContext(msg.getCSN(), "dependency", "parent") |
| | | : msg instanceof DeleteMsg ? new DeleteContext(msg.getCSN(), "dependency") |
| | | : new ModifyContext(msg.getCSN(), "dependency"); |
| | | // Only the operation's DN and replication context are inputs to the real dependency scan. |
| | | final Operation op = (Operation) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] { type }, |
| | | (proxy, method, args) -> |
| | | { |
| | | if ("getAttachment".equals(method.getName())) |
| | | { |
| | | return context; |
| | | } |
| | | if ("getEntryDN".equals(method.getName())) |
| | | { |
| | | return msg.getDN(); |
| | | } |
| | | throw new AssertionError("Unexpected operation method: " + method.getName()); |
| | | }); |
| | | return pendingChanges.checkDependencies(op, msg); |
| | | } |
| | | |
| | | private static void awaitDependencyScan(CountDownLatch latch) |
| | | { |
| | | try |
| | | { |
| | | assertTrue(latch.await(10, TimeUnit.SECONDS), "dependency scan did not reach its barrier"); |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | Thread.currentThread().interrupt(); |
| | | throw new AssertionError(e); |
| | | } |
| | | } |
| | | |
| | | private static final class PausingDependencies extends ConcurrentSkipListSet<PendingChange> |
| | | { |
| | | private final CSN pauseAt; |
| | | private final CountDownLatch reached = new CountDownLatch(1); |
| | | private final CountDownLatch resume = new CountDownLatch(1); |
| | | private Thread scanningThread; |
| | | |
| | | private PausingDependencies(CSN pauseAt) |
| | | { |
| | | this.pauseAt = pauseAt; |
| | | } |
| | | |
| | | @Override |
| | | public Iterator<PendingChange> iterator() |
| | | { |
| | | final Iterator<PendingChange> iterator = super.iterator(); |
| | | return new Iterator<PendingChange>() |
| | | { |
| | | @Override |
| | | public boolean hasNext() |
| | | { |
| | | return iterator.hasNext(); |
| | | } |
| | | |
| | | @Override |
| | | public PendingChange next() |
| | | { |
| | | final PendingChange change = iterator.next(); |
| | | if (Thread.currentThread() == scanningThread && change.getCSN().equals(pauseAt)) |
| | | { |
| | | reached.countDown(); |
| | | awaitDependencyScan(resume); |
| | | } |
| | | return change; |
| | | } |
| | | }; |
| | | } |
| | | } |
| | | |
| | | /** A rename of an entry into the DN {@code deleteMsg(csn, "uuid-1")} deletes. */ |
| | | private ModifyDNMsg renameIntoDeletedEntry(CSN csn) throws Exception |
| | | { |
| | |
| | | import static org.opends.server.core.DirectoryServer.*; |
| | | import static org.testng.Assert.*; |
| | | |
| | | import java.util.ArrayList; |
| | | import java.io.OutputStream; |
| | | import java.lang.reflect.Field; |
| | | import java.util.ArrayList; |
| | | import java.util.Collections; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.SortedSet; |
| | | import java.util.TreeSet; |
| | | import java.util.UUID; |
| | | import java.util.concurrent.CountDownLatch; |
| | | import java.util.concurrent.ExecutionException; |
| | | import java.util.concurrent.FutureTask; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicReference; |
| | | import java.util.concurrent.locks.Lock; |
| | | import java.util.function.BooleanSupplier; |
| | | |
| | | import org.forgerock.i18n.LocalizableMessage; |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.forgerock.opendj.ldap.ResultCode; |
| | | import org.forgerock.opendj.server.config.meta.ReplicationDomainCfgDefn.IsolationPolicy; |
| | |
| | | import org.opends.server.replication.ReplicationTestCase; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.opends.server.replication.common.CSNGenerator; |
| | | import org.opends.server.replication.common.DSInfo; |
| | | import org.opends.server.replication.common.ServerStatus; |
| | | import org.opends.server.replication.protocol.DeleteMsg; |
| | | import org.opends.server.replication.protocol.DoneMsg; |
| | | import org.opends.server.replication.protocol.EntryMsg; |
| | | import org.opends.server.replication.protocol.ErrorMsg; |
| | | import org.opends.server.replication.protocol.InitializeRcvAckMsg; |
| | | import org.opends.server.replication.protocol.InitializeRequestMsg; |
| | | import org.opends.server.replication.protocol.InitializeTargetMsg; |
| | | import org.opends.server.replication.protocol.LDAPUpdateMsg; |
| | |
| | | import org.opends.server.replication.server.ReplServerFakeConfiguration; |
| | | import org.opends.server.replication.server.ReplicationServer; |
| | | import org.opends.server.replication.server.ReplicationServerDomain; |
| | | import org.opends.server.replication.service.FakeReplicationDomain; |
| | | import org.opends.server.replication.service.ReplicationBroker; |
| | | import org.opends.server.types.DirectoryException; |
| | | import org.opends.server.types.Entry; |
| | |
| | | private DN baseDN; |
| | | private ReplicationServer replicationServer; |
| | | private LDAPReplicationDomain domain; |
| | | private volatile boolean reconnectAllowed = true; |
| | | private volatile String replacementServerAddress; |
| | | private TestSynchronousReplayQueue queue; |
| | | private ReplicationBroker exporter; |
| | | private CSNGenerator gen; |
| | |
| | | lock.lock(); |
| | | try |
| | | { |
| | | // Keep the established session available to report the failure and make the next |
| | | // reconnect fail, as it can while the RS still holds the previous registration. |
| | | reconnectAllowed = false; |
| | | exporter.publish(new InitializeTargetMsg(baseDN, EXPORTER_ID, DS_ID, EXPORTER_ID, 3, INIT_WINDOW)); |
| | | waitUntil(() -> !domain.ieRunning() |
| | | && errorLogRecordsOf(NOTE_FULL_UPDATE_ENGAGED_FROM_REMOTE_END.ordinal()).size() > completions, |
| | |
| | | assertTrue(entryExists(original.getName()), "a rejected preflight must leave the original data intact"); |
| | | assertNull(org.opends.server.api.LocalBackend.getWriteFailure(baseDN)); |
| | | assertThat(errorLogRecordsOf(WARN_REPLAY_NOT_DRAINED.ordinal())).hasSize(shutdownWarnings); |
| | | final ErrorMsg failure = waitForSpecificMsg(exporter, ErrorMsg.class); |
| | | assertFalse(domain.isConnected(), "the restart must fail while reconnecting is disabled"); |
| | | // Read every frame on the timed session so monitoring messages advance the wait's deadline check. |
| | | final ErrorMsg failure = waitForSpecificMsg(exporter.getSession(), ErrorMsg.class); |
| | | assertEquals(failure.getDetails().toString(), ERR_INIT_OPERATIONS_NOT_DRAINED.get(baseDN).toString()); |
| | | } |
| | | finally |
| | | { |
| | | reconnectAllowed = true; |
| | | lock.unlock(); |
| | | domain.setReplayDrainTimeout(30_000); |
| | | } |
| | |
| | | assertTrue(entryExists(DN.valueOf(IMPORTED_ENTRY_DN)), "a later import must still work"); |
| | | } |
| | | |
| | | @org.testng.annotations.DataProvider(name = "replacementReconnect") |
| | | public Object[][] replacementReconnect() |
| | | { |
| | | return new Object[][] { { false, false }, { true, false }, { false, true } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "replacementReconnect", timeOut = 120_000) |
| | | public void aDrainRefusalReachesTheExporterAfterChangingReplicationServers( |
| | | boolean delayedReconnect, boolean returnThroughOriginal) throws Exception |
| | | { |
| | | final int replacementId = RS_ID + 1; |
| | | final int exporterId = EXPORTER_ID + 1; |
| | | final int replacementPort = TestCaseUtils.findFreePort(); |
| | | final String dbName = "replayDuringImportReplacementDb"; |
| | | final SortedSet<String> originalAddress = |
| | | new TreeSet<>(Collections.singleton("localhost:" + replicationServer.getReplicationPort())); |
| | | final ReplicationServer replacement = new ReplicationServer(new ReplServerFakeConfiguration( |
| | | replacementPort, dbName, 0, replacementId, 0, 100, originalAddress)); |
| | | final AtomicBoolean streamed = new AtomicBoolean(); |
| | | final String replacementAddress = "localhost:" + replacementPort; |
| | | final FakeReplicationDomain remoteExporter = new FakeReplicationDomain(baseDN, exporterId, |
| | | new TreeSet<>(Collections.singleton(replacementAddress)), 0, getGenerationId(baseDN)) |
| | | { |
| | | @Override |
| | | protected void exportBackend(OutputStream output) throws DirectoryException |
| | | { |
| | | streamed.set(true); |
| | | super.exportBackend(output); |
| | | } |
| | | }; |
| | | remoteExporter.initExport(exportedEntries()[0], 1); |
| | | final FutureTask<Void> attempt = new FutureTask<>(() -> |
| | | { |
| | | remoteExporter.initializeRemote(DS_ID, null); |
| | | return null; |
| | | }); |
| | | final Thread exportThread = new Thread(attempt, "export across replication servers"); |
| | | exportThread.setDaemon(true); |
| | | try |
| | | { |
| | | final DN originalDn = DN.valueOf("cn=original," + EXAMPLE_DN); |
| | | TestCaseUtils.addEntry("dn: " + originalDn, |
| | | "objectClass: top", "objectClass: person", "cn: original", "sn: original"); |
| | | final ReplicationServerDomain original = replicationServer.getReplicationServerDomain(baseDN); |
| | | waitUntil(() -> remoteExporter.getReplicaInfos().containsKey(DS_ID) |
| | | && original.getConnectedRSs().containsKey(replacementId), |
| | | "the exporter never learned the route to the importer"); |
| | | |
| | | final Field replayLockField = LDAPReplicationDomain.class.getDeclaredField("replayReadLock"); |
| | | replayLockField.setAccessible(true); |
| | | final Lock replayLock = (Lock) replayLockField.get(domain); |
| | | final Field stateField = LDAPReplicationDomain.class.getDeclaredField("state"); |
| | | stateField.setAccessible(true); |
| | | final Field saveLockField = PersistentServerState.class.getDeclaredField("saveLock"); |
| | | saveLockField.setAccessible(true); |
| | | final Lock saveLock = (Lock) saveLockField.get(stateField.get(domain)); |
| | | // The RS builds its routing error from several messages and logs it with ID -1. |
| | | final int unreachable = errorLogRecordsOf(-1).size(); |
| | | saveLock.lock(); |
| | | try |
| | | { |
| | | replayLock.lock(); |
| | | try |
| | | { |
| | | exportThread.start(); |
| | | waitUntil(domain::ieRunning, "the importer did not receive the initialization header"); |
| | | waitUntil(() -> original.getConnectedDSs().get(DS_ID).getStatus() == ServerStatus.FULL_UPDATE_STATUS, |
| | | "the preparing importer did not enter FULL_UPDATE"); |
| | | // Deliver an unambiguously stale refusal while the new attempt is still active. |
| | | final String staleRefusal = "drain refusal from a previous export"; |
| | | final int previousErrors = errorLogRecordsOf(ERR_ERROR_MSG_RECEIVED.ordinal()).size(); |
| | | exporter.publish(new ErrorMsg( |
| | | DS_ID, exporterId, LocalizableMessage.raw(staleRefusal), UUID.randomUUID().toString())); |
| | | waitUntil(() -> errorLogRecordsOf(ERR_ERROR_MSG_RECEIVED.ordinal()).stream().skip(previousErrors) |
| | | .anyMatch(record -> record.contains(staleRefusal)), "the exporter did not ignore the stale refusal"); |
| | | if (!returnThroughOriginal) |
| | | { |
| | | replacementServerAddress = replacementAddress; |
| | | } |
| | | assertEquals(replacement.applyConfigurationChange(new ReplServerFakeConfiguration( |
| | | replacementPort, dbName, 0, replacementId, 0, 100, new TreeSet<>())).getResultCode(), |
| | | ResultCode.SUCCESS); |
| | | waitUntil(() -> !original.getConnectedRSs().containsKey(replacementId), |
| | | "the original replication server retained the route to the exporter"); |
| | | reconnectAllowed = !delayedReconnect; |
| | | domain.setReplayDrainTimeout(100); |
| | | } |
| | | finally |
| | | { |
| | | replayLock.unlock(); |
| | | } |
| | | if (delayedReconnect) |
| | | { |
| | | waitUntil(() -> !domain.ieRunning() && !domain.isConnected(), |
| | | "the importer did not complete preparation failure after the first reconnect failed"); |
| | | reconnectAllowed = true; |
| | | } |
| | | if (returnThroughOriginal) |
| | | { |
| | | waitUntil(() -> !domain.ieRunning() && domain.isConnected() && domain.getRsServerId() == RS_ID |
| | | && original.getConnectedDSs().containsKey(DS_ID), |
| | | "the importer did not reconnect to the original replication server"); |
| | | replacementServerAddress = replacementAddress; |
| | | original.stopServer(original.getConnectedDSs().get(DS_ID), false); |
| | | } |
| | | waitUntil(() -> !domain.ieRunning() && domain.isConnected() && domain.getRsServerId() == replacementId, |
| | | "the importer did not reconnect through the exporter's replication server"); |
| | | waitUntil(() -> |
| | | { |
| | | final DSInfo importer = remoteExporter.getReplicaInfos().get(DS_ID); |
| | | return importer != null && importer.getRsId() == replacementId; |
| | | }, "the exporter did not see the importer on the replacement replication server"); |
| | | assertThat(errorLogRecordsOf(-1).stream().skip(unreachable)) |
| | | .anyMatch(message -> message.contains("unroutable message =ErrorMsg")); |
| | | assertTrue(entryExists(originalDn), "the preparation failure must preserve the backend"); |
| | | final ExecutionException failure = expectThrows(ExecutionException.class, |
| | | () -> attempt.get(5, TimeUnit.SECONDS)); |
| | | assertThat(failure.getCause()).isInstanceOf(DirectoryException.class) |
| | | .hasMessage(ERR_INIT_OPERATIONS_NOT_DRAINED.get(baseDN).toString()); |
| | | assertFalse(streamed.get(), "the exporter must wait for the importer to finish preparation"); |
| | | } |
| | | finally |
| | | { |
| | | saveLock.unlock(); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | reconnectAllowed = true; |
| | | replacementServerAddress = null; |
| | | domain.setReplayDrainTimeout(30_000); |
| | | remoteExporter.disableService(); |
| | | exportThread.join(5000); |
| | | remove(replacement); |
| | | } |
| | | } |
| | | |
| | | @org.testng.annotations.DataProvider(name = "interruptedPreparation") |
| | | public Object[][] interruptedPreparation() |
| | | { |
| | | return new Object[][] { { false }, { true } }; |
| | | } |
| | | |
| | | @Test |
| | | public void aCorrelatedImportAnnouncesReadinessAndReceivesTheData() throws Exception |
| | | { |
| | | final String[] exported = exportedEntries(); |
| | | final String attemptId = UUID.randomUUID().toString(); |
| | | startImportInto(exported.length, attemptId); |
| | | final InitializeRcvAckMsg ready = waitForSpecificMsg(exporter.getSession(), InitializeRcvAckMsg.class); |
| | | assertEquals(ready.getInitializationAttemptId(), attemptId); |
| | | assertEquals(ready.getSenderID(), DS_ID); |
| | | assertEquals(ready.getNumAck(), 0); |
| | | finishImport(exported); |
| | | assertTrue(entryExists(DN.valueOf(IMPORTED_ENTRY_DN))); |
| | | } |
| | | |
| | | @Test(dataProvider = "interruptedPreparation", timeOut = 120_000) |
| | | public void anInterruptedImportDrainReportsTheInterrupt(boolean waitingForSave) throws Exception |
| | | { |
| | |
| | | |
| | | final SortedSet<String> replServers = new TreeSet<>(); |
| | | replServers.add("localhost:" + rsPort); |
| | | final DomainFakeCfg conf = new DomainFakeCfg(baseDN, DS_ID, replServers); |
| | | final DomainFakeCfg conf = new DomainFakeCfg(baseDN, DS_ID, replServers) |
| | | { |
| | | @Override |
| | | public SortedSet<String> getReplicationServer() |
| | | { |
| | | if (!reconnectAllowed) |
| | | { |
| | | return Collections.emptySortedSet(); |
| | | } |
| | | final String address = replacementServerAddress; |
| | | return address != null ? new TreeSet<>(Collections.singleton(address)) : super.getReplicationServer(); |
| | | } |
| | | }; |
| | | conf.setIsolationPolicy(IsolationPolicy.ACCEPT_ALL_UPDATES); |
| | | queue = new TestSynchronousReplayQueue(); |
| | | domain = MultimasterReplication.createNewDomain(conf, queue); |
| | |
| | | */ |
| | | private void startImportInto(int entryCount) throws Exception |
| | | { |
| | | startImportInto(entryCount, null); |
| | | } |
| | | |
| | | private void startImportInto(int entryCount, String attemptId) throws Exception |
| | | { |
| | | // The broker can report the replica connected before the replication server can route to it. |
| | | final ReplicationServerDomain rsDomain = replicationServer.getReplicationServerDomain(baseDN); |
| | | waitUntil(() -> rsDomain.getConnectedDSs().containsKey(DS_ID), |
| | | "the replication server did not register the import target"); |
| | | exporter.publish(new InitializeTargetMsg( |
| | | baseDN, EXPORTER_ID, DS_ID, EXPORTER_ID, entryCount, INIT_WINDOW)); |
| | | baseDN, EXPORTER_ID, DS_ID, EXPORTER_ID, entryCount, INIT_WINDOW, attemptId)); |
| | | final long deadline = System.currentTimeMillis() + 30_000; |
| | | while (getServerContext().getBackendConfigManager().hasLocalBackend("userRoot")) |
| | | { |
| | |
| | | import java.net.Socket; |
| | | import java.net.SocketException; |
| | | import java.net.SocketTimeoutException; |
| | | import java.nio.file.Files; |
| | | import java.nio.file.Path; |
| | | import java.util.ArrayList; |
| | | import java.util.Arrays; |
| | | import java.util.Collections; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.forgerock.opendj.ldap.ResultCode; |
| | | import org.opends.server.TestCaseUtils; |
| | | import org.opends.server.core.DirectoryServer; |
| | | import org.opends.server.plugins.PausePreParsePlugin; |
| | | import org.opends.server.replication.ReplicationTestCase; |
| | | import org.opends.server.replication.common.AssuredMode; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.opends.server.replication.common.CSNGenerator; |
| | | import org.opends.server.replication.common.DSInfo; |
| | | import org.opends.server.replication.common.RSInfo; |
| | | import org.opends.server.replication.common.ServerState; |
| | | import org.opends.server.replication.common.ServerStatus; |
| | | import org.opends.server.replication.protocol.AckMsg; |
| | | import org.opends.server.replication.protocol.DeleteMsg; |
| | | import org.opends.server.replication.protocol.DoneMsg; |
| | | import org.opends.server.replication.protocol.EntryMsg; |
| | | import org.opends.server.replication.protocol.HeartbeatMsg; |
| | | import org.opends.server.replication.protocol.InitializeTargetMsg; |
| | | import org.opends.server.replication.protocol.LDAPUpdateMsg; |
| | | import org.opends.server.replication.protocol.ModifyMsg; |
| | | import org.opends.server.replication.protocol.MonitorMsg; |
| | | import org.opends.server.replication.protocol.ProtocolVersion; |
| | | import org.opends.server.replication.protocol.ReplServerStartMsg; |
| | | import org.opends.server.replication.protocol.ReplSessionSecurity; |
| | | import org.opends.server.replication.protocol.ReplicaOfflineMsg; |
| | |
| | | import org.opends.server.replication.protocol.WindowProbeMsg; |
| | | import org.opends.server.replication.service.DSRSShutdownSync; |
| | | import org.opends.server.replication.service.ReplicationBroker; |
| | | import org.opends.server.replication.service.ReplicationDomain; |
| | | import org.opends.server.types.OperationType; |
| | | import org.opends.server.util.TestTimer; |
| | | import org.testng.annotations.AfterClass; |
| | | import org.testng.annotations.BeforeClass; |
| | | import org.testng.annotations.DataProvider; |
| | | import org.testng.annotations.Test; |
| | | |
| | | /** |
| | |
| | | { |
| | | survivor.differentGroup = true; |
| | | survivor.start(); |
| | | final LDAPReplicationDomain domain = startDomain(former, 100000, survivor.getPort()); |
| | | final LDAPReplicationDomain domain = startDomain(former, 100000, survivor.getAddress()); |
| | | assertEquals(domain.getRsServerId(), former.serverId); |
| | | newTimer().repeatUntilSuccess(() -> assertNotNull(former.session.get())); |
| | | assertEquals(replaceDescription("already on both replication servers"), ResultCode.SUCCESS); |
| | |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] assuredReplaySessions() |
| | | { |
| | | // A null replacement leaves the original session open until the replay completes. |
| | | return new Object[][] { { true, null }, { true, true }, { true, false }, { false, true } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "assuredReplaySessions", timeOut = 120_000) |
| | | public void assuredReplayAcknowledgesOnlyItsOriginalSession(boolean sourceInGroup, Boolean replacementInGroup) |
| | | throws Exception |
| | | { |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | final DN dn = DN.valueOf("cn=assured-switch," + baseDN); |
| | | TestCaseUtils.addEntry("dn: " + dn, "objectClass: person", "cn: assured-switch", "sn: assured-switch"); |
| | | final CSN csn = new CSNGenerator(OTHER_DS_ID, 0).newCSN(); |
| | | final DeleteMsg update = new DeleteMsg(dn, csn, getEntryUUID(dn)); |
| | | update.setAssured(true); |
| | | update.setAssuredMode(AssuredMode.SAFE_READ_MODE); |
| | | final WithholdingReplicationServer rs = new WithholdingReplicationServer(LARGE_WINDOW); |
| | | final AtomicReference<Runnable> switchSender = new AtomicReference<>(); |
| | | try |
| | | { |
| | | rs.differentGroup = !sourceInGroup; |
| | | final LDAPReplicationDomain domain = startDomain(rs); |
| | | final ReplicationBroker broker = brokerOf(domain); |
| | | assertEquals(broker.getRsGroupId() == domain.getGroupId(), sourceInGroup); |
| | | final Session original = broker.getSession(); |
| | | PausePreParsePlugin.pause(OperationType.DELETE, dn); |
| | | newTimer().repeatUntilSuccess(() -> assertNotNull(rs.session.get())); |
| | | rs.session.get().publish(update); |
| | | assertTrue(PausePreParsePlugin.awaitPaused(OperationType.DELETE, 30, SECONDS), "replay did not reach the backend"); |
| | | assertTrue(original.closeForSwitch(switchSender::set)); |
| | | if (replacementInGroup != null) |
| | | { |
| | | runSwitchSender(switchSender); |
| | | newTimer().repeatUntilSuccess(() -> assertEquals(rs.count(StopMsg.class), 1)); |
| | | rs.differentGroup = !replacementInGroup; |
| | | rs.closeTheSession(); |
| | | // The same RS ID on a new socket must not inherit the old session's ack. |
| | | newTimer().repeatUntilSuccess(() -> |
| | | assertTrue(domain.isConnected() && broker.getSession() != original && rs.sessionsStarted() == 2)); |
| | | assertEquals(broker.getRsGroupId() == domain.getGroupId(), replacementInGroup.booleanValue()); |
| | | } |
| | | |
| | | PausePreParsePlugin.release(OperationType.DELETE); |
| | | assertMonitorAttrValueEventually(baseDN, "replayed-updates", 1, "the assured replay did not finish"); |
| | | assertNull(DirectoryServer.getEntry(dn)); |
| | | if (replacementInGroup != null) |
| | | { |
| | | assertEquals(domain.getAssuredSrReceivedUpdatesAcked(), 0, "the undelivered ack was counted as sent"); |
| | | assertEquals(domain.getAssuredSrReceivedUpdatesNotAcked(), sourceInGroup ? 1 : 0, |
| | | "only the source session's group decides whether an ack was due"); |
| | | domain.disable(); |
| | | rs.waitForTheSessionToEnd(); |
| | | assertEquals(rs.count(AckMsg.class), 0, "the replacement session received the previous session's ack"); |
| | | } |
| | | else |
| | | { |
| | | newTimer().repeatUntilSuccess(() -> assertNotNull(rs.lastAck, "the old RS did not receive its ack")); |
| | | assertEquals(rs.lastAck.getCSN(), csn); |
| | | assertFalse(rs.lastAck.hasReplayError()); |
| | | assertEquals(domain.getAssuredSrReceivedUpdatesAcked(), 1); |
| | | assertEquals(domain.getAssuredSrReceivedUpdatesNotAcked(), 0); |
| | | runSwitchSender(switchSender); |
| | | newTimer().repeatUntilSuccess(() -> assertEquals(rs.count(StopMsg.class), 1)); |
| | | assertEquals(rs.count(AckMsg.class), 1); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | PausePreParsePlugin.release(OperationType.DELETE); |
| | | runSwitchSender(switchSender); |
| | | cleanUp(rs); |
| | | } |
| | | } |
| | | |
| | | @Test(timeOut = 120_000) |
| | | public void gracefulStopSendsOfflineWhileTheSwitchSenderIsPending() throws Exception |
| | | { |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | final WithholdingReplicationServer rs = new WithholdingReplicationServer(LARGE_WINDOW); |
| | | final AtomicReference<Runnable> switchSender = new AtomicReference<>(); |
| | | Thread disabling = null; |
| | | try |
| | | { |
| | | final LDAPReplicationDomain domain = startDomain(rs); |
| | | assertTrue(brokerOf(domain).getSession().closeForSwitch(switchSender::set)); |
| | | disabling = startThread("disable during planned switch", domain::disable); |
| | | newTimer().repeatUntilSuccess(() -> assertNotNull(rs.lastOffline, "the healthy old RS did not receive offline")); |
| | | assertEquals(rs.lastOffline.getCSN().getServerId(), DS_ID); |
| | | runSwitchSender(switchSender); |
| | | disabling.join(stopBoundMS()); |
| | | assertFalse(disabling.isAlive(), "the graceful stop did not finish"); |
| | | rs.waitForTheSessionToEnd(); |
| | | assertEquals(rs.count(ReplicaOfflineMsg.class), 1); |
| | | assertEquals(rs.sessionsStarted(), 1); |
| | | } |
| | | finally |
| | | { |
| | | runSwitchSender(switchSender); |
| | | cleanUp(rs, disabling); |
| | | } |
| | | } |
| | | |
| | | private enum SwitchAtShutdown |
| | | { |
| | | ORDINARY, FORMER_RS_DISAPPEARS, REPLACEMENT_WITHHOLDS_TOPOLOGY, WRONG_GENERATION, CHANGED_GENERATION |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] switchesAtShutdown() |
| | | { |
| | | return new Object[][] { { SwitchAtShutdown.ORDINARY }, { SwitchAtShutdown.FORMER_RS_DISAPPEARS }, |
| | | { SwitchAtShutdown.REPLACEMENT_WITHHOLDS_TOPOLOGY }, { SwitchAtShutdown.WRONG_GENERATION }, |
| | | { SwitchAtShutdown.CHANGED_GENERATION } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "switchesAtShutdown", timeOut = 120_000) |
| | | public void gracefulStopSendsOfflineOnTheReplacementAfterTheOldStop(SwitchAtShutdown scenario) throws Exception |
| | | { |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | setConnectionTimeout(LONG_CONNECTION_TIMEOUT_MS); |
| | | final WithholdingReplicationServer oldRS = new WithholdingReplicationServer(LARGE_WINDOW); |
| | | final WithholdingReplicationServer nextRS = new WithholdingReplicationServer(LARGE_WINDOW, 4); |
| | | final boolean withholdTopology = scenario == SwitchAtShutdown.REPLACEMENT_WITHHOLDS_TOPOLOGY; |
| | | final boolean wrongGeneration = scenario == SwitchAtShutdown.WRONG_GENERATION; |
| | | final boolean changedGeneration = scenario == SwitchAtShutdown.CHANGED_GENERATION; |
| | | final DelayedFailoverHandshake replacementHandshake = new DelayedFailoverHandshake(1, 0); |
| | | if (wrongGeneration) |
| | | { |
| | | replacementHandshake.sendNextReply.countDown(); |
| | | } |
| | | Thread disabling = null; |
| | | try |
| | | { |
| | | nextRS.differentGroup = true; |
| | | nextRS.start(); |
| | | final LDAPReplicationDomain domain = startDomain(oldRS, 100000, nextRS.getAddress()); |
| | | assertEquals(domain.getRsServerId(), oldRS.serverId); |
| | | nextRS.differentGroup = false; |
| | | newTimer().repeatUntilSuccess(() -> assertNotNull(oldRS.session.get())); |
| | | oldRS.advertiseRebalance(nextRS, domain); |
| | | newTimer().repeatUntilSuccess(() -> assertEquals(oldRS.count(StopMsg.class), 1)); |
| | | |
| | | if (withholdTopology) |
| | | { |
| | | setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS); |
| | | } |
| | | final long stopBound = stopBoundMS(); |
| | | final CSN previous = offlineAnnouncementOfTheReplica(); |
| | | final Thread stop = startThread("disable after switch StopMsg", domain::disable); |
| | | disabling = stop; |
| | | // Answer the old StopMsg as soon as the concurrent disable tries to publish offline. |
| | | newTimer().repeatUntilSuccess(() -> { |
| | | final CSN announced = offlineAnnouncementOfTheReplica(); |
| | | assertTrue(announced != null && !announced.equals(previous), "disable did not announce the offline marker"); |
| | | }); |
| | | final CSN marker = offlineAnnouncementOfTheReplica(); |
| | | if (scenario == SwitchAtShutdown.ORDINARY) |
| | | { |
| | | oldRS.shutdown(); |
| | | } |
| | | else |
| | | { |
| | | // The former RS answers discovery, then refuses the elected connection. |
| | | oldRS.delayedFailoverHandshake = new DelayedFailoverHandshake(1, 0, oldRS.listenSocket); |
| | | nextRS.withholdTopology = withholdTopology; |
| | | if (wrongGeneration || changedGeneration) |
| | | { |
| | | nextRS.delayedFailoverHandshake = replacementHandshake; |
| | | } |
| | | if (wrongGeneration) |
| | | { |
| | | nextRS.generationOverride = domain.getGenerationID() + 1; |
| | | } |
| | | if (withholdTopology) |
| | | { |
| | | // A new handshake timeout must not extend the deadline already set by the stop. |
| | | setConnectionTimeout(60_000); |
| | | } |
| | | oldRS.closeTheSession(); |
| | | if (changedGeneration) |
| | | { |
| | | await(replacementHandshake.nextStartReceived); |
| | | nextRS.generationOverride = domain.getGenerationID() + 1; |
| | | replacementHandshake.sendNextReply.countDown(); |
| | | } |
| | | } |
| | | |
| | | stop.join(stopBound); |
| | | assertFalse(stop.isAlive(), "the graceful stop did not finish within its budget"); |
| | | assertEquals(oldRS.count(ReplicaOfflineMsg.class), 0, "offline was written after the old StopMsg"); |
| | | if (withholdTopology || wrongGeneration || changedGeneration) |
| | | { |
| | | if (withholdTopology) |
| | | { |
| | | assertEquals(nextRS.sessionsStarted(), 1, "stop did not attempt to open the replacement session"); |
| | | } |
| | | else |
| | | { |
| | | assertEquals(replacementHandshake.starts.get(), wrongGeneration ? 1 : 2); |
| | | assertEquals(nextRS.sessionsStarted(), 0, "stop opened a session with a different generation"); |
| | | } |
| | | assertFalse(marker.equals(offlineAnnouncementOfTheReplica()), "stop did not withdraw the undelivered marker"); |
| | | assertNull(nextRS.lastOffline, "offline was written before the replacement handshake finished"); |
| | | } |
| | | else |
| | | { |
| | | newTimer().repeatUntilSuccess(() -> |
| | | assertNotNull(nextRS.lastOffline, "the replacement RS did not receive offline")); |
| | | nextRS.waitForTheSessionToEnd(); |
| | | assertEquals(nextRS.lastOffline.getCSN().getServerId(), DS_ID); |
| | | assertEquals(nextRS.lastOffline.getCSN(), marker); |
| | | assertTrue(nextRS.received.indexOf(ReplicaOfflineMsg.class) < nextRS.received.indexOf(StopMsg.class), |
| | | "offline must precede the replacement session's StopMsg"); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | replacementHandshake.sendNextReply.countDown(); |
| | | setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS); |
| | | try |
| | | { |
| | | nextRS.shutdown(); |
| | | } |
| | | finally |
| | | { |
| | | cleanUp(oldRS, disabling); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private enum ReplacementRecovery { COMPLETE, OLD_WINDOW_EXHAUSTED, OUT_OF_CREDIT, SEARCH_FAILED } |
| | | |
| | | @DataProvider |
| | | public Object[][] replacementRecoveries() |
| | | { |
| | | return new Object[][] { { ReplacementRecovery.COMPLETE }, { ReplacementRecovery.OLD_WINDOW_EXHAUSTED }, |
| | | { ReplacementRecovery.OUT_OF_CREDIT }, { ReplacementRecovery.SEARCH_FAILED } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "replacementRecoveries", timeOut = 120_000) |
| | | public void shutdownOrdersOfflineAfterMissingReplacementHistory(ReplacementRecovery recovery) throws Exception |
| | | { |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | setConnectionTimeout(LONG_CONNECTION_TIMEOUT_MS); |
| | | final boolean exhaustedOldWindow = recovery == ReplacementRecovery.OLD_WINDOW_EXHAUSTED; |
| | | final WithholdingReplicationServer oldRS = new WithholdingReplicationServer(exhaustedOldWindow ? 3 : LARGE_WINDOW); |
| | | final boolean pauseRecovery = exhaustedOldWindow || recovery == ReplacementRecovery.OUT_OF_CREDIT; |
| | | final WithholdingReplicationServer nextRS = new WithholdingReplicationServer(pauseRecovery ? 1 : LARGE_WINDOW, 4); |
| | | Thread shutdown = null; |
| | | try |
| | | { |
| | | final LDAPReplicationDomain domain = startDomain(oldRS, 100000, nextRS.getAddress()); |
| | | assertEquals(replaceDescription("shared"), ResultCode.SUCCESS); |
| | | oldRS.waitForUpdates(1); |
| | | final CSN shared = oldRS.receivedUpdateCSNs().get(0); |
| | | final AtomicBoolean searchFailed = new AtomicBoolean(); |
| | | if (recovery == ReplacementRecovery.SEARCH_FAILED) |
| | | { |
| | | // This RS needs history older than the in-memory messages. Fail its backend search. |
| | | nextRS.state.update(new CSN(shared.getTime() - 1, 1, DS_ID)); |
| | | domain.setMissingChangesSearchHook(search -> { |
| | | searchFailed.set(true); |
| | | search.setResultCode(ResultCode.OPERATIONS_ERROR); |
| | | }); |
| | | } |
| | | else |
| | | { |
| | | nextRS.state.update(shared); |
| | | } |
| | | assertEquals(replaceDescription("missing one"), ResultCode.SUCCESS); |
| | | assertEquals(replaceDescription("missing two"), ResultCode.SUCCESS); |
| | | oldRS.waitForUpdates(3); |
| | | final List<CSN> missing = oldRS.receivedUpdateCSNs().subList(1, 3); |
| | | |
| | | nextRS.start(); |
| | | oldRS.advertiseRebalance(nextRS, domain); |
| | | newTimer().repeatUntilSuccess(() -> assertEquals(oldRS.count(StopMsg.class), 1)); |
| | | final CSN previous = offlineAnnouncementOfTheReplica(); |
| | | shutdown = startThread("shutdown after switch StopMsg", domain::shutdown); |
| | | newTimer().repeatUntilSuccess(() -> { |
| | | final CSN announced = offlineAnnouncementOfTheReplica(); |
| | | assertTrue(announced != null && !announced.equals(previous)); |
| | | }); |
| | | final CSN marker = offlineAnnouncementOfTheReplica(); |
| | | oldRS.shutdown(); |
| | | if (exhaustedOldWindow) |
| | | { |
| | | // The replacement needs more credit for the second missing update. The announcement |
| | | // must remain pending until it can send both updates and then the offline marker. |
| | | newTimer().repeatUntilSuccess(() -> assertTrue(offlineAnnouncementOfTheReplica() == null |
| | | || nextRS.count(ModifyMsg.class) == 1 && nextRS.count(WindowProbeMsg.class) > 0)); |
| | | assertEquals(offlineAnnouncementOfTheReplica(), marker, "shutdown withdrew the marker during recovery"); |
| | | assertNull(nextRS.lastOffline); |
| | | nextRS.giveCredit(2); |
| | | } |
| | | |
| | | shutdown.join(stopBoundMS()); |
| | | assertFalse(shutdown.isAlive(), "shutdown exceeded its budget"); |
| | | assertEquals(nextRS.sessionsStarted(), 1); |
| | | nextRS.waitForTheSessionToEnd(); |
| | | assertEquals(oldRS.count(ReplicaOfflineMsg.class), 0); |
| | | if (recovery == ReplacementRecovery.COMPLETE || exhaustedOldWindow) |
| | | { |
| | | assertEquals(nextRS.receivedUpdateCSNs(), missing); |
| | | assertEquals(nextRS.count(ReplicaOfflineMsg.class), 1); |
| | | assertEquals(nextRS.lastOffline.getCSN(), marker); |
| | | assertTrue(nextRS.received.lastIndexOf(ModifyMsg.class) < nextRS.received.indexOf(ReplicaOfflineMsg.class)); |
| | | } |
| | | else |
| | | { |
| | | assertNull(nextRS.lastOffline, "a replacement missing history received the offline marker"); |
| | | if (recovery == ReplacementRecovery.SEARCH_FAILED) |
| | | { |
| | | assertTrue(searchFailed.get(), "recovery did not reach the history search"); |
| | | assertTrue(nextRS.receivedUpdateCSNs().isEmpty()); |
| | | } |
| | | else |
| | | { |
| | | assertEquals(nextRS.receivedUpdateCSNs(), missing.subList(0, 1)); |
| | | } |
| | | assertNull(offlineAnnouncementOfTheReplica(), "the undelivered marker was not withdrawn"); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS); |
| | | try |
| | | { |
| | | nextRS.shutdown(); |
| | | } |
| | | finally |
| | | { |
| | | cleanUp(oldRS, shutdown); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private static ReplicationBroker brokerOf(LDAPReplicationDomain domain) throws ReflectiveOperationException |
| | | { |
| | | final Field field = ReplicationDomain.class.getDeclaredField("broker"); |
| | | field.setAccessible(true); |
| | | return (ReplicationBroker) field.get(domain); |
| | | } |
| | | |
| | | private static void runSwitchSender(AtomicReference<Runnable> pending) |
| | | { |
| | | final Runnable sender = pending.getAndSet(null); |
| | | if (sender != null) |
| | | { |
| | | sender.run(); |
| | | } |
| | | } |
| | | |
| | | @Test(timeOut = 120_000) |
| | | public void plannedRebalanceReplaysTheOldRsAndPublishesOnTheNewRs() throws Exception |
| | | { |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | final DN deleteDN = DN.valueOf("cn=before-switch," + baseDN); |
| | | TestCaseUtils.addEntry("dn: " + deleteDN, "objectClass: top", "objectClass: person", |
| | | "cn: before-switch", "sn: before-switch"); |
| | | final String entryUUID = getEntryUUID(deleteDN); |
| | | final WithholdingReplicationServer oldRS = new WithholdingReplicationServer(LARGE_WINDOW); |
| | | final WithholdingReplicationServer nextRS = new WithholdingReplicationServer(LARGE_WINDOW, 4); |
| | | Thread writer = null; |
| | | try |
| | | { |
| | | final LDAPReplicationDomain domain = startDomain(oldRS, 500, nextRS.getAddress()); |
| | | assertEquals(domain.getRsServerId(), oldRS.serverId); |
| | | nextRS.start(); |
| | | oldRS.advertiseRebalance(nextRS, domain); |
| | | |
| | | newTimer().repeatUntilSuccess(() -> assertEquals(oldRS.count(StopMsg.class), 1)); |
| | | assertEquals(domain.getRsServerId(), oldRS.serverId, "the old RS has not replied yet"); |
| | | |
| | | oldRS.goAway(); // A closing RS stops publishing heartbeats. |
| | | // The RS is still draining its side. Replay this update before replacing its session. |
| | | final CSN remoteCSN = new CSNGenerator(OTHER_DS_ID, 0).newCSN(); |
| | | oldRS.session.get().publish(new DeleteMsg(deleteDN, remoteCSN, entryUUID)); |
| | | newTimer().repeatUntilSuccess(() -> { |
| | | assertNull(DirectoryServer.getEntry(deleteDN)); |
| | | assertEquals(domain.getServerState().getCSN(OTHER_DS_ID), remoteCSN); |
| | | }); |
| | | |
| | | final AtomicReference<ResultCode> result = new AtomicReference<>(); |
| | | final Thread localWrite = startThread("write during planned switch", |
| | | () -> result.set(replaceDescription("during planned switch"))); |
| | | writer = localWrite; |
| | | newTimer().repeatUntilSuccess(() -> assertTrue(Arrays.stream(localWrite.getStackTrace()).anyMatch(frame -> |
| | | frame.getClassName().equals(ReplicationBroker.class.getName()) && frame.getMethodName().equals("publish")), |
| | | "the local write did not wait for a session to publish on")); |
| | | // Leave the peer draining past the configured connection timeout. |
| | | localWrite.join(SHORT_CONNECTION_TIMEOUT_MS + 500); |
| | | assertEquals(domain.getRsServerId(), oldRS.serverId, "the old RS is still finishing its sends"); |
| | | assertEquals(oldRS.receivedUpdateCSNs(), Collections.emptyList()); |
| | | assertNull(result.get(), "the write completed before the session could publish it"); |
| | | |
| | | oldRS.closeTheSession(); |
| | | new TestTimer.Builder().maxSleep(30, SECONDS).sleepTimes(50, MILLISECONDS).toTimer() |
| | | .repeatUntilSuccess(() -> assertEquals(domain.getRsServerId(), nextRS.serverId)); |
| | | localWrite.join(10000); |
| | | assertEquals(result.get(), ResultCode.SUCCESS); |
| | | final CSN localCSN = domain.getServerState().getCSN(DS_ID); |
| | | assertNotNull(localCSN); |
| | | nextRS.waitForUpdates(1); |
| | | assertEquals(nextRS.receivedUpdateCSNs(), Collections.singletonList(localCSN)); |
| | | } |
| | | finally |
| | | { |
| | | setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS); |
| | | try |
| | | { |
| | | nextRS.shutdown(); |
| | | } |
| | | finally |
| | | { |
| | | cleanUp(oldRS, writer); |
| | | } |
| | | } |
| | | } |
| | | |
| | | @Test(timeOut = 120_000) |
| | | public void plannedRebalanceKeepsLdifDataAndReplaysUpdatesAfterAnInitializationHeader() throws Exception |
| | | { |
| | | final DN ldifBaseDN = DN.valueOf("o=switch-ldif"); |
| | | final DN retainedDN = DN.valueOf("cn=retain," + ldifBaseDN); |
| | | final DN replayDN = DN.valueOf("cn=delete," + ldifBaseDN); |
| | | final DN backendDN = DN.valueOf("ds-cfg-backend-id=switchLdif,cn=Backends,cn=config"); |
| | | final Path ldifFile = Path.of(TestCaseUtils.createTempFile( |
| | | "dn: " + ldifBaseDN, "objectClass: top", "objectClass: organization", "o: switch-ldif", "")); |
| | | TestCaseUtils.addEntry("dn: " + backendDN, "objectClass: top", "objectClass: ds-cfg-backend", |
| | | "objectClass: ds-cfg-local-backend", "objectClass: ds-cfg-ldif-backend", "ds-cfg-backend-id: switchLdif", |
| | | "ds-cfg-enabled: true", "ds-cfg-java-class: org.opends.server.backends.LDIFBackend", |
| | | "ds-cfg-writability-mode: enabled", "ds-cfg-base-dn: " + ldifBaseDN, "ds-cfg-ldif-file: " + ldifFile); |
| | | final WithholdingReplicationServer oldRS = new WithholdingReplicationServer(LARGE_WINDOW); |
| | | final WithholdingReplicationServer nextRS = new WithholdingReplicationServer(LARGE_WINDOW, 4); |
| | | try |
| | | { |
| | | TestCaseUtils.addEntry("dn: " + retainedDN, "objectClass: top", "objectClass: person", |
| | | "cn: retain", "sn: retain"); |
| | | TestCaseUtils.addEntry("dn: " + replayDN, "objectClass: top", "objectClass: person", |
| | | "cn: delete", "sn: delete"); |
| | | final String replayUUID = getEntryUUID(replayDN); |
| | | |
| | | final LDAPReplicationDomain domain = startDomain(ldifBaseDN, oldRS, 100000, nextRS.getAddress()); |
| | | final AtomicBoolean importClaimed = new AtomicBoolean(); |
| | | domain.setImportClaimHook(() -> importClaimed.set(true)); |
| | | assertEquals(domain.getRsServerId(), oldRS.serverId); |
| | | nextRS.start(); |
| | | oldRS.advertiseRebalance(nextRS, domain); |
| | | newTimer().repeatUntilSuccess(() -> assertEquals(oldRS.count(StopMsg.class), 1)); |
| | | |
| | | // Hold the stop reply while the DS deals with the remaining frames from the old RS. |
| | | final Session retiring = oldRS.session.get(); |
| | | assertTrue(retiring.publish(new InitializeTargetMsg(ldifBaseDN, OTHER_DS_ID, DS_ID, OTHER_DS_ID, 1, 4), null)); |
| | | final CSN replayCSN = new CSNGenerator(OTHER_DS_ID, 0).newCSN(); |
| | | assertTrue(retiring.publish(new DeleteMsg(replayDN, replayCSN, replayUUID), null)); |
| | | newTimer().repeatUntilSuccess(() -> { |
| | | assertFalse(importClaimed.get(), "the old session entered full initialization"); |
| | | assertEquals(domain.getServerState().getCSN(OTHER_DS_ID), replayCSN, "the update has not replayed"); |
| | | }); |
| | | |
| | | assertEquals(domain.getRsServerId(), oldRS.serverId, "the replay must finish before the stop reply"); |
| | | assertNotNull(DirectoryServer.getEntry(retainedDN)); |
| | | assertNull(DirectoryServer.getEntry(replayDN)); |
| | | final String storedLdif = Files.readString(ldifFile); |
| | | assertTrue(storedLdif.contains("dn: " + retainedDN), "the active LDIF lost an existing entry"); |
| | | assertFalse(storedLdif.contains("dn: " + replayDN), "the active LDIF did not record the incremental delete"); |
| | | |
| | | oldRS.goAway(); |
| | | oldRS.closeTheSession(); |
| | | newTimer().repeatUntilSuccess(() -> assertEquals(domain.getRsServerId(), nextRS.serverId)); |
| | | } |
| | | finally |
| | | { |
| | | try |
| | | { |
| | | nextRS.shutdown(); |
| | | } |
| | | finally |
| | | { |
| | | try |
| | | { |
| | | oldRS.shutdown(); |
| | | } |
| | | finally |
| | | { |
| | | MultimasterReplication.deleteDomain(ldifBaseDN); |
| | | TestCaseUtils.deleteEntry(backendDN); |
| | | Files.deleteIfExists(ldifFile); |
| | | Files.deleteIfExists(Path.of(ldifFile + ".old")); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | @Test(timeOut = 120_000) |
| | | public void plannedRebalanceAbortsOnlyTheOldSessionWhenItDoesNotReply() throws Exception |
| | | { |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | final WithholdingReplicationServer oldRS = new WithholdingReplicationServer(LARGE_WINDOW); |
| | | final WithholdingReplicationServer nextRS = new WithholdingReplicationServer(LARGE_WINDOW, 4); |
| | | try |
| | | { |
| | | final LDAPReplicationDomain domain = startDomain(oldRS, 100000, nextRS.getAddress()); |
| | | assertEquals(domain.getRsServerId(), oldRS.serverId); |
| | | nextRS.start(); |
| | | |
| | | final List<String> records = errorLogRecordsOf(() -> { |
| | | oldRS.advertiseRebalance(nextRS, domain); |
| | | newTimer().repeatUntilSuccess(() -> assertEquals(oldRS.count(StopMsg.class), 1)); |
| | | // Keep the session open without answering the StopMsg or accepting a new connection. |
| | | oldRS.goAway(); |
| | | new TestTimer.Builder().maxSleep(30, SECONDS).sleepTimes(50, MILLISECONDS).toTimer() |
| | | .repeatUntilSuccess(() -> assertEquals(domain.getRsServerId(), nextRS.serverId)); |
| | | return null; |
| | | }); |
| | | assertTrue(records.stream().anyMatch(record -> record.contains("Timed out switching from replication server")), |
| | | "the switch completed without the expected timeout diagnostic"); |
| | | assertEquals(replaceDescription("after the old session timed out"), ResultCode.SUCCESS); |
| | | nextRS.waitForUpdates(1); |
| | | } |
| | | finally |
| | | { |
| | | try |
| | | { |
| | | nextRS.shutdown(); |
| | | } |
| | | finally |
| | | { |
| | | cleanUp(oldRS); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private enum FormerRsDuringFailover |
| | | { |
| | | OFFLINE, |
| | | TIMES_OUT, |
| | | DISAPPEARS_AFTER_PROBE |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] failoverStartReplyTimeouts() |
| | | { |
| | | return new Object[][] { |
| | | { 0, 1, FormerRsDuringFailover.OFFLINE }, // The discovery probe times out. |
| | | { 1, 1, FormerRsDuringFailover.OFFLINE }, // The elected RS times out after a successful probe. |
| | | { 0, 2, FormerRsDuringFailover.OFFLINE }, // The discovery timeout is followed by another timeout. |
| | | { 1, 2, FormerRsDuringFailover.OFFLINE }, // The elected RS times out again. |
| | | { 0, 1, FormerRsDuringFailover.TIMES_OUT }, |
| | | { 0, 1, FormerRsDuringFailover.DISAPPEARS_AFTER_PROBE } |
| | | }; |
| | | } |
| | | |
| | | @Test(dataProvider = "failoverStartReplyTimeouts", timeOut = 120_000) |
| | | public void failoverAllowsOneRetryOfTheSurvivingRs(int successfulProbes, int timedOutReplies, |
| | | FormerRsDuringFailover formerRs) throws Exception |
| | | { |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | final WithholdingReplicationServer first = new WithholdingReplicationServer(LARGE_WINDOW); |
| | | final WithholdingReplicationServer second = new WithholdingReplicationServer(LARGE_WINDOW, 4); |
| | | // The configured URLs are sorted, so put the original RS first. |
| | | final boolean firstSortsFirst = first.getAddress().compareTo(second.getAddress()) < 0; |
| | | final WithholdingReplicationServer oldRS = firstSortsFirst ? first : second; |
| | | final WithholdingReplicationServer nextRS = firstSortsFirst ? second : first; |
| | | final DelayedFailoverHandshake handshake = new DelayedFailoverHandshake(successfulProbes, timedOutReplies, |
| | | formerRs == FormerRsDuringFailover.DISAPPEARS_AFTER_PROBE ? oldRS.listenSocket : null); |
| | | final DelayedFailoverHandshake oldHandshake = new DelayedFailoverHandshake(0, 2); |
| | | Thread writer = null; |
| | | try |
| | | { |
| | | // Answer startup probes while ensuring the original RS wins the election. |
| | | nextRS.differentGroup = true; |
| | | nextRS.start(); |
| | | final LDAPReplicationDomain domain = startDomain(oldRS, 100000, nextRS.getAddress()); |
| | | assertEquals(domain.getRsServerId(), oldRS.serverId); |
| | | nextRS.differentGroup = false; |
| | | nextRS.delayedFailoverHandshake = handshake; |
| | | if (formerRs == FormerRsDuringFailover.OFFLINE) |
| | | { |
| | | oldRS.shutdown(); |
| | | } |
| | | else |
| | | { |
| | | newTimer().repeatUntilSuccess(() -> assertNotNull(oldRS.session.get())); |
| | | if (formerRs == FormerRsDuringFailover.TIMES_OUT) |
| | | { |
| | | oldRS.delayedFailoverHandshake = oldHandshake; |
| | | } |
| | | oldRS.dropTheSession(); |
| | | } |
| | | |
| | | await(handshake.nextStartReceived); |
| | | final AtomicReference<ResultCode> duringFailover = new AtomicReference<>(); |
| | | if (timedOutReplies == 1) |
| | | { |
| | | assertFalse(domain.hasConnectionError(), "the broker declared isolation before retrying the surviving RS"); |
| | | if (formerRs == FormerRsDuringFailover.TIMES_OUT) |
| | | { |
| | | assertEquals(oldHandshake.starts.get(), 1, "the broker retried the former RS before the survivor"); |
| | | } |
| | | final Thread localWrite = startThread("write during failover retry", |
| | | () -> duringFailover.set(replaceDescription("during failover retry"))); |
| | | writer = localWrite; |
| | | newTimer().repeatUntilSuccess(() -> assertTrue(isIn(localWrite, ReplicationBroker.class, "publish"), |
| | | "the write did not reach replication during failover")); |
| | | } |
| | | else |
| | | { |
| | | assertTrue(domain.hasConnectionError(), "the broker did not report isolation after the retry expired"); |
| | | assertEquals(replaceDescription("while isolated"), ResultCode.UNWILLING_TO_PERFORM); |
| | | } |
| | | handshake.sendNextReply.countDown(); |
| | | |
| | | newTimer().repeatUntilSuccess(() -> { |
| | | assertEquals(domain.getRsServerId(), nextRS.serverId); |
| | | assertFalse(domain.hasConnectionError(), "the broker did not clear isolation after reconnecting"); |
| | | }); |
| | | if (writer != null) |
| | | { |
| | | assertEquals(handshake.starts.get(), successfulProbes + timedOutReplies + 1, |
| | | "the surviving RS should have connected on the extra attempt"); |
| | | writer.join(10_000); |
| | | assertEquals(duringFailover.get(), ResultCode.SUCCESS); |
| | | final CSN firstCSN = domain.getServerState().getCSN(DS_ID); |
| | | assertNotNull(firstCSN); |
| | | assertEquals(replaceDescription("after failover"), ResultCode.SUCCESS); |
| | | final CSN secondCSN = domain.getServerState().getCSN(DS_ID); |
| | | assertTrue(firstCSN.isOlderThan(secondCSN)); |
| | | nextRS.waitForUpdates(2); |
| | | assertEquals(nextRS.receivedUpdateCSNs(), Arrays.asList(firstCSN, secondCSN)); |
| | | } |
| | | else |
| | | { |
| | | assertEquals(replaceDescription("after isolation"), ResultCode.SUCCESS); |
| | | nextRS.waitForUpdates(1); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | handshake.sendNextReply.countDown(); |
| | | oldHandshake.sendNextReply.countDown(); |
| | | try |
| | | { |
| | | nextRS.shutdown(); |
| | | } |
| | | finally |
| | | { |
| | | cleanUp(oldRS, writer); |
| | | } |
| | | } |
| | | } |
| | | |
| | | @Test(timeOut = 120_000) |
| | | public void failoverRetriesElectedRsAfterStartReplyTimeout() throws Exception |
| | | { |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | final WithholdingReplicationServer oldRS = new WithholdingReplicationServer(LARGE_WINDOW); |
| | | final WithholdingReplicationServer otherRS = new WithholdingReplicationServer(LARGE_WINDOW, 4); |
| | | final DelayedFailoverHandshake oldHandshake = new DelayedFailoverHandshake(1, 1); |
| | | final DelayedFailoverHandshake otherHandshake = new DelayedFailoverHandshake(0, 2); |
| | | try |
| | | { |
| | | otherRS.differentGroup = true; |
| | | otherRS.start(); |
| | | final LDAPReplicationDomain domain = startDomain(oldRS, 100000, otherRS.getAddress()); |
| | | assertEquals(domain.getRsServerId(), oldRS.serverId); |
| | | newTimer().repeatUntilSuccess(() -> assertNotNull(oldRS.session.get())); |
| | | |
| | | otherRS.differentGroup = false; |
| | | otherRS.delayedFailoverHandshake = otherHandshake; |
| | | oldRS.delayedFailoverHandshake = oldHandshake; |
| | | oldRS.dropTheSession(); |
| | | |
| | | await(oldHandshake.nextStartReceived); |
| | | assertFalse(domain.hasConnectionError(), "the broker declared isolation before retrying the elected RS"); |
| | | assertEquals(otherHandshake.starts.get(), 1, "the other RS should only receive the discovery probe"); |
| | | oldHandshake.sendNextReply.countDown(); |
| | | |
| | | waitForConnection(domain); |
| | | assertEquals(domain.getRsServerId(), oldRS.serverId); |
| | | assertFalse(domain.hasConnectionError()); |
| | | assertEquals(replaceDescription("after retrying the elected RS"), ResultCode.SUCCESS); |
| | | oldRS.waitForUpdates(1); |
| | | } |
| | | finally |
| | | { |
| | | oldHandshake.sendNextReply.countDown(); |
| | | otherHandshake.sendNextReply.countDown(); |
| | | try |
| | | { |
| | | otherRS.shutdown(); |
| | | } |
| | | finally |
| | | { |
| | | cleanUp(oldRS); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private LDAPReplicationDomain startDomain(WithholdingReplicationServer rs) throws Exception |
| | | { |
| | | // Heartbeats far apart: the session stays up whatever the replication server reads. |
| | |
| | | } |
| | | |
| | | private LDAPReplicationDomain startDomain(WithholdingReplicationServer rs, long heartbeatIntervalMS, |
| | | int... additionalPorts) throws Exception |
| | | String... otherServers) throws Exception |
| | | { |
| | | return startDomain(baseDN, rs, heartbeatIntervalMS, otherServers); |
| | | } |
| | | |
| | | private LDAPReplicationDomain startDomain(DN domainBaseDN, WithholdingReplicationServer rs, long heartbeatIntervalMS, |
| | | String... otherServers) throws Exception |
| | | { |
| | | rs.start(); |
| | | final SortedSet<String> servers = new TreeSet<>(Collections.singleton("127.0.0.1:" + rs.getPort())); |
| | | for (int port : additionalPorts) |
| | | { |
| | | servers.add("127.0.0.1:" + port); |
| | | } |
| | | final DomainFakeCfg conf = new DomainFakeCfg(baseDN, DS_ID, servers); |
| | | final SortedSet<String> servers = new TreeSet<>(Arrays.asList(otherServers)); |
| | | servers.add(rs.getAddress()); |
| | | final DomainFakeCfg conf = new DomainFakeCfg(domainBaseDN, DS_ID, servers); |
| | | conf.setHeartbeatInterval(heartbeatIntervalMS); |
| | | final LDAPReplicationDomain domain = MultimasterReplication.createNewDomain(conf); |
| | | domain.start(); |
| | |
| | | return new TestTimer.Builder().maxSleep(10, SECONDS).sleepTimes(50, MILLISECONDS).toTimer(); |
| | | } |
| | | |
| | | /** Withholds start replies until the broker's read times out, then lets the test release the next reply. */ |
| | | private static final class DelayedFailoverHandshake |
| | | { |
| | | private final int successfulProbes; |
| | | private final int timedOutReplies; |
| | | private final ServerSocket formerRsListener; |
| | | private final AtomicInteger starts = new AtomicInteger(); |
| | | private final CountDownLatch nextStartReceived = new CountDownLatch(1); |
| | | private final CountDownLatch sendNextReply = new CountDownLatch(1); |
| | | |
| | | DelayedFailoverHandshake(int successfulProbes, int timedOutReplies) |
| | | { |
| | | this(successfulProbes, timedOutReplies, null); |
| | | } |
| | | |
| | | DelayedFailoverHandshake(int successfulProbes, int timedOutReplies, ServerSocket formerRsListener) |
| | | { |
| | | this.successfulProbes = successfulProbes; |
| | | this.timedOutReplies = timedOutReplies; |
| | | this.formerRsListener = formerRsListener; |
| | | } |
| | | |
| | | boolean respond(Session session) throws Exception |
| | | { |
| | | final int startNumber = starts.incrementAndGet(); |
| | | if (startNumber == 1 && formerRsListener != null) |
| | | { |
| | | // The former RS has accepted its discovery connection and can answer even after closing its listener. |
| | | formerRsListener.close(); |
| | | } |
| | | final int attempt = startNumber - successfulProbes; |
| | | if (attempt >= 1 && attempt <= timedOutReplies) |
| | | { |
| | | session.setSoTimeout(2 * MultimasterReplication.getConnectionTimeoutMS()); |
| | | session.receive(); // The broker closes the session after its read deadline. |
| | | return false; |
| | | } |
| | | if (attempt == timedOutReplies + 1) |
| | | { |
| | | nextStartReceived.countDown(); |
| | | await(sendNextReply); |
| | | } |
| | | return true; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * A replication server which keeps the session of the domain up and reads every message of it, |
| | | * but gives no credit beyond the window it opens the session with - of one update, unless the |
| | |
| | | private final List<Class<?>> received = new CopyOnWriteArrayList<>(); |
| | | /** The CSNs of the changes received on the sessions, in the order they came. */ |
| | | private final List<CSN> updateCSNs = new CopyOnWriteArrayList<>(); |
| | | private volatile AckMsg lastAck; |
| | | private volatile ReplicaOfflineMsg lastOffline; |
| | | private volatile boolean differentGroup; |
| | | private volatile boolean withholdTopology; |
| | | private volatile Long generationOverride; |
| | | private final ServerState state = new ServerState(); |
| | | /** Guards {@link #reading} and the changes of {@link #away}. */ |
| | | private final Object readingLock = new Object(); |
| | |
| | | private boolean reading = true; |
| | | /** Whether this server is away: it then sends no heartbeat, and answers no connection either. */ |
| | | private volatile boolean away; |
| | | private volatile boolean differentGroup; |
| | | private volatile Callable<Void> beforeStartReply; |
| | | /** 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; |
| | | |
| | | WithholdingReplicationServer() throws IOException |
| | | { |
| | |
| | | return listenSocket.getLocalPort(); |
| | | } |
| | | |
| | | String getAddress() |
| | | { |
| | | return "127.0.0.1:" + getPort(); |
| | | } |
| | | |
| | | void advertiseRebalance(WithholdingReplicationServer nextRS, LDAPReplicationDomain domain) throws IOException |
| | | { |
| | | final long generationId = domain.getGenerationID(); |
| | | final byte groupId = domain.getGroupId(); |
| | | final DSInfo otherDS = new DSInfo(OTHER_DS_ID, "", serverId, generationId, ServerStatus.NORMAL_STATUS, |
| | | false, AssuredMode.SAFE_DATA_MODE, (byte) 0, groupId, Collections.emptyList(), Collections.emptyList(), |
| | | Collections.emptyList(), ProtocolVersion.getCurrentVersion()); |
| | | final Session current = session.get(); |
| | | current.publish(new TopologyMsg(Collections.singletonList(otherDS), Arrays.asList( |
| | | new RSInfo(serverId, getAddress(), generationId, groupId, 1), |
| | | new RSInfo(nextRS.serverId, nextRS.getAddress(), generationId, groupId, 1)))); |
| | | final MonitorMsg monitor = new MonitorMsg(serverId, DS_ID); |
| | | monitor.setReplServerDbState(state.duplicate()); |
| | | assertTrue(current.publish(monitor, null)); |
| | | assertTrue(current.publish(monitor, null)); |
| | | } |
| | | |
| | | @Override |
| | | public void run() |
| | | { |
| | |
| | | { |
| | | hook.call(); |
| | | } |
| | | final String url = "127.0.0.1:" + getPort(); |
| | | final DelayedFailoverHandshake failoverHandshake = delayedFailoverHandshake; |
| | | if (failoverHandshake != null && !failoverHandshake.respond(s)) |
| | | { |
| | | return; |
| | | } |
| | | final String url = getAddress(); |
| | | final byte groupId = differentGroup ? (byte) (start.getGroupId() + 1) : start.getGroupId(); |
| | | final Long override = generationOverride; |
| | | s.publish(new ReplServerStartMsg(serverId, url, start.getBaseDN(), window, state.duplicate(), |
| | | start.getGenerationId(), start.getSSLEncryption(), groupId, 5000)); |
| | | override != null ? override : start.getGenerationId(), start.getSSLEncryption(), groupId, 5000)); |
| | | if (!start.getSSLEncryption()) |
| | | { |
| | | s.stopEncryption(); |
| | |
| | | } |
| | | return; |
| | | } |
| | | s.publish(new TopologyMsg(new ArrayList<DSInfo>(), Collections.singletonList( |
| | | new RSInfo(serverId, url, start.getGenerationId(), groupId, 1)))); |
| | | s.setSoTimeout(0); |
| | | session.set(s); |
| | | startHeartbeats(s, start.getHeartbeatInterval()); |
| | | if (!withholdTopology) |
| | | { |
| | | s.publish(new TopologyMsg(new ArrayList<DSInfo>(), Collections.singletonList( |
| | | new RSInfo(serverId, url, start.getGenerationId(), groupId, 1)))); |
| | | s.setSoTimeout(0); |
| | | session.set(s); |
| | | startHeartbeats(s, start.getHeartbeatInterval()); |
| | | } |
| | | while (true) |
| | | { |
| | | waitToRead(); |
| | |
| | | state.update(csn); |
| | | } |
| | | received.add(msg.getClass()); |
| | | if (msg instanceof AckMsg) |
| | | { |
| | | lastAck = (AckMsg) msg; |
| | | } |
| | | else if (msg instanceof ReplicaOfflineMsg) |
| | | { |
| | | lastOffline = (ReplicaOfflineMsg) msg; |
| | | } |
| | | } |
| | | } |
| | | catch (Exception e) |
| | |
| | | * |
| | | * Copyright 2009-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2011-2016 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.protocol; |
| | | |
| | |
| | | }; |
| | | } |
| | | |
| | | @Test |
| | | public void preparationRefusalRetainsItsAttemptAcrossV9AndCannotLoseItOnV8() throws Exception |
| | | { |
| | | final String attemptId = "f3916e33-5e3f-450e-ba61-e3e0baf3c784"; |
| | | final InitializeTargetMsg header = new InitializeTargetMsg(DN.valueOf("dc=example"), 1, 2, 1, 17, 8, attemptId); |
| | | final InitializeTargetMsg decoded = new InitializeTargetMsg( |
| | | header.getBytes(REPLICATION_PROTOCOL_V9), REPLICATION_PROTOCOL_V9); |
| | | assertEquals(decoded.getInitializationAttemptId(), attemptId); |
| | | final InitializeTargetMsg legacy = new InitializeTargetMsg( |
| | | header.getBytes(REPLICATION_PROTOCOL_V8), REPLICATION_PROTOCOL_V8); |
| | | assertNull(legacy.getInitializationAttemptId()); |
| | | assertEquals(legacy.getBaseDN(), DN.valueOf("dc=example")); |
| | | assertEquals(legacy.getEntryCount(), 17L); |
| | | assertEquals(legacy.getInitWindow(), 8); |
| | | |
| | | final LocalizableMessage reason = LocalizableMessage.raw("import preparation refused"); |
| | | final ErrorMsg refusal = new ErrorMsg(2, 1, reason, attemptId); |
| | | final ErrorMsg forwarded = new ErrorMsg(refusal.getBytes(REPLICATION_PROTOCOL_V9), REPLICATION_PROTOCOL_V9); |
| | | assertEquals(forwarded.getInitializationAttemptId(), attemptId); |
| | | assertEquals(forwarded.getSenderID(), 2); |
| | | assertEquals(forwarded.getDestination(), 1); |
| | | assertEquals(forwarded.getDetails().toString(), "import preparation refused"); |
| | | assertNull(forwarded.getBytes(REPLICATION_PROTOCOL_V8)); |
| | | final ErrorMsg uncorrelated = new ErrorMsg(2, 1, reason); |
| | | final ErrorMsg legacyError = new ErrorMsg( |
| | | uncorrelated.getBytes(REPLICATION_PROTOCOL_V8), REPLICATION_PROTOCOL_V8); |
| | | assertNull(legacyError.getInitializationAttemptId()); |
| | | assertEquals(legacyError.getDetails().toString(), "import preparation refused"); |
| | | |
| | | final InitializeRcvAckMsg ready = new InitializeRcvAckMsg(2, 1, attemptId); |
| | | final InitializeRcvAckMsg decodedReady = new InitializeRcvAckMsg( |
| | | ready.getBytes(REPLICATION_PROTOCOL_V9), REPLICATION_PROTOCOL_V9); |
| | | assertEquals(decodedReady.getInitializationAttemptId(), attemptId); |
| | | assertEquals(decodedReady.getNumAck(), 0); |
| | | assertNull(decodedReady.getBytes(REPLICATION_PROTOCOL_V8)); |
| | | final InitializeRcvAckMsg credit = new InitializeRcvAckMsg( |
| | | new InitializeRcvAckMsg(2, 1, 4).getBytes(REPLICATION_PROTOCOL_V8), REPLICATION_PROTOCOL_V8); |
| | | assertEquals(credit.getNumAck(), 4); |
| | | assertNull(credit.getInitializationAttemptId()); |
| | | } |
| | | |
| | | /** |
| | | * Test that various combinations of ErrorMsg encoding and decoding |
| | | * using protocol VLAST and V3 are working. |
| | |
| | | } |
| | | |
| | | @Test |
| | | public void plannedSwitchKeepsReadingUntilThePeerReplies() throws Exception |
| | | { |
| | | try (SessionPair pair = connectSessionPair()) |
| | | { |
| | | pair.peer.publish(new EntryMsg(PEER_ID, SENDER_ID, new byte[] { 1, 2, 3 }, 1)); |
| | | |
| | | assertThat(pair.publisher.closeForSwitch(Runnable::run)).isTrue(); |
| | | |
| | | assertThat(pair.peer.receive()).isInstanceOf(StopMsg.class); |
| | | assertThat(((EntryMsg) pair.publisher.receive()).getEntryBytes()) |
| | | .containsExactly((byte) 1, (byte) 2, (byte) 3); |
| | | assertThat(pair.publisher.publish(new HeartbeatMsg(), null)).isFalse(); |
| | | pair.peer.close(); |
| | | assertThat(pair.publisher.receive()).isInstanceOf(StopMsg.class); |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void plannedSwitchEndsControlWritesWithTheStopFrame() throws Exception |
| | | { |
| | | try (SessionPair pair = connectSessionPair()) |
| | | { |
| | | final AtomicReference<Runnable> sender = new AtomicReference<>(); |
| | | final CSN csn = newCSN(); |
| | | assertThat(pair.publisher.closeForSwitch(sender::set)).isTrue(); |
| | | assertThat(pair.publisher.publish(new HeartbeatMsg(), null)).isFalse(); |
| | | assertThat(pair.publisher.publish(new AckMsg(csn), null)).isTrue(); |
| | | assertThat(pair.publisher.publish(new ReplicaOfflineMsg(csn), null)).isTrue(); |
| | | |
| | | sender.get().run(); |
| | | assertThat(((AckMsg) pair.peer.receive()).getCSN()).isEqualTo(csn); |
| | | assertThat(((ReplicaOfflineMsg) pair.peer.receive()).getCSN()).isEqualTo(csn); |
| | | assertThat(pair.peer.receive()).isInstanceOf(StopMsg.class); |
| | | assertThat(pair.publisher.publish(new AckMsg(csn), null)).isFalse(); |
| | | assertThat(pair.publisher.publish(new ReplicaOfflineMsg(csn), null)).isFalse(); |
| | | } |
| | | } |
| | | |
| | | @Test(timeOut = 30_000) |
| | | public void plannedSwitchReleasesAPublicationWaitingForTheWriteLock() throws Exception |
| | | { |
| | | final ExecutorService writers = Executors.newFixedThreadPool(2); |
| | | try (SessionPair pair = connectSessionPair()) |
| | | { |
| | | try |
| | | { |
| | | writers.submit(() -> pair.publisher.publish(newBlockingMsg(), null)); |
| | | pair.awaitBytesReachedThePeer(); |
| | | |
| | | final CountDownLatch started = new CountDownLatch(1); |
| | | final AtomicReference<Thread> waitingThread = new AtomicReference<>(); |
| | | final Future<Boolean> waiting = writers.submit(() -> { |
| | | waitingThread.set(Thread.currentThread()); |
| | | started.countDown(); |
| | | return pair.publisher.publish(new HeartbeatMsg(), null); |
| | | }); |
| | | assertThat(started.await(5, TimeUnit.SECONDS)).isTrue(); |
| | | awaitWaitingIn(waitingThread.get(), "send"); |
| | | assertThat(pair.publisher.closeForSwitch(task -> start("planned stop", task))).isTrue(); |
| | | |
| | | assertThat(waiting.get(3, TimeUnit.SECONDS)).isFalse(); |
| | | } |
| | | finally |
| | | { |
| | | pair.publisher.abort(new IOException("the test releases the blocked writer")); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | writers.shutdownNow(); |
| | | assertThat(writers.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void aMessageWhichCannotBeEncodedForThePeerIsRefusedWithoutRunningTheCallback() |
| | | throws Exception |
| | | { |
| | |
| | | |
| | | import java.net.ServerSocket; |
| | | import java.net.Socket; |
| | | import java.util.List; |
| | | import java.util.TreeSet; |
| | | import java.util.concurrent.Callable; |
| | | import java.util.concurrent.ExecutorService; |
| | |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.opends.server.TestCaseUtils; |
| | | import org.opends.server.replication.ReplicationTestCase; |
| | | import org.opends.server.replication.common.ServerState; |
| | | import org.opends.server.replication.protocol.ReplSessionSecurity; |
| | | import org.opends.server.replication.protocol.Session; |
| | | import org.testng.annotations.DataProvider; |
| | | import org.testng.annotations.Test; |
| | | |
| | | /** |
| | |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] registeredDataServerStates() |
| | | { |
| | | return new Object[][] { |
| | | { false, false, true }, |
| | | { true, false, false }, |
| | | { false, true, false } |
| | | }; |
| | | } |
| | | |
| | | /** |
| | | * The handshake also aborts before registering, e.g. when rejecting a second |
| | | * connection with an already connected server id. Such an abort must never |
| | | * evict the legitimately connected handler owning that server id. |
| | | * A second handshake must keep the first handler registered until teardown. |
| | | * Only an existing live session is evidence of two live connections sharing an ID. |
| | | */ |
| | | @Test |
| | | public void abortBeforeRegisterMustNotEvictConnectedDataServer() throws Exception |
| | | @Test(dataProvider = "registeredDataServerStates") |
| | | public void abortBeforeRegisterMustNotEvictConnectedDataServer(boolean closeSession, |
| | | boolean stopHandler, boolean duplicateIdError) throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer replicationServer = null; |
| | |
| | | final DataServerHandler connected = |
| | | new DataServerHandler(connectedSession, 100, replicationServer, 100); |
| | | initializeFromHandshake(connected, baseDN, REMOTE_DS_ID, true); |
| | | domain.lock(); |
| | | try |
| | | { |
| | | domain.lock(); |
| | | domain.register(connected); |
| | | } |
| | | finally |
| | |
| | | domain.release(); |
| | | } |
| | | |
| | | // Second handshake with the same server id: rejected and aborted |
| | | // before it ever registered. |
| | | final DataServerHandler duplicate = |
| | | new DataServerHandler(duplicateSession, 100, replicationServer, 100); |
| | | initializeFromHandshake(duplicate, baseDN, REMOTE_DS_ID, true); |
| | | assertTrue(domain.isAlreadyConnectedToDS(duplicate)); |
| | | try |
| | | { |
| | | // ServerReader closes the session before calling stopServer(), which |
| | | // can leave a closing session registered while a new handshake arrives. |
| | | if (closeSession) |
| | | { |
| | | connectedSession.close(); |
| | | } |
| | | if (stopHandler) |
| | | { |
| | | assertFalse(connected.engageShutdown()); |
| | | } |
| | | |
| | | duplicate.abortStart(null); |
| | | // Second handshake with the same server id: rejected and aborted |
| | | // before it ever registered. |
| | | final DataServerHandler duplicate = |
| | | new DataServerHandler(duplicateSession, 100, replicationServer, 100); |
| | | initializeFromHandshake(duplicate, baseDN, REMOTE_DS_ID, true); |
| | | final List<String> records = errorLogRecordsOf(() -> { |
| | | assertTrue(domain.isAlreadyConnectedToDS(duplicate)); |
| | | duplicate.abortStart(null); |
| | | return null; |
| | | }); |
| | | |
| | | assertSame(domain.getConnectedDSs().get(REMOTE_DS_ID), connected, |
| | | "aborting an unregistered handshake evicted the connected DS"); |
| | | assertEquals(records.stream().anyMatch(line -> line.contains("category=SYNC severity=ERROR msgID=54 ")), |
| | | duplicateIdError, records.toString()); |
| | | |
| | | assertSame(domain.getConnectedDSs().get(REMOTE_DS_ID), connected, |
| | | "aborting an unregistered handshake evicted the connected DS"); |
| | | } |
| | | finally |
| | | { |
| | | domain.lock(); |
| | | try |
| | | { |
| | | domain.unregisterFailedHandshake(connected); |
| | | } |
| | | finally |
| | | { |
| | | domain.release(); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | finally |
| | |
| | | handler.serverId = remoteServerId; |
| | | handler.serverURL = "127.0.0.1:1636"; |
| | | handler.setBaseDNAndDomain(baseDN, isDataServer); |
| | | handler.setInitialServerState(new ServerState()); |
| | | } |
| | | |
| | | /** Teardown must never mask the primary assertion failure. */ |
| | |
| | | package org.opends.server.replication.server; |
| | | |
| | | import static org.assertj.core.api.Assertions.assertThat; |
| | | import static org.forgerock.opendj.ldap.ModificationType.REPLACE; |
| | | import static org.opends.messages.ReplicationMessages.*; |
| | | import static org.opends.server.TestCaseUtils.*; |
| | | import static org.opends.server.protocols.internal.InternalClientConnection.getRootConnection; |
| | | import static org.opends.server.util.CollectionUtils.newArrayList; |
| | | import static org.opends.server.util.CollectionUtils.newTreeSet; |
| | | import static org.opends.server.util.StaticUtils.*; |
| | | |
| | | import java.io.DataInputStream; |
| | | import java.net.InetAddress; |
| | | import java.net.InetSocketAddress; |
| | | import java.net.ServerSocket; |
| | | import java.net.Socket; |
| | | import java.util.ArrayList; |
| | | import java.util.Collections; |
| | | import java.util.List; |
| | | import java.util.concurrent.CountDownLatch; |
| | | import java.util.concurrent.ExecutorService; |
| | | import java.util.concurrent.Executors; |
| | | import java.util.concurrent.Future; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.TimeoutException; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.forgerock.opendj.ldap.ResultCode; |
| | | import org.opends.server.TestCaseUtils; |
| | | import org.opends.server.replication.ReplicationTestCase; |
| | | import org.opends.server.replication.common.DSInfo; |
| | | import org.opends.server.replication.common.RSInfo; |
| | | import org.opends.server.replication.common.ServerState; |
| | | import org.opends.server.replication.plugin.DummyReplicationDomain; |
| | | import org.opends.server.replication.plugin.MultimasterReplication; |
| | | import org.opends.server.replication.protocol.ReplSessionSecurity; |
| | | import org.opends.server.replication.protocol.ReplServerStartMsg; |
| | | import org.opends.server.replication.protocol.ReplicationMsg; |
| | | import org.opends.server.replication.protocol.Session; |
| | | import org.opends.server.replication.protocol.StopMsg; |
| | | import org.opends.server.replication.protocol.TopologyMsg; |
| | | import org.opends.server.replication.service.ReplicationBroker; |
| | | import org.opends.server.types.HostPort; |
| | | import org.opends.server.util.TestTimer; |
| | | import org.testng.annotations.DataProvider; |
| | | import org.testng.annotations.Test; |
| | | |
| | | /** |
| | |
| | | |
| | | private static final int RS_ID = 8241; |
| | | private static final int PEER_RS_ID = 8242; |
| | | private static final String TRACE_TLS_FAILURES = "org.opends.server.replication.traceTlsFailures"; |
| | | |
| | | @DataProvider |
| | | public Object[][] generationDuringPeerStart() |
| | | { |
| | | return new Object[][] { { false }, { true } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "generationDuringPeerStart") |
| | | public void aSlowPeerStartReplyDoesNotDelayAnotherDirectoryServer(boolean generationChanges) throws Exception |
| | | { |
| | | TestCaseUtils.startServer(); |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final DN provider = DN.valueOf("cn=Multimaster Synchronization,cn=Synchronization Providers,cn=config"); |
| | | final int originalTimeout = MultimasterReplication.getConnectionTimeoutMS(); |
| | | final int[] ports = TestCaseUtils.findFreePorts(2); |
| | | final int dsId = 8243; |
| | | final int nextDsId = 8244; |
| | | final String db = "replicationServerSlowStartReplyDb"; |
| | | final HostPort peerAddress = HostPort.valueOf("127.0.0.1:" + ports[1]); |
| | | final CountDownLatch startReceived = new CountDownLatch(1); |
| | | final CountDownLatch sendReply = new CountDownLatch(1); |
| | | final CountDownLatch finishPeer = new CountDownLatch(1); |
| | | final ExecutorService clients = Executors.newFixedThreadPool(2); |
| | | ReplicationServer rs = null; |
| | | ReplicationBroker current = null; |
| | | ReplicationBroker next = null; |
| | | try (ServerSocket listener = bindPeerPort(ports[1])) |
| | | { |
| | | setConnectionTimeout(provider, SOCKET_TIMEOUT_MS); |
| | | listener.setSoTimeout(SOCKET_TIMEOUT_MS); |
| | | final ReplSessionSecurity security = getReplSessionSecurity(); |
| | | rs = new ReplicationServer(new ReplServerFakeConfiguration( |
| | | ports[0], db, 0, RS_ID, 0, 100, newTreeSet())); |
| | | current = new ReplicationBroker(new DummyReplicationDomain(EMPTY_DN_GENID), new ServerState(), |
| | | newFakeCfg(baseDN, dsId, ports[0]), security); |
| | | current.start(); |
| | | assertThat(current.isConnected()).isTrue(); |
| | | final ReplicationServerDomain domain = rs.getReplicationServerDomain(baseDN); |
| | | final TestTimer registration = new TestTimer.Builder().maxSleep(5, TimeUnit.SECONDS) |
| | | .sleepTimes(50, TimeUnit.MILLISECONDS).toTimer(); |
| | | registration.repeatUntilSuccess(() -> assertThat(domain.getConnectedDSs()).containsKey(dsId)); |
| | | final long advertisedGeneration = domain.getGenerationId(); |
| | | assertThat(advertisedGeneration).isEqualTo(EMPTY_DN_GENID); |
| | | |
| | | final Future<?> peer = clients.submit(() -> { |
| | | try (Socket socket = listener.accept(); |
| | | Session session = security.createServerSession(socket, SOCKET_TIMEOUT_MS)) |
| | | { |
| | | final ReplicationMsg start = session.receive(); |
| | | assertThat(start).isInstanceOf(ReplServerStartMsg.class); |
| | | assertThat(((ReplServerStartMsg) start).getGenerationId()).isEqualTo(advertisedGeneration); |
| | | startReceived.countDown(); |
| | | assertThat(sendReply.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue(); |
| | | session.publish(peerStartMsg(peerAddress, baseDN)); |
| | | stopEncryptionWith(session, start); |
| | | if (generationChanges) |
| | | { |
| | | assertThat(session.receive()).isInstanceOf(StopMsg.class); |
| | | } |
| | | else |
| | | { |
| | | assertThat(session.receive()).isInstanceOf(TopologyMsg.class); |
| | | final RSInfo info = new RSInfo(PEER_RS_ID, peerAddress.toString(), -1, (byte) 1, 1); |
| | | session.publish(new TopologyMsg(Collections.<DSInfo>emptyList(), newArrayList(info))); |
| | | assertThat(finishPeer.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue(); |
| | | } |
| | | } |
| | | return null; |
| | | }); |
| | | assertThat(rs.applyConfigurationChange(new ReplServerFakeConfiguration( |
| | | ports[0], db, 0, RS_ID, 0, 100, newTreeSet(peerAddress.toString()))).getResultCode()) |
| | | .isEqualTo(ResultCode.SUCCESS); |
| | | assertThat(startReceived.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)) |
| | | .as("the background RS connector has sent its start message").isTrue(); |
| | | |
| | | next = new ReplicationBroker(new DummyReplicationDomain(EMPTY_DN_GENID), new ServerState(), |
| | | newFakeCfg(baseDN, nextDsId, ports[0]), security); |
| | | final Future<?> directoryServer = clients.submit(next::start); |
| | | try |
| | | { |
| | | directoryServer.get(8, TimeUnit.SECONDS); |
| | | } |
| | | catch (TimeoutException e) |
| | | { |
| | | throw new AssertionError("the DS handshake waited for the peer RS start reply", e); |
| | | } |
| | | assertThat(next.isConnected()).isTrue(); |
| | | registration.repeatUntilSuccess(() -> assertThat(domain.getConnectedDSs()).containsKeys(dsId, nextDsId)); |
| | | |
| | | if (generationChanges) |
| | | { |
| | | final long newGeneration = advertisedGeneration + 1; |
| | | domain.changeGenerationId(newGeneration); |
| | | sendReply.countDown(); |
| | | peer.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | assertThat(domain.getConnectedRSs()).doesNotContainKey(PEER_RS_ID); |
| | | assertThat(domain.getGenerationId()).isEqualTo(newGeneration); |
| | | } |
| | | else |
| | | { |
| | | try (Socket socket = new Socket("127.0.0.1", ports[0]); |
| | | Session crossed = security.createClientSession(socket, SOCKET_TIMEOUT_MS)) |
| | | { |
| | | crossed.publish(peerStartMsg(peerAddress, baseDN)); |
| | | assertThat(crossed.receive()).as("the incoming RS connection should give way to the outgoing one") |
| | | .isInstanceOf(StopMsg.class); |
| | | } |
| | | sendReply.countDown(); |
| | | waitForRegistrationUnder(rs, baseDN, peerAddress, SOCKET_TIMEOUT_MS); |
| | | assertThat(domain.getGenerationId()).isEqualTo(advertisedGeneration); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | sendReply.countDown(); |
| | | finishPeer.countDown(); |
| | | try |
| | | { |
| | | stop(next, current); |
| | | remove(rs); |
| | | } |
| | | finally |
| | | { |
| | | clients.shutdownNow(); |
| | | setConnectionTimeout(provider, originalTimeout); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private void setConnectionTimeout(DN provider, int milliseconds) |
| | | { |
| | | assertThat(getRootConnection().processModify( |
| | | modifyRequest(provider, REPLACE, "ds-cfg-connection-timeout", milliseconds + " ms")).getResultCode()) |
| | | .isEqualTo(ResultCode.SUCCESS); |
| | | } |
| | | |
| | | @Test |
| | | public void tracesEveryFailedTlsAttemptWhenEnabled() throws Exception |
| | | { |
| | | TestCaseUtils.startServer(); |
| | | |
| | | final DN baseDN = DN.valueOf("cn=admin data"); |
| | | final int[] ports = TestCaseUtils.findFreePorts(2); |
| | | final HostPort peerAddress = HostPort.valueOf("127.0.0.1:" + ports[1]); |
| | | final String previous = System.getProperty(TRACE_TLS_FAILURES); |
| | | final ExecutorService peerThread = Executors.newSingleThreadExecutor(); |
| | | ReplicationServer rs = null; |
| | | try (ServerSocket listener = bindPeerPort(ports[1])) |
| | | { |
| | | listener.setSoTimeout(SOCKET_TIMEOUT_MS); |
| | | final Future<List<Integer>> clients = peerThread.submit(() -> rejectTlsHandshakes(listener, 3)); |
| | | rs = new ReplicationServer(new ReplServerFakeConfiguration( |
| | | ports[0], "replicationServerTlsAttemptDb", 0, RS_ID, 0, 100, newTreeSet())); |
| | | final ReplicationServer caller = rs; |
| | | final List<String> records = errorLogRecordsOf(() -> { |
| | | System.clearProperty(TRACE_TLS_FAILURES); |
| | | assertThat(caller.connect(peerAddress, baseDN)).isFalse(); |
| | | System.setProperty(TRACE_TLS_FAILURES, "true"); |
| | | assertThat(caller.connect(peerAddress, baseDN)).isFalse(); |
| | | assertThat(caller.connect(peerAddress, baseDN)).isFalse(); |
| | | return null; |
| | | }); |
| | | |
| | | final List<Integer> sourcePorts = clients.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | final String diagnostic = "Replication TLS client handshake failed for RS(" + RS_ID |
| | | + ") for domain \"cn=admin data\" from "; |
| | | assertThat(countRecordsOf(records, connectErrorPrefix(peerAddress, baseDN))).isEqualTo(1); |
| | | assertThat(countRecordsOf(records, diagnostic)).isEqualTo(2); |
| | | for (int sourcePort : sourcePorts.subList(1, 3)) |
| | | { |
| | | assertTlsAttempt(records, diagnostic, sourcePort, ports[1]); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | restoreTlsTracing(previous); |
| | | peerThread.shutdownNow(); |
| | | remove(rs); |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void tracesFailedTlsAttemptThroughDirectoryServerBroker() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf("dc=tls-test"); |
| | | final int dsId = 8243; |
| | | final String previous = System.getProperty(TRACE_TLS_FAILURES); |
| | | final ExecutorService peerThread = Executors.newSingleThreadExecutor(); |
| | | ReplicationBroker broker = null; |
| | | try (ServerSocket listener = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) |
| | | { |
| | | listener.setSoTimeout(SOCKET_TIMEOUT_MS); |
| | | final int port = listener.getLocalPort(); |
| | | final Future<List<Integer>> clients = peerThread.submit(() -> rejectTlsHandshakes(listener, 1)); |
| | | broker = new ReplicationBroker(new DummyReplicationDomain(EMPTY_DN_GENID), new ServerState(), |
| | | newFakeCfg(baseDN, dsId, port), getReplSessionSecurity()); |
| | | final ReplicationBroker caller = broker; |
| | | System.setProperty(TRACE_TLS_FAILURES, "true"); |
| | | final List<String> records = errorLogRecordsOf(() -> { |
| | | caller.start(); |
| | | assertThat(caller.isConnected()).isFalse(); |
| | | return null; |
| | | }); |
| | | |
| | | final int sourcePort = clients.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS).get(0); |
| | | final String diagnostic = "Replication TLS client handshake failed for DS(" + dsId |
| | | + ") for domain \"" + baseDN + "\" from "; |
| | | assertThat(countRecordsOf(records, diagnostic)).isEqualTo(1); |
| | | assertTlsAttempt(records, diagnostic, sourcePort, port); |
| | | } |
| | | finally |
| | | { |
| | | restoreTlsTracing(previous); |
| | | peerThread.shutdownNow(); |
| | | stop(broker); |
| | | } |
| | | } |
| | | |
| | | private List<Integer> rejectTlsHandshakes(ServerSocket listener, int attempts) throws Exception |
| | | { |
| | | final List<Integer> sourcePorts = new ArrayList<>(); |
| | | for (int i = 0; i < attempts; i++) |
| | | { |
| | | try (Socket socket = listener.accept()) |
| | | { |
| | | socket.setSoTimeout(SOCKET_TIMEOUT_MS); |
| | | sourcePorts.add(socket.getPort()); |
| | | final DataInputStream input = new DataInputStream(socket.getInputStream()); |
| | | assertThat(input.readUnsignedByte()).isEqualTo(22); // TLS handshake record |
| | | input.readUnsignedShort(); // TLS record version |
| | | input.readFully(new byte[input.readUnsignedShort()]); |
| | | // A fatal TLS alert with description bad_certificate. |
| | | socket.getOutputStream().write(new byte[] { 21, 3, 3, 0, 2, 2, 42 }); |
| | | } |
| | | } |
| | | return sourcePorts; |
| | | } |
| | | |
| | | private void assertTlsAttempt(List<String> records, String diagnostic, int sourcePort, int port) |
| | | { |
| | | // A dual-stack socket on macOS can render the IPv4 loopback source as IPv6-compatible. |
| | | assertThat(records).anySatisfy(record -> { |
| | | assertThat(record).contains("severity=NOTICE msgID=341 msg=" + diagnostic).endsWith("/127.0.0.1:" + port); |
| | | assertThat(record).containsAnyOf( |
| | | "/127.0.0.1:" + sourcePort + " to ", "/[0:0:0:0:0:0:7f00:1]:" + sourcePort + " to "); |
| | | }); |
| | | } |
| | | |
| | | private void restoreTlsTracing(String previous) |
| | | { |
| | | if (previous == null) |
| | | { |
| | | System.clearProperty(TRACE_TLS_FAILURES); |
| | | } |
| | | else |
| | | { |
| | | System.setProperty(TRACE_TLS_FAILURES, previous); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Tests that a replication server reports a peer it cannot connect to once, and reports |
| | |
| | | |
| | | import static org.assertj.core.api.Assertions.assertThat; |
| | | import static org.mockito.Mockito.*; |
| | | import static org.opends.server.replication.common.ServerStatus.NORMAL_STATUS; |
| | | import static org.opends.server.replication.common.StatusMachineEvent.TO_DEGRADED_STATUS_EVENT; |
| | | |
| | | import java.io.ByteArrayOutputStream; |
| | | import java.io.Closeable; |
| | |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicReference; |
| | | |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.mockito.invocation.InvocationOnMock; |
| | | import org.opends.server.loggers.ConsoleDebugLogPublisher; |
| | | import org.opends.server.loggers.DebugLogger; |
| | | import org.opends.server.loggers.TraceSettings; |
| | | import org.opends.server.replication.ReplicationTestCase; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.opends.server.replication.common.ServerState; |
| | | import org.opends.server.replication.protocol.DeleteMsg; |
| | | import org.opends.server.replication.protocol.MonitorMsg; |
| | | import org.opends.server.replication.protocol.ProtocolVersion; |
| | | import org.opends.server.replication.protocol.ReplSessionSecurity; |
| | |
| | | } |
| | | } |
| | | |
| | | @Test(dataProvider = "failedSends") |
| | | public void failedStatusChangeChecksLocalCloseAndHandlerShutdown(final boolean locallyClosed, |
| | | final boolean shuttingDown, final int expectedErrors) throws Exception |
| | | { |
| | | final Session[] pair = connectSessionPair(); |
| | | try |
| | | { |
| | | final Session session = pair[1]; |
| | | final DataServerHandler handler = mock(DataServerHandler.class); |
| | | final ReplicationServerDomain domain = mock(ReplicationServerDomain.class); |
| | | final ReplicationServer server = mock(ReplicationServer.class); |
| | | final AtomicReference<IOException> failure = new AtomicReference<>(); |
| | | final DN baseDN = DN.valueOf("dc=example,dc=com"); |
| | | |
| | | setField(ReplicationServerDomain.class, domain, "baseDN", baseDN); |
| | | setField(ReplicationServerDomain.class, domain, "localReplicationServer", server); |
| | | setField(ReplicationServerDomain.class, domain, "connectedDSs", Collections.singletonMap(9302, handler)); |
| | | setField(DataServerHandler.class, handler, "status", NORMAL_STATUS); |
| | | setField(MessageHandler.class, handler, "replicationServer", server); |
| | | setField(MessageHandler.class, handler, "replicationServerDomain", domain); |
| | | setField(ServerHandler.class, handler, "session", session); |
| | | final MsgQueue queue = new MsgQueue(); |
| | | queue.add(new DeleteMsg(baseDN, new CSN(1, 1, 9302), "status-test-entry")); |
| | | setField(MessageHandler.class, handler, "msgQueue", queue); |
| | | setField(MessageHandler.class, handler, "following", true); |
| | | when(server.getDegradedStatusThreshold()).thenReturn(1); |
| | | when(handler.getStatus()).thenReturn(NORMAL_STATUS); |
| | | when(handler.getServerId()).thenReturn(9302); |
| | | when(handler.shuttingDown()).thenReturn(shuttingDown); |
| | | doCallRealMethod().when(domain).checkDSDegradedStatus(); |
| | | |
| | | doAnswer(invocation -> { |
| | | // Begin closing after the analyzer has chosen this DS. |
| | | if (locallyClosed) |
| | | { |
| | | session.close(); |
| | | } |
| | | else |
| | | { |
| | | closeSocketsUnder(session); |
| | | } |
| | | try |
| | | { |
| | | return invocation.callRealMethod(); |
| | | } |
| | | catch (IOException e) |
| | | { |
| | | failure.set(e); |
| | | throw e; |
| | | } |
| | | }).when(handler).changeStatus(TO_DEGRADED_STATUS_EVENT); |
| | | |
| | | final List<String> logged = errorLogRecordsOf(() -> { |
| | | domain.checkDSDegradedStatus(); |
| | | return null; |
| | | }); |
| | | assertThat(failure.get()).as("status change reached the closed socket").isNotNull(); |
| | | assertThat(logged).filteredOn(record -> record.contains("category=SYNC severity=ERROR msgID=139 ")) |
| | | .hasSize(expectedErrors) |
| | | .allMatch(record -> record.contains("serverId: 9302")); |
| | | } |
| | | finally |
| | | { |
| | | StaticUtils.close(pair); |
| | | } |
| | | } |
| | | |
| | | private static void assertMonitorErrors(final List<String> logged, final int count) |
| | | { |
| | | // Keep duplicates: two identical reports in the same second must count as two errors. |
| | |
| | | package org.opends.server.replication.server; |
| | | |
| | | import static org.assertj.core.api.Assertions.assertThat; |
| | | import static org.assertj.core.api.Assertions.assertThatThrownBy; |
| | | import static org.opends.messages.ReplicationMessages.WARN_IGNORING_UPDATE_UNSUPPORTED_BY_PEER; |
| | | import static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING; |
| | | import static org.opends.server.util.CollectionUtils.newArrayList; |
| | | import static org.mockito.Mockito.*; |
| | | import static org.mockito.AdditionalAnswers.delegatesTo; |
| | | |
| | | import java.io.BufferedOutputStream; |
| | | import java.io.IOException; |
| | | import java.lang.reflect.Field; |
| | | import java.net.InetSocketAddress; |
| | | import java.net.ServerSocket; |
| | | import java.net.Socket; |
| | | import java.util.ArrayList; |
| | | import java.util.Arrays; |
| | | import java.util.Collection; |
| | | import java.util.Collections; |
| | | import java.util.List; |
| | | import java.util.TreeSet; |
| | | import java.util.concurrent.Callable; |
| | |
| | | import java.util.concurrent.TimeoutException; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicReference; |
| | | import java.util.concurrent.locks.ReentrantLock; |
| | | |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.forgerock.opendj.ldap.ModificationType; |
| | |
| | | import org.opends.server.core.DirectoryServer; |
| | | import org.opends.server.replication.ReplicationTestCase; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.opends.server.replication.common.DSInfo; |
| | | import org.opends.server.replication.common.AssuredMode; |
| | | import org.opends.server.replication.common.ServerStatus; |
| | | import org.opends.server.replication.common.CSNGenerator; |
| | | import org.opends.server.replication.common.RSInfo; |
| | | import org.opends.server.replication.common.ServerState; |
| | | import org.opends.server.replication.plugin.DummyReplicationDomain; |
| | | import org.opends.server.replication.protocol.DeleteMsg; |
| | | import org.opends.server.replication.protocol.ModifyMsg; |
| | | import org.opends.server.replication.protocol.ProtocolVersion; |
| | |
| | | import org.opends.server.replication.protocol.StopMsg; |
| | | import org.opends.server.replication.protocol.TopologyMsg; |
| | | import org.opends.server.replication.protocol.WindowMsg; |
| | | import org.opends.server.replication.protocol.UpdateMsg; |
| | | import org.opends.server.replication.server.changelog.api.ChangelogException; |
| | | import org.opends.server.replication.server.changelog.api.ReplicationDomainDB; |
| | | import org.opends.server.replication.service.DSRSShutdownSync; |
| | | import org.opends.server.replication.service.DSRSShutdownSync.ForwardingPeer; |
| | | import org.opends.server.replication.service.ReplicationBroker; |
| | | import org.opends.server.types.Attributes; |
| | | import org.opends.server.types.Modification; |
| | |
| | | * announce themselves offline again while the shutdown is waiting for them. */ |
| | | private static final long REANNOUNCE_INTERVAL = 200; |
| | | |
| | | /** A departing RS reader may already be waiting to apply its last topology message. */ |
| | | @Test |
| | | public void stoppingPeerDoesNotHoldDomainLockWhileJoiningReader() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer server = null; |
| | | FakePeerReplicationServer peer = null; |
| | | ReplicationBroker broker = null; |
| | | final ExecutorService stopping = Executors.newSingleThreadExecutor(); |
| | | final AtomicReference<Thread> stoppingThread = new AtomicReference<>(); |
| | | try |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | final ReplServerFakeConfiguration config = new ReplServerFakeConfiguration( |
| | | port, "shutdownDomainLockDb", 0, 8258, 0, 100, new TreeSet<String>()); |
| | | // This peer exercises topology messages, not the unrelated five-second |
| | | // wait for replies to monitor requests. |
| | | config.setMonitoringPeriod(0); |
| | | server = new ReplicationServer(config, new DSRSShutdownSync()); |
| | | peer = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | waitForConnectedReplicationServer(domain, REMOTE_RS_ID); |
| | | final ReplicationServerHandler handler = domain.getConnectedRSs().get(REMOTE_RS_ID); |
| | | final Field lockField = ReplicationServerDomain.class.getDeclaredField("lock"); |
| | | lockField.setAccessible(true); |
| | | final ReentrantLock domainLock = (ReentrantLock) lockField.get(domain); |
| | | final Field readerField = ServerHandler.class.getDeclaredField("reader"); |
| | | readerField.setAccessible(true); |
| | | final Thread reader = (Thread) readerField.get(handler); |
| | | final Future<?> stopped; |
| | | domain.lock(); |
| | | try |
| | | { |
| | | // Queue teardown first, then the real reader of a real peer session. Once |
| | | // released, teardown must let that reader finish before joining it. |
| | | stopped = stopping.submit(() -> { |
| | | stoppingThread.set(Thread.currentThread()); |
| | | domain.stopServer(handler, false); |
| | | }); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(stoppingThread.get()).isNotNull(); |
| | | assertThat(domainLock.hasQueuedThread(stoppingThread.get())).isTrue(); |
| | | }); |
| | | peer.session.publish(new TopologyMsg(null, |
| | | newArrayList(new RSInfo(REMOTE_RS_ID, peer.serverURL, EMPTY_DN_GENID, (byte) 1, 1)))); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(domainLock.hasQueuedThread(reader)).as("peer reader waiting for domain lock").isTrue(); |
| | | }); |
| | | } |
| | | finally |
| | | { |
| | | domain.release(); |
| | | } |
| | | stopped.get(2000, TimeUnit.MILLISECONDS); |
| | | assertThat(reader.isAlive()).as("departing peer reader has stopped").isFalse(); |
| | | broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID); |
| | | waitForConnectedDirectoryServer(domain); |
| | | } |
| | | finally |
| | | { |
| | | // Interrupt a failing teardown test before cleanup: it may be in the old |
| | | // 30-second join while its reader waits for the lock it still owns. |
| | | stopping.shutdownNow(); |
| | | stopping.awaitTermination(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | if (broker != null) |
| | | { |
| | | broker.stop(); |
| | | } |
| | | closeQuietly(peer); |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | /** Both directory and replication sessions can spend time draining accepted messages. */ |
| | | @DataProvider |
| | | public Object[][] closingHandlerRoles() |
| | | { |
| | | return new Object[][] { { false }, { true } }; |
| | | } |
| | | |
| | | /** A slow close must not prevent another DS from completing a real failover handshake. */ |
| | | @Test(dataProvider = "closingHandlerRoles") |
| | | public void stoppingHandlerDoesNotHoldDomainLockWhileClosingSession(boolean replicationPeer) |
| | | throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final CountDownLatch closing = new CountDownLatch(1); |
| | | final CountDownLatch releaseClose = new CountDownLatch(1); |
| | | final ExecutorService stopping = Executors.newFixedThreadPool(2); |
| | | ReplicationServer server = null; |
| | | ReplicationBroker keeper = null; |
| | | ReplicationBroker reconnecting = null; |
| | | Future<?> stopped = null; |
| | | try (ServerSocket listen = TestCaseUtils.bindFreePort()) |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | final ReplServerFakeConfiguration config = new ReplServerFakeConfiguration( |
| | | port, "closingHandlerHandshakeDb" + replicationPeer, 0, 8269, 0, 100, new TreeSet<String>()); |
| | | config.setMonitoringPeriod(0); |
| | | server = new ReplicationServer(config, new DSRSShutdownSync()); |
| | | keeper = openReplicationSession(baseDN, LOCAL_DS_ID, 100, port, 5000, EMPTY_DN_GENID); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | final Session[] pair = connectSessionPair(listen, getReplSessionSecurity()); |
| | | try (Session remote = pair[0]; Session local = pair[1]) |
| | | { |
| | | final ServerHandler old; |
| | | if (replicationPeer) |
| | | { |
| | | old = registerConnectedReplicationServer(server, baseDN, local); |
| | | } |
| | | else |
| | | { |
| | | final DataServerHandler ds = new DataServerHandler(local, 100, server, 100); |
| | | ds.serverId = UNREACHABLE_DS_ID; |
| | | ds.serverURL = "127.0.0.1:1636"; |
| | | ds.setBaseDNAndDomain(baseDN, true); |
| | | ds.setInitialServerState(new ServerState()); |
| | | ds.setGenerationId(EMPTY_DN_GENID); |
| | | domain.lock(); |
| | | try |
| | | { |
| | | domain.register(ds); |
| | | } |
| | | finally |
| | | { |
| | | domain.release(); |
| | | } |
| | | old = ds; |
| | | } |
| | | DirectoryServer.registerMonitorProvider(old); |
| | | // Delay only the socket write during close. The real Session still drains |
| | | // and sends StopMsg; the new broker performs its real network handshake. |
| | | final Field outputField = Session.class.getDeclaredField("output"); |
| | | outputField.setAccessible(true); |
| | | final BufferedOutputStream output = (BufferedOutputStream) outputField.get(local); |
| | | outputField.set(local, new BufferedOutputStream(output) { |
| | | @Override |
| | | public synchronized void flush() throws IOException |
| | | { |
| | | if (local.closeInitiated()) |
| | | { |
| | | closing.countDown(); |
| | | try |
| | | { |
| | | if (!releaseClose.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)) |
| | | { |
| | | throw new IOException("Test did not release the session close"); |
| | | } |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | Thread.currentThread().interrupt(); |
| | | throw new IOException(e); |
| | | } |
| | | } |
| | | super.flush(); |
| | | } |
| | | }); |
| | | stopped = stopping.submit(() -> domain.stopServer(old, false)); |
| | | assertThat(closing.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue(); |
| | | assertThat(stopped.isDone()).as("the old session is still draining").isFalse(); |
| | | reconnecting = new ReplicationBroker(new DummyReplicationDomain(EMPTY_DN_GENID), |
| | | new ServerState(), newFakeCfg(baseDN, REMOTE_DS_ID, port), getReplSessionSecurity()); |
| | | final ReplicationBroker newBroker = reconnecting; |
| | | stopping.submit(() -> newBroker.start()).get(10, TimeUnit.SECONDS); |
| | | assertThat(reconnecting.isConnected()) |
| | | .as("a live RS must accept failover while another peer's session is closing").isTrue(); |
| | | assertThat(stopped.isDone()).as("the new handshake did not wait for the old close").isFalse(); |
| | | assertThat(DirectoryServer.getMonitorProviders()).doesNotContainValue(old); |
| | | releaseClose.countDown(); |
| | | stopped.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | assertThat(domain.getConnectedDSs()).containsKey(REMOTE_DS_ID); |
| | | } |
| | | finally |
| | | { |
| | | releaseClose.countDown(); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | releaseClose.countDown(); |
| | | awaitQuietly(stopped); |
| | | if (reconnecting != null) |
| | | { |
| | | reconnecting.stop(); |
| | | } |
| | | if (keeper != null) |
| | | { |
| | | keeper.stop(); |
| | | } |
| | | removeQuietly(server); |
| | | stopping.shutdownNow(); |
| | | stopping.awaitTermination(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | } |
| | | } |
| | | |
| | | /** A replacement can connect while the old reader finishes, but must keep its monitors. */ |
| | | @Test |
| | | public void stoppingPeerKeepsReplacementMonitors() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final CountDownLatch releaseReader = new CountDownLatch(1); |
| | | final ExecutorService stopping = Executors.newSingleThreadExecutor(); |
| | | ReplicationServer server = null; |
| | | Thread reader = null; |
| | | try (ServerSocket listen = new ServerSocket(0)) |
| | | { |
| | | final ReplServerFakeConfiguration config = new ReplServerFakeConfiguration( |
| | | TestCaseUtils.findFreePort(), "replacementMonitorsDb", 0, 8260, 0, 100, new TreeSet<String>()); |
| | | config.setMonitoringPeriod(0); |
| | | server = new ReplicationServer(config, new DSRSShutdownSync()); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | final Session[] oldPair = connectSessionPair(listen, getReplSessionSecurity()); |
| | | final Session[] newPair = connectSessionPair(listen, getReplSessionSecurity()); |
| | | try (Session oldRemote = oldPair[0]; Session oldLocal = oldPair[1]; |
| | | Session newRemote = newPair[0]; Session newLocal = newPair[1]) |
| | | { |
| | | final ReplicationServerHandler old = registerConnectedReplicationServer(server, baseDN, oldLocal); |
| | | DirectoryServer.registerMonitorProvider(old); |
| | | final DSInfo replica = new DSInfo(REMOTE_DS_ID, "localhost:1389", REMOTE_RS_ID, EMPTY_DN_GENID, |
| | | ServerStatus.NORMAL_STATUS, false, AssuredMode.SAFE_READ_MODE, (byte) 1, (byte) 1, |
| | | Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(), |
| | | ProtocolVersion.getCurrentVersion()); |
| | | final TopologyMsg topology = new TopologyMsg(newArrayList(replica), |
| | | newArrayList(new RSInfo(REMOTE_RS_ID, old.serverURL, EMPTY_DN_GENID, (byte) 1, 1))); |
| | | domain.receiveTopoInfoFromRS(topology, old, false); |
| | | final String replicaMonitorName = StaticUtils.toLowerCase("Connected directory server DS(" |
| | | + REMOTE_DS_ID + ") localhost:1389,cn=" + old.getMonitorInstanceName()); |
| | | final Object oldReplicaMonitor = DirectoryServer.getMonitorProviders().get(replicaMonitorName); |
| | | assertThat(oldReplicaMonitor).isInstanceOf(LightweightServerHandler.class); |
| | | |
| | | // Model a reader finishing accepted work after its session has closed. |
| | | // Its join must allow the replacement handshake, but cleanup by monitor |
| | | // name must finish before that replacement can register its providers. |
| | | reader = new ServerReader(oldLocal, old) { |
| | | @Override |
| | | public void run() |
| | | { |
| | | try |
| | | { |
| | | releaseReader.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | Thread.currentThread().interrupt(); |
| | | } |
| | | } |
| | | }; |
| | | final Field readerField = ServerHandler.class.getDeclaredField("reader"); |
| | | readerField.setAccessible(true); |
| | | readerField.set(old, reader); |
| | | reader.start(); |
| | | final Future<?> stopped = stopping.submit(() -> domain.stopServer(old, false)); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(domain.getConnectedRSs()).doesNotContainKey(REMOTE_RS_ID); |
| | | assertThat(DirectoryServer.getMonitorProviders()).doesNotContainValue(old); |
| | | }); |
| | | |
| | | final ReplicationServerHandler replacement = |
| | | registerConnectedReplicationServer(server, baseDN, newLocal); |
| | | DirectoryServer.registerMonitorProvider(replacement); |
| | | domain.receiveTopoInfoFromRS(topology, replacement, false); |
| | | final Object replacementReplicaMonitor = DirectoryServer.getMonitorProviders().get(replicaMonitorName); |
| | | assertThat(replacementReplicaMonitor).isInstanceOf(LightweightServerHandler.class) |
| | | .isNotSameAs(oldReplicaMonitor); |
| | | releaseReader.countDown(); |
| | | stopped.get(WRITER_REACTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | assertThat(DirectoryServer.getMonitorProviders()).containsValue(replacement); |
| | | assertThat(DirectoryServer.getMonitorProviders().get(replicaMonitorName)) |
| | | .as("old teardown must not remove the replacement's replica monitor") |
| | | .isSameAs(replacementReplicaMonitor); |
| | | } |
| | | finally |
| | | { |
| | | releaseReader.countDown(); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | releaseReader.countDown(); |
| | | stopping.shutdownNow(); |
| | | stopping.awaitTermination(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | if (reader != null) |
| | | { |
| | | reader.join(SOCKET_TIMEOUT_MS); |
| | | } |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] disconnectedPeerReplacements() |
| | | { |
| | | return new Object[][] { { false }, { true } }; |
| | | } |
| | | |
| | | /** A late topology message of a removed session must not resurrect its generation. */ |
| | | @Test(dataProvider = "disconnectedPeerReplacements") |
| | | public void disconnectedPeerCannotChangeGeneration(boolean replacementConnected) throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer server = null; |
| | | ReplicationServerHandler old = null; |
| | | try (ServerSocket listen = TestCaseUtils.bindFreePort()) |
| | | { |
| | | server = newReplicationServer(new DSRSShutdownSync(), "disconnectedPeerGenerationDb", 8259); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | final Session[] oldPair = connectSessionPair(listen, getReplSessionSecurity()); |
| | | final Session[] newPair = connectSessionPair(listen, getReplSessionSecurity()); |
| | | try (Session oldRemote = oldPair[0]; Session oldLocal = oldPair[1]; |
| | | Session newRemote = newPair[0]; Session newLocal = newPair[1]) |
| | | { |
| | | old = registerConnectedReplicationServer(server, baseDN, oldLocal); |
| | | domain.stopServer(old, false); |
| | | if (replacementConnected) |
| | | { |
| | | registerConnectedReplicationServer(server, baseDN, newLocal); |
| | | } |
| | | final DSInfo replica = new DSInfo(REMOTE_DS_ID, "localhost:1389", REMOTE_RS_ID, 123456, |
| | | ServerStatus.NORMAL_STATUS, false, AssuredMode.SAFE_READ_MODE, (byte) 1, (byte) 1, |
| | | Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(), |
| | | ProtocolVersion.getCurrentVersion()); |
| | | domain.receiveTopoInfoFromRS(new TopologyMsg(newArrayList(replica), |
| | | newArrayList(new RSInfo(REMOTE_RS_ID, "localhost:1636", 123456, (byte) 1, 1))), old, true); |
| | | assertThat(domain.getGenerationId()).as("removed peer cannot supply a generation id").isEqualTo(-1); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | if (old != null) |
| | | { |
| | | old.shutdown(); // Also clears remote-replica monitors created by a failing implementation. |
| | | } |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void stoppingPeerCannotCancelOfflineForwardForItsReplacement() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final RecordingShutdownSync shutdownSync = new RecordingShutdownSync(); |
| | | final CountDownLatch releaseOld = new CountDownLatch(1); |
| | | final CountDownLatch oldIsClosing = new CountDownLatch(1); |
| | | final ExecutorService stopping = Executors.newSingleThreadExecutor(); |
| | | ReplicationServer server = null; |
| | | ReplicationBroker broker = null; |
| | | FakePeerReplicationServer replacement = null; |
| | | try (ServerSocket listen = TestCaseUtils.bindFreePort()) |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | server = newReplicationServer(shutdownSync, "offlineForwardReplacementDb", 8261, port); |
| | | broker = openReplicationSession(baseDN, LOCAL_DS_ID, 100, port, 5000, EMPTY_DN_GENID); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | final Session[] oldPair = connectSessionPair(listen, getReplSessionSecurity()); |
| | | try (Session oldRemote = oldPair[0]; Session oldLocal = oldPair[1]) |
| | | { |
| | | final ReplicationServerHandler old = new ReplicationServerHandler(oldLocal, 100, server, 100) |
| | | { |
| | | @Override |
| | | void awaitShutdown() |
| | | { |
| | | oldIsClosing.countDown(); |
| | | try |
| | | { |
| | | assertThat(releaseOld.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue(); |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | Thread.currentThread().interrupt(); |
| | | } |
| | | super.awaitShutdown(); |
| | | } |
| | | }; |
| | | registerConnectedReplicationServer(domain, baseDN, old, REMOTE_RS_ID); |
| | | final Future<?> stopped = stopping.submit(() -> domain.stopServer(old, false)); |
| | | try |
| | | { |
| | | assertThat(oldIsClosing.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue(); |
| | | replacement = FakePeerReplicationServer.connected( |
| | | port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID, HELD_BACK_PEER_WINDOW); |
| | | waitForConnectedReplicationServer(domain, REMOTE_RS_ID); |
| | | |
| | | final CSNGenerator csns = new CSNGenerator(LOCAL_DS_ID, 0); |
| | | final Future<DeleteMsg> windowFiller = replacement.receive(DeleteMsg.class); |
| | | broker.publish(new DeleteMsg(DN.valueOf("uid=offline," + baseDN), |
| | | csns.newCSN(), "offline-entry-uuid")); |
| | | assertThat(windowFiller.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isNotNull(); |
| | | |
| | | final CSN offlineCSN = csns.newCSN(); |
| | | shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN); |
| | | broker.publish(new ReplicaOfflineMsg(offlineCSN)); |
| | | shutdownSync.awaitDispatch(); |
| | | assertThat(shutdownSync.dispatchedTo()).containsExactly(REMOTE_RS_ID); |
| | | assertThat(shutdownSync.canShutdown(baseDN)).isFalse(); |
| | | |
| | | releaseOld.countDown(); |
| | | stopped.get(WRITER_REACTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | assertThat(shutdownSync.canShutdown(baseDN)) |
| | | .as("the old session cannot cancel the new session's forward").isFalse(); |
| | | |
| | | final Future<ReplicaOfflineMsg> received = replacement.receive(ReplicaOfflineMsg.class); |
| | | replacement.openSendWindow(1); |
| | | final ReplicaOfflineMsg forwarded = received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | assertThat(forwarded).isNotNull(); |
| | | assertThat(forwarded.getCSN()).isEqualTo(offlineCSN); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(shutdownSync.forwardedBy()).contains(REMOTE_RS_ID); |
| | | assertThat(shutdownSync.canShutdown(baseDN)).isTrue(); |
| | | }); |
| | | } |
| | | finally |
| | | { |
| | | releaseOld.countDown(); |
| | | } |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | closeQuietly(replacement); |
| | | stop(broker); |
| | | stopping.shutdownNow(); |
| | | stopping.awaitTermination(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | /** A remote DS can still write when its RS starts shutting down: no offline message |
| | | * announces those last changes. Every peer must receive them before its session closes. */ |
| | | @Test |
| | | public void shutdownForwardsRemoteDirectoryUpdatesToEveryPeer() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer server = null; |
| | | ReplicationBroker broker = null; |
| | | FakePeerReplicationServer fast = null; |
| | | FakePeerReplicationServer slow = null; |
| | | final ExecutorService shutdown = Executors.newSingleThreadExecutor(); |
| | | try |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | server = newReplicationServer(new DSRSShutdownSync(), "shutdownRemoteUpdatesDb", 8250, port); |
| | | broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID); |
| | | fast = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID); |
| | | slow = FakePeerReplicationServer.connected(port, HELD_BACK_RS_ID, baseDN, EMPTY_DN_GENID, 1); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | waitForConnectedReplicationServer(domain, REMOTE_RS_ID); |
| | | waitForConnectedReplicationServer(domain, HELD_BACK_RS_ID); |
| | | final Future<List<ReplicationMsg>> fastMessages = fast.receiveUntil(StopMsg.class); |
| | | final Future<List<ReplicationMsg>> slowMessages = slow.receiveUntil(StopMsg.class); |
| | | final List<CSN> expected = new ArrayList<>(); |
| | | final long time = System.currentTimeMillis(); |
| | | for (int i = 1; i <= 4; i++) |
| | | { |
| | | final CSN csn = new CSN(time, i, REMOTE_DS_ID); |
| | | expected.add(csn); |
| | | broker.publish(new DeleteMsg(DN.valueOf("uid=last-" + i + "," + baseDN), csn, |
| | | "22222222-2222-2222-2222-222222222222")); |
| | | } |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(3)); |
| | | }); |
| | | final ReplicationServer stopping = server; |
| | | final Future<?> stopped = shutdown.submit(() -> stopping.shutdown()); |
| | | // Keep the slow peer's window closed until all DS readers have been stopped. |
| | | newConnectionTimer().repeatUntilSuccess(() -> { assertThat(domain.getConnectedDSs()).isEmpty(); }); |
| | | slow.openSendWindow(10); |
| | | stopped.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | for (Future<List<ReplicationMsg>> messages : Arrays.asList(fastMessages, slowMessages)) |
| | | { |
| | | final List<CSN> actual = new ArrayList<>(); |
| | | for (ReplicationMsg msg : messages.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)) |
| | | { |
| | | if (msg instanceof DeleteMsg) |
| | | { |
| | | actual.add(((DeleteMsg) msg).getCSN()); |
| | | } |
| | | } |
| | | assertThat(actual).as("updates received by a peer before the RS stopped").containsExactlyElementsOf(expected); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | closeQuietly(fast); |
| | | closeQuietly(slow); |
| | | if (broker != null) |
| | | { |
| | | broker.stop(); |
| | | } |
| | | removeQuietly(server); |
| | | shutdown.shutdownNow(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * A DS can move to the peer while older changes still wait for send-window credit. |
| | | * The newer change coming back from that peer proves nothing about those older |
| | | * records: advancing the outgoing cursor would skip them and strand shutdown. |
| | | */ |
| | | @DataProvider |
| | | public Object[][] migrationHistorySources() |
| | | { |
| | | return new Object[][] { { false }, { true } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "migrationHistorySources") |
| | | public void incomingPeerUpdateDoesNotSkipDirectoryHistory(boolean retainedHistory) throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer server = null; |
| | | ReplicationBroker broker = null; |
| | | FakePeerReplicationServer peer = null; |
| | | try |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | server = newReplicationServer(new DSRSShutdownSync(), "shutdownMigratedUpdatesDb", 8253, port); |
| | | broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID); |
| | | final List<CSN> expected = new ArrayList<>(); |
| | | final long time = System.currentTimeMillis(); |
| | | for (int i = 1; i <= 3; i++) |
| | | { |
| | | final CSN csn = new CSN(time, i, REMOTE_DS_ID); |
| | | expected.add(csn); |
| | | } |
| | | if (retainedHistory) |
| | | { |
| | | publishBeforeMigration(broker, baseDN, expected); |
| | | } |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | if (retainedHistory) |
| | | { |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(2)); |
| | | }); |
| | | } |
| | | peer = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID, 1); |
| | | waitForConnectedReplicationServer(domain, REMOTE_RS_ID); |
| | | if (!retainedHistory) |
| | | { |
| | | waitForFollowing(domain, REMOTE_RS_ID); |
| | | publishBeforeMigration(broker, baseDN, expected); |
| | | } |
| | | final ReplicationServerHandler handler = domain.getConnectedRSs().get(REMOTE_RS_ID); |
| | | final Future<List<ReplicationMsg>> received = peer.receiveUntil(StopMsg.class); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(2)); |
| | | assertThat(handler.getServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(1)); |
| | | }); |
| | | // Change 2 is dequeued but blocked; change 3 is still in the outgoing queue. |
| | | final CSN migrated = new CSN(time, 4, REMOTE_DS_ID); |
| | | peer.session.publish(new DeleteMsg(DN.valueOf("uid=after-migration," + baseDN), migrated, |
| | | "22222222-2222-2222-2222-222222222222")); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(migrated); |
| | | assertThat(handler.getServerState().getCSN(REMOTE_DS_ID)).isEqualTo(migrated); |
| | | }); |
| | | final ServerState outstanding = new ServerState(); |
| | | outstanding.update(expected.get(2)); |
| | | assertThat(handler.awaitPublished(outstanding, System.nanoTime())) |
| | | .as("a newer incoming CSN does not confirm delivery of an older outgoing record") |
| | | .isFalse(); |
| | | peer.openSendWindow(10); |
| | | final List<String> records = errorLogRecordsOf(() -> { |
| | | domain.awaitDirectUpdatesForwarded(System.nanoTime() + TimeUnit.SECONDS.toNanos(2)); |
| | | return null; |
| | | }); |
| | | assertThat(records.stream().anyMatch(line -> line.contains("RS shutdown could not forward"))) |
| | | .as("the incoming update must not strand the earlier direct updates") |
| | | .isFalse(); |
| | | server.shutdown(); |
| | | final List<CSN> actual = new ArrayList<>(); |
| | | for (ReplicationMsg msg : received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)) |
| | | { |
| | | if (msg instanceof DeleteMsg) |
| | | { |
| | | actual.add(((DeleteMsg) msg).getCSN()); |
| | | } |
| | | } |
| | | // Crediting the incoming maximum to publishedState would hide the warning, |
| | | // but still lose change 3. Verify the actual stream, not just the drain result. |
| | | assertThat(actual).containsExactlyElementsOf(expected); |
| | | } |
| | | finally |
| | | { |
| | | closeQuietly(peer); |
| | | if (broker != null) |
| | | { |
| | | broker.stop(); |
| | | } |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] directWriteOrigins() |
| | | { |
| | | return new Object[][] { { true, false }, { false, false }, { true, true } }; |
| | | } |
| | | |
| | | /** A new direct write must not overtake history of its replica received through another RS. */ |
| | | @Test(dataProvider = "directWriteOrigins") |
| | | public void directWriteAfterPeerHistoryPreservesTheOutgoingPrefix(boolean sameOrigin, boolean newerPeerUpdate) throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer server = null; |
| | | ReplicationBroker broker = null; |
| | | FakePeerReplicationServer source = null; |
| | | FakePeerReplicationServer target = null; |
| | | try |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | server = newReplicationServer(new DSRSShutdownSync(), "peerHistoryPrefixDb", 8254, port); |
| | | broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID); |
| | | source = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID); |
| | | target = FakePeerReplicationServer.connected(port, HELD_BACK_RS_ID, baseDN, EMPTY_DN_GENID); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | waitForConnectedReplicationServer(domain, REMOTE_RS_ID); |
| | | waitForConnectedReplicationServer(domain, HELD_BACK_RS_ID); |
| | | final Future<List<ReplicationMsg>> received = target.receiveUntil(StopMsg.class); |
| | | source.receiveUntil(StopMsg.class); |
| | | final List<CSN> expected = new ArrayList<>(); |
| | | final long time = System.currentTimeMillis(); |
| | | for (int i = 1; i <= 4; i++) |
| | | { |
| | | expected.add(new CSN(time, i, i == 4 && !sameOrigin ? REMOTE_DS_ID + 1 : REMOTE_DS_ID)); |
| | | } |
| | | publishBeforeMigration(broker, baseDN, expected.subList(0, 1)); |
| | | final ReplicationServerHandler targetHandler = domain.getConnectedRSs().get(HELD_BACK_RS_ID); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(targetHandler.getServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(0)); |
| | | }); |
| | | waitForFollowing(domain, HELD_BACK_RS_ID); |
| | | for (CSN csn : expected.subList(1, 3)) |
| | | { |
| | | source.session.publish(new DeleteMsg(DN.valueOf("uid=via-peer-" + csn + "," + baseDN), csn, |
| | | "22222222-2222-2222-2222-222222222222")); |
| | | } |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(2)); |
| | | }); |
| | | if (newerPeerUpdate) |
| | | { |
| | | // Hold the outgoing queue while both publications complete: peer 5 must |
| | | // not hide the unqueued prefix 2,3 when direct 4 is selected next. |
| | | final Field queueField = MessageHandler.class.getDeclaredField("msgQueue"); |
| | | queueField.setAccessible(true); |
| | | synchronized (queueField.get(targetHandler)) |
| | | { |
| | | domain.put(new DeleteMsg(DN.valueOf("uid=direct-four," + baseDN), expected.get(3), |
| | | "22222222-2222-2222-2222-222222222222"), domain.getConnectedDSs().get(REMOTE_DS_ID)); |
| | | expected.add(new CSN(time, 5, REMOTE_DS_ID)); |
| | | domain.put(new DeleteMsg(DN.valueOf("uid=peer-five," + baseDN), expected.get(4), |
| | | "22222222-2222-2222-2222-222222222222"), domain.getConnectedRSs().get(REMOTE_RS_ID)); |
| | | } |
| | | } |
| | | else |
| | | { |
| | | publishBeforeMigration(broker, baseDN, expected.subList(3, 4)); |
| | | } |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(targetHandler.getServerState().cover(expected.get(3))).isTrue(); |
| | | }); |
| | | final ServerState delivered = new ServerState(); |
| | | delivered.update(expected.get(expected.size() - 1)); |
| | | assertThat(targetHandler.awaitPublished(delivered, System.nanoTime() + TimeUnit.SECONDS.toNanos(5))) |
| | | .as("the last peer update is written before shutdown, which only drains direct updates").isTrue(); |
| | | server.shutdown(); |
| | | final List<CSN> actual = new ArrayList<>(); |
| | | for (ReplicationMsg msg : received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)) |
| | | { |
| | | if (msg instanceof DeleteMsg) |
| | | { |
| | | actual.add(((DeleteMsg) msg).getCSN()); |
| | | } |
| | | } |
| | | assertThat(actual).as("only a direct write from the same origin needs the peer history") |
| | | .containsExactlyElementsOf(sameOrigin ? expected : Arrays.asList(expected.get(0), expected.get(3))); |
| | | } |
| | | finally |
| | | { |
| | | closeQuietly(source); |
| | | closeQuietly(target); |
| | | if (broker != null) |
| | | { |
| | | broker.stop(); |
| | | } |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | /** Registration between the peer watermark and persistence must not lose that prefix. */ |
| | | @Test |
| | | public void newlyConnectedPeerSeesHistoryPublishedDuringItsRegistration() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final CountDownLatch beforePersistence = new CountDownLatch(1); |
| | | final CountDownLatch releasePut = new CountDownLatch(1); |
| | | ReplicationServer server = null; |
| | | ReplicationBroker broker = null; |
| | | FakePeerReplicationServer source = null; |
| | | FakePeerReplicationServer target = null; |
| | | try |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | server = newReplicationServer(new DSRSShutdownSync(), "peerRegistrationPrefixDb", 8255, port); |
| | | broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID); |
| | | source = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | waitForConnectedReplicationServer(domain, REMOTE_RS_ID); |
| | | source.receiveUntil(StopMsg.class); |
| | | final Field dbField = ReplicationServerDomain.class.getDeclaredField("domainDB"); |
| | | dbField.setAccessible(true); |
| | | final ReplicationDomainDB database = (ReplicationDomainDB) dbField.get(domain); |
| | | final ReplicationDomainDB delayed = mock(ReplicationDomainDB.class, delegatesTo(database)); |
| | | doAnswer(invocation -> { |
| | | beforePersistence.countDown(); |
| | | assertThat(releasePut.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue(); |
| | | return database.publishUpdateMsg(baseDN, (UpdateMsg) invocation.getArguments()[1]); |
| | | }).when(delayed).publishUpdateMsg(eq(baseDN), any(UpdateMsg.class)); |
| | | dbField.set(domain, delayed); |
| | | final CSN first = new CSN(System.currentTimeMillis(), 1, REMOTE_DS_ID); |
| | | final CSN last = new CSN(first.getTime(), 2, REMOTE_DS_ID); |
| | | source.session.publish(new DeleteMsg(DN.valueOf("uid=peer-history," + baseDN), first, |
| | | "22222222-2222-2222-2222-222222222222")); |
| | | assertThat(beforePersistence.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue(); |
| | | target = FakePeerReplicationServer.connected(port, HELD_BACK_RS_ID, baseDN, EMPTY_DN_GENID); |
| | | waitForConnectedReplicationServer(domain, HELD_BACK_RS_ID); |
| | | waitForFollowing(domain, HELD_BACK_RS_ID); |
| | | final Future<List<ReplicationMsg>> received = target.receiveUntil(StopMsg.class); |
| | | releasePut.countDown(); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(domain.getLatestServerState().cover(first)).isTrue(); |
| | | }); |
| | | publishBeforeMigration(broker, baseDN, Arrays.asList(last)); |
| | | final ReplicationServerHandler handler = domain.getConnectedRSs().get(HELD_BACK_RS_ID); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(handler.getServerState().cover(last)).isTrue(); |
| | | }); |
| | | server.shutdown(); |
| | | final List<CSN> actual = new ArrayList<>(); |
| | | for (ReplicationMsg msg : received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)) |
| | | { |
| | | if (msg instanceof DeleteMsg) |
| | | { |
| | | actual.add(((DeleteMsg) msg).getCSN()); |
| | | } |
| | | } |
| | | assertThat(actual).containsExactly(first, last); |
| | | } |
| | | finally |
| | | { |
| | | releasePut.countDown(); |
| | | closeQuietly(source); |
| | | closeQuietly(target); |
| | | if (broker != null) |
| | | { |
| | | broker.stop(); |
| | | } |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | /** A future CSN from an old generation must not force replay of every new direct write. */ |
| | | @Test |
| | | public void generationResetForgetsUnqueuedPeerHistory() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final ExecutorService consumer = Executors.newSingleThreadExecutor(); |
| | | ReplicationServer server = null; |
| | | ReplicationServerHandler handler = null; |
| | | try |
| | | { |
| | | server = newReplicationServer(new DSRSShutdownSync(), "peerHistoryGenerationDb", 8256); |
| | | handler = new ReplicationServerHandler(null, 100, server, 100); |
| | | handler.setBaseDNAndDomain(baseDN, false); |
| | | handler.setInitialServerState(new ServerState()); |
| | | handler.setGenerationId(1); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, false); |
| | | domain.initGenerationID(1); |
| | | final ReplicationServerHandler source = new ReplicationServerHandler(null, 100, server, 100); |
| | | source.setBaseDNAndDomain(baseDN, false); |
| | | source.setInitialServerState(new ServerState()); |
| | | source.setGenerationId(1); |
| | | final long time = System.currentTimeMillis(); |
| | | final DeleteMsg first = new DeleteMsg(baseDN, new CSN(time, 1, REMOTE_DS_ID), |
| | | "22222222-2222-2222-2222-222222222222"); |
| | | final ReplicationDomainDB database = server.getChangelogDB().getReplicationDomainDB(); |
| | | database.publishUpdateMsg(baseDN, first); |
| | | handler.add(first); |
| | | assertThat(handler.getNextMessage().getCSN()).isEqualTo(first.getCSN()); |
| | | final ReplicationServerHandler target = handler; |
| | | final DeleteMsg current = new DeleteMsg(baseDN, new CSN(time + 1, 2, REMOTE_DS_ID), |
| | | "22222222-2222-2222-2222-222222222222"); |
| | | final Future<Boolean> fromChangelog = consumer.submit(() -> { |
| | | assertThat(target.getNextMessage().getCSN()).isEqualTo(current.getCSN()); |
| | | return target.isLastMessageFromLateQueue(); |
| | | }); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { assertThat(target.isFollowing()).isTrue(); }); |
| | | domain.put(new DeleteMsg(baseDN, new CSN(time + 60000, 1, REMOTE_DS_ID), |
| | | "22222222-2222-2222-2222-222222222222"), source); |
| | | domain.changeGenerationId(2); |
| | | handler.setGenerationId(2); |
| | | database.publishUpdateMsg(baseDN, current); |
| | | handler.add(current); |
| | | assertThat(fromChangelog.get(5, TimeUnit.SECONDS)) |
| | | .as("a new-generation direct write needs no replay of discarded old-generation history").isFalse(); |
| | | } |
| | | finally |
| | | { |
| | | if (handler != null) |
| | | { |
| | | handler.setConsumerActive(false); |
| | | } |
| | | consumer.shutdownNow(); |
| | | assertThat(consumer.awaitTermination(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue(); |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | private void publishBeforeMigration(ReplicationBroker broker, DN baseDN, List<CSN> csns) |
| | | throws Exception |
| | | { |
| | | for (CSN csn : csns) |
| | | { |
| | | broker.publish(new DeleteMsg(DN.valueOf("uid=before-migration-" + csn + "," + baseDN), csn, |
| | | "22222222-2222-2222-2222-222222222222")); |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void catchUpSkipsOnlyExactPeerReceiptsAndWaitsForOlderWrites() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer server = null; |
| | | try |
| | | { |
| | | server = newReplicationServer(new DSRSShutdownSync(), "shutdownPeerReceiptsDb", 8254); |
| | | final ReplicationServerHandler handler = new ReplicationServerHandler(null, 100, server, 100); |
| | | handler.setBaseDNAndDomain(baseDN, false); |
| | | handler.setInitialServerState(new ServerState()); |
| | | final List<DeleteMsg> updates = new ArrayList<>(); |
| | | for (int i = 1; i <= 5; i++) |
| | | { |
| | | final DeleteMsg update = new DeleteMsg(baseDN, |
| | | new CSN(System.currentTimeMillis(), i, REMOTE_DS_ID), |
| | | "22222222-2222-2222-2222-222222222222"); |
| | | updates.add(update); |
| | | if (i == 2 || i == 4) |
| | | { |
| | | handler.recordReceivedUpdate(update); |
| | | } |
| | | server.getChangelogDB().getReplicationDomainDB().publishUpdateMsg(baseDN, update); |
| | | } |
| | | assertThat(handler.getNextMessage().getCSN()).isEqualTo(updates.get(0).getCSN()); |
| | | assertThat(handler.getNextMessage().getCSN()).isEqualTo(updates.get(2).getCSN()); |
| | | assertThat(handler.getNextMessage().getCSN()).isEqualTo(updates.get(4).getCSN()); |
| | | final ServerState target = new ServerState(); |
| | | target.update(updates.get(3).getCSN()); |
| | | handler.updatePublishedState(updates.get(0).getCSN()); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())) |
| | | .as("the received change 4 cannot confirm the unwritten change 3").isFalse(); |
| | | handler.updatePublishedState(updates.get(2).getCSN()); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())) |
| | | .as("change 4 is already held by the peer once its older writes complete").isTrue(); |
| | | target.update(updates.get(4).getCSN()); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())) |
| | | .as("the selected change 5 is not written yet").isFalse(); |
| | | handler.updatePublishedState(updates.get(4).getCSN()); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())).isTrue(); |
| | | } |
| | | finally |
| | | { |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] peerGenerationChanges() |
| | | { |
| | | return new Object[][] { { false }, { true } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "peerGenerationChanges") |
| | | public void aDiscardedWriteIsNotConfirmedByALaterReceiptOrWrite(boolean changePeerGeneration) throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer server = null; |
| | | try |
| | | { |
| | | server = newReplicationServer(new DSRSShutdownSync(), "shutdownDiscardedReceiptDb", 8255); |
| | | final ReplicationServerHandler handler = new ReplicationServerHandler(null, 100, server, 100); |
| | | handler.setBaseDNAndDomain(baseDN, false); |
| | | handler.setInitialServerState(new ServerState()); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, false); |
| | | domain.initGenerationID(1); |
| | | handler.setGenerationId(changePeerGeneration ? 2 : 1); |
| | | final long time = System.currentTimeMillis(); |
| | | final CSN first = new CSN(time, 1, REMOTE_DS_ID); |
| | | final CSN received = new CSN(time, 2, REMOTE_DS_ID); |
| | | final CSN last = new CSN(time, 3, REMOTE_DS_ID); |
| | | for (CSN csn : Arrays.asList(first, received, last)) |
| | | { |
| | | final DeleteMsg update = new DeleteMsg(baseDN, csn, |
| | | "22222222-2222-2222-2222-222222222222"); |
| | | if (csn.equals(received)) |
| | | { |
| | | handler.recordReceivedUpdate(update); |
| | | } |
| | | server.getChangelogDB().getReplicationDomainDB().publishUpdateMsg(baseDN, update); |
| | | } |
| | | assertThat(handler.getNextMessage().getCSN()).isEqualTo(first); |
| | | handler.updateDiscardedState(first); |
| | | if (changePeerGeneration) |
| | | { |
| | | // A peer now advertising the right generation has not received the dropped history. |
| | | handler.setGenerationId(1); |
| | | // Its old receipts are forgotten, so this record is conservatively sent again. |
| | | assertThat(handler.getNextMessage().getCSN()).isEqualTo(received); |
| | | handler.updatePublishedState(received); |
| | | } |
| | | assertThat(handler.getNextMessage().getCSN()).isEqualTo(last); |
| | | final ServerState target = new ServerState(); |
| | | target.update(received); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())).isFalse(); |
| | | handler.updatePublishedState(last); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())) |
| | | .as("a later socket write must not conceal an earlier discarded record").isFalse(); |
| | | } |
| | | finally |
| | | { |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void exactReceiptsReleaseOnlyMatchingDiscardedWrites() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final ReplicationServer server = newReplicationServer(new DSRSShutdownSync(), "exactDiscardedReceiptDb", 8263); |
| | | try |
| | | { |
| | | final ReplicationServerHandler handler = new ReplicationServerHandler(null, 2, server, 100); |
| | | handler.setBaseDNAndDomain(baseDN, false); |
| | | handler.setInitialServerState(new ServerState()); |
| | | server.getReplicationServerDomain(baseDN, false).initGenerationID(1); |
| | | handler.setGenerationId(2); |
| | | final List<DeleteMsg> updates = new ArrayList<>(); |
| | | final long time = System.currentTimeMillis(); |
| | | for (int i = 0; i < 4; i++) |
| | | { |
| | | final DeleteMsg update = new DeleteMsg(baseDN, new CSN(time, i + 1, REMOTE_DS_ID), |
| | | "22222222-2222-2222-2222-222222222222"); |
| | | updates.add(update); |
| | | assertThat(handler.updateServerState(update)).isTrue(); |
| | | } |
| | | final DeleteMsg pending = updates.get(0); |
| | | final DeleteMsg firstDiscard = updates.get(1); |
| | | final DeleteMsg secondDiscard = updates.get(2); |
| | | final DeleteMsg delayedDiscard = updates.get(3); |
| | | handler.updateDiscardedState(firstDiscard.getCSN()); |
| | | handler.updateDiscardedState(secondDiscard.getCSN()); |
| | | handler.recordReceivedUpdate(firstDiscard); // Wrong generation. |
| | | handler.setGenerationId(1); |
| | | handler.recordReceivedUpdate(delayedDiscard); |
| | | |
| | | final ServerState target = new ServerState(); |
| | | target.update(pending.getCSN()); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())) |
| | | .as("an exact receipt cannot release an earlier pending write").isFalse(); |
| | | target.update(firstDiscard.getCSN()); |
| | | handler.updatePublishedState(pending.getCSN()); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())) |
| | | .as("a receipt from another generation cannot release the first discard").isFalse(); |
| | | handler.recordReceivedUpdate(firstDiscard); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())).isTrue(); |
| | | target.update(delayedDiscard.getCSN()); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())) |
| | | .as("the other discarded write from the same origin is still missing").isFalse(); |
| | | handler.recordReceivedUpdate(secondDiscard); |
| | | // The two intervening receipts evicted this CSN from the ordinary catch-up cache. |
| | | handler.updateDiscardedState(delayedDiscard.getCSN()); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())) |
| | | .as("the last exact receipt preceded its discard callback").isTrue(); |
| | | } |
| | | finally |
| | | { |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] overflowDiscards() |
| | | { |
| | | // Confirm the first two CSNs in either order, with or without a third missing discard. |
| | | return new Object[][] { { 2, 0 }, { 2, 1 }, { 3, 1 } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "overflowDiscards") |
| | | public void exactOverflowReceiptDoesNotHideAnotherDiscard(int discardCount, int firstReceipt) throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final ReplicationServer server = newReplicationServer(new DSRSShutdownSync(), "overflowDiscardDb", 8265); |
| | | try |
| | | { |
| | | final ReplicationServerHandler handler = new ReplicationServerHandler(null, 1, server, 100); |
| | | handler.setBaseDNAndDomain(baseDN, false); |
| | | handler.setInitialServerState(new ServerState()); |
| | | server.getReplicationServerDomain(baseDN, false).initGenerationID(1); |
| | | handler.setGenerationId(1); |
| | | final List<DeleteMsg> updates = new ArrayList<>(); |
| | | final long time = System.currentTimeMillis(); |
| | | for (int i = 0; i < discardCount; i++) |
| | | { |
| | | final DeleteMsg update = new DeleteMsg(baseDN, new CSN(time, i + 1, REMOTE_DS_ID), |
| | | "22222222-2222-2222-2222-222222222222"); |
| | | updates.add(update); |
| | | assertThat(handler.updateServerState(update)).isTrue(); |
| | | handler.updateDiscardedState(update.getCSN()); |
| | | } |
| | | final ServerState target = new ServerState(); |
| | | target.update(updates.get(discardCount - 1).getCSN()); |
| | | handler.recordReceivedUpdate(updates.get(firstReceipt)); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())).isFalse(); |
| | | handler.recordReceivedUpdate(updates.get(1 - firstReceipt)); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())) |
| | | .as("the first two exact receipts cover the target only if no third discard is missing") |
| | | .isEqualTo(discardCount == 2); |
| | | } |
| | | finally |
| | | { |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] changelogFailureSources() |
| | | { |
| | | return new Object[][] { { true }, { false } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "changelogFailureSources") |
| | | public void changelogFailureShutsDownAfterReleasingDirectAdmission(boolean fromDS) throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final ReplicationServer server = newReplicationServer(new DSRSShutdownSync(), "failedDirectPublishDb", 8264); |
| | | try |
| | | { |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | domain.initGenerationID(1); |
| | | final ServerHandler source = mock(ServerHandler.class); |
| | | when(source.isDataServer()).thenReturn(fromDS); |
| | | when(source.getGenerationId()).thenReturn(1L); |
| | | final Field dbField = ReplicationServerDomain.class.getDeclaredField("domainDB"); |
| | | dbField.setAccessible(true); |
| | | final ReplicationDomainDB failing = mock(ReplicationDomainDB.class); |
| | | final DeleteMsg update = new DeleteMsg(baseDN, new CSN(System.currentTimeMillis(), 1, REMOTE_DS_ID), |
| | | "22222222-2222-2222-2222-222222222222"); |
| | | when(failing.publishUpdateMsg(baseDN, update)).thenThrow(new ChangelogException(new IOException("injected"))); |
| | | dbField.set(domain, failing); |
| | | |
| | | final List<String> records = errorLogRecordsOf(() -> { |
| | | domain.put(update, source); |
| | | return null; |
| | | }); |
| | | assertThat(records.stream().anyMatch(line -> line.contains("RS shutdown timed out waiting for direct DS updates"))) |
| | | .as("the failed publisher can cross its own domain's shutdown barrier").isFalse(); |
| | | when(source.isDataServer()).thenReturn(true); |
| | | assertThatThrownBy(() -> domain.put(update, source)).isInstanceOf(IOException.class) |
| | | .hasMessageContaining("closing its directory connections"); |
| | | } |
| | | finally |
| | | { |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] discardBeforeOrAfterLocalReset() |
| | | { |
| | | return new Object[][] { { false }, { true } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "discardBeforeOrAfterLocalReset") |
| | | public void localGenerationResetDoesNotCarryDiscardedWrites(boolean delayedDiscard) throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer server = null; |
| | | try |
| | | { |
| | | server = newReplicationServer(new DSRSShutdownSync(), "shutdownDiscardedGenerationDb", 8257); |
| | | final ReplicationServerHandler handler = new ReplicationServerHandler(null, 100, server, 100); |
| | | handler.setBaseDNAndDomain(baseDN, false); |
| | | handler.setInitialServerState(new ServerState()); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, false); |
| | | domain.initGenerationID(1); |
| | | handler.setGenerationId(1); |
| | | final long time = System.currentTimeMillis(); |
| | | final CSN old = new CSN(time, 1, REMOTE_DS_ID); |
| | | final CSN current = new CSN(time, 2, REMOTE_DS_ID); |
| | | server.getChangelogDB().getReplicationDomainDB().publishUpdateMsg(baseDN, |
| | | new DeleteMsg(baseDN, old, "22222222-2222-2222-2222-222222222222")); |
| | | assertThat(handler.getNextMessage().getCSN()).isEqualTo(old); |
| | | if (!delayedDiscard) |
| | | { |
| | | handler.updateDiscardedState(old); |
| | | } |
| | | domain.changeGenerationId(2); |
| | | handler.setGenerationId(2); |
| | | if (delayedDiscard) |
| | | { |
| | | // The writer selected this record before reset, but reports its drop afterwards. |
| | | handler.updateDiscardedState(old); |
| | | } |
| | | server.getChangelogDB().getReplicationDomainDB().publishUpdateMsg(baseDN, |
| | | new DeleteMsg(baseDN, current, "22222222-2222-2222-2222-222222222222")); |
| | | assertThat(handler.getNextMessage().getCSN()).isEqualTo(current); |
| | | handler.updatePublishedState(current); |
| | | final ServerState target = new ServerState(); |
| | | target.update(current); |
| | | assertThat(handler.awaitPublished(target, System.nanoTime())) |
| | | .as("a local reset discards the old generation's delivery obligation").isTrue(); |
| | | } |
| | | finally |
| | | { |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] receiptCacheResets() |
| | | { |
| | | return new Object[][] { { false }, { true } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "receiptCacheResets") |
| | | public void boundedReceiptsNeverHideUnknownHistory(boolean newGeneration) throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer server = null; |
| | | try |
| | | { |
| | | server = newReplicationServer(new DSRSShutdownSync(), "boundedPeerReceiptsDb", 8256); |
| | | final ReplicationServerHandler handler = new ReplicationServerHandler(null, 2, server, 100); |
| | | handler.setBaseDNAndDomain(baseDN, false); |
| | | handler.setInitialServerState(new ServerState()); |
| | | handler.setGenerationId(1); |
| | | final long time = System.currentTimeMillis(); |
| | | final List<CSN> expected = new ArrayList<>(); |
| | | for (int i = 1; i <= 6; i++) |
| | | { |
| | | final CSN csn = new CSN(time, i, REMOTE_DS_ID); |
| | | final DeleteMsg update = new DeleteMsg(baseDN, csn, |
| | | "22222222-2222-2222-2222-222222222222"); |
| | | if (i % 2 == 1) |
| | | { |
| | | handler.recordReceivedUpdate(update); |
| | | } |
| | | if (newGeneration || i == 1 || i % 2 == 0) |
| | | { |
| | | // The first receipt is evicted; an unknown or forgotten record is sent. |
| | | expected.add(csn); |
| | | } |
| | | server.getChangelogDB().getReplicationDomainDB().publishUpdateMsg(baseDN, update); |
| | | } |
| | | if (newGeneration) |
| | | { |
| | | handler.setGenerationId(2); |
| | | } |
| | | for (CSN csn : expected) |
| | | { |
| | | assertThat(handler.getNextMessage().getCSN()).isEqualTo(csn); |
| | | handler.updatePublishedState(csn); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void generationResetDoesNotAwaitDiscardedUpdates() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | ReplicationServer server = null; |
| | | ReplicationBroker broker = null; |
| | | FakePeerReplicationServer peer = null; |
| | | try |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | server = newReplicationServer(new DSRSShutdownSync(), "shutdownResetUpdatesDb", 8251, port); |
| | | broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | final CSN csn = new CSN(System.currentTimeMillis(), 1, REMOTE_DS_ID); |
| | | broker.publish(new DeleteMsg(DN.valueOf("uid=old," + baseDN), csn, |
| | | "22222222-2222-2222-2222-222222222222")); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { |
| | | assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(csn); |
| | | }); |
| | | broker.stop(); |
| | | broker = null; |
| | | domain.changeGenerationId(EMPTY_DN_GENID + 1); |
| | | peer = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID + 1); |
| | | waitForConnectedReplicationServer(domain, REMOTE_RS_ID); |
| | | final List<String> records = errorLogRecordsOf(() -> { |
| | | domain.awaitDirectUpdatesForwarded(System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(100)); |
| | | return null; |
| | | }); |
| | | assertThat(records.stream().anyMatch(line -> line.contains("RS shutdown could not forward"))) |
| | | .as("a generation reset discarded these changes, so the new generation owes no forward") |
| | | .isFalse(); |
| | | } |
| | | finally |
| | | { |
| | | closeQuietly(peer); |
| | | if (broker != null) |
| | | { |
| | | broker.stop(); |
| | | } |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void shutdownWaitsForAReaderAlreadyRemovedByConcurrentTeardown() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final CountDownLatch inDatabase = new CountDownLatch(1); |
| | | final CountDownLatch releasePut = new CountDownLatch(1); |
| | | final ExecutorService executor = Executors.newFixedThreadPool(2); |
| | | ReplicationServer server = null; |
| | | ReplicationBroker broker = null; |
| | | FakePeerReplicationServer peer = null; |
| | | Future<?> teardown = null; |
| | | Future<?> stopped = null; |
| | | try |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | server = newReplicationServer(new DSRSShutdownSync(), "shutdownConcurrentReaderDb", 8252, port); |
| | | broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID); |
| | | peer = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | waitForConnectedReplicationServer(domain, REMOTE_RS_ID); |
| | | waitForFollowing(domain, REMOTE_RS_ID); |
| | | final CSN first = new CSN(System.currentTimeMillis(), 1, REMOTE_DS_ID); |
| | | Future<DeleteMsg> receivedFirst = peer.receive(DeleteMsg.class); |
| | | broker.publish(new DeleteMsg(DN.valueOf("uid=first," + baseDN), first, |
| | | "22222222-2222-2222-2222-222222222222")); |
| | | assertThat(receivedFirst.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS).getCSN()).isEqualTo(first); |
| | | final Future<List<ReplicationMsg>> received = peer.receiveUntil(StopMsg.class); |
| | | |
| | | final Field dbField = ReplicationServerDomain.class.getDeclaredField("domainDB"); |
| | | dbField.setAccessible(true); |
| | | final ReplicationDomainDB database = (ReplicationDomainDB) dbField.get(domain); |
| | | final ReplicationDomainDB delayed = mock(ReplicationDomainDB.class, delegatesTo(database)); |
| | | doAnswer(invocation -> { |
| | | boolean created = database.publishUpdateMsg(baseDN, (UpdateMsg) invocation.getArguments()[1]); |
| | | inDatabase.countDown(); |
| | | assertThat(releasePut.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue(); |
| | | return created; |
| | | }).when(delayed).publishUpdateMsg(eq(baseDN), any(UpdateMsg.class)); |
| | | dbField.set(domain, delayed); |
| | | final CSN last = new CSN(first.getTime(), 2, REMOTE_DS_ID); |
| | | broker.publish(new DeleteMsg(DN.valueOf("uid=last," + baseDN), last, |
| | | "22222222-2222-2222-2222-222222222222")); |
| | | assertThat(inDatabase.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue(); |
| | | final DataServerHandler ds = domain.getConnectedDSs().get(REMOTE_DS_ID); |
| | | teardown = executor.submit(() -> domain.stopServer(ds, false)); |
| | | newConnectionTimer().repeatUntilSuccess(() -> { assertThat(domain.getConnectedDSs()).isEmpty(); }); |
| | | final ReplicationServer stopping = server; |
| | | stopped = executor.submit(() -> stopping.shutdown()); |
| | | try |
| | | { |
| | | stopped.get(EARLY_CLOSE_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | } |
| | | catch (TimeoutException expected) |
| | | { |
| | | // A correct shutdown is waiting for the put which already reached its database. |
| | | } |
| | | releasePut.countDown(); |
| | | stopped.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | final List<CSN> changes = new ArrayList<>(); |
| | | for (ReplicationMsg msg : received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)) |
| | | { |
| | | if (msg instanceof DeleteMsg) |
| | | { |
| | | changes.add(((DeleteMsg) msg).getCSN()); |
| | | } |
| | | } |
| | | assertThat(changes).as("the accepted update of a reader already in teardown").contains(last); |
| | | } |
| | | finally |
| | | { |
| | | releasePut.countDown(); |
| | | awaitQuietly(teardown); |
| | | awaitQuietly(stopped); |
| | | closeQuietly(peer); |
| | | if (broker != null) |
| | | { |
| | | broker.stop(); |
| | | } |
| | | removeQuietly(server); |
| | | executor.shutdownNow(); |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void shutdownWaitsForTheReplicaOfflineMsgToBeForwarded() throws Exception |
| | | { |
| | |
| | | * released by the first forward reported for it, so end the wait now rather than sit out |
| | | * the rest of its grace period in the join below. |
| | | */ |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN, unreachableCSN, HANDSHAKING_RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded( |
| | | baseDN, unreachableCSN, domain.getConnectedRSs().get(HANDSHAKING_RS_ID).offlineForwarder()); |
| | | } |
| | | finally |
| | | { |
| | |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void undeliveredDirectUpdatesShareOneDeadlineAcrossDomains() throws Exception |
| | | { |
| | | final DN baseDN1 = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | final DN baseDN2 = DN.valueOf("dc=world,dc=company"); |
| | | final List<ReplicationBroker> brokers = new ArrayList<>(); |
| | | final List<FakePeerReplicationServer> peers = new ArrayList<>(); |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | final ReplicationServer server = newReplicationServer( |
| | | new DSRSShutdownSync(), "directUpdatesSharedDeadlineDb", 8262, port); |
| | | try |
| | | { |
| | | for (DN baseDN : Arrays.asList(baseDN1, baseDN2)) |
| | | { |
| | | final ReplicationBroker broker = |
| | | openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID); |
| | | brokers.add(broker); |
| | | final FakePeerReplicationServer peer = FakePeerReplicationServer.connected( |
| | | port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID, HELD_BACK_PEER_WINDOW); |
| | | peers.add(peer); |
| | | final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true); |
| | | waitForConnectedReplicationServer(domain, REMOTE_RS_ID); |
| | | |
| | | final Future<DeleteMsg> windowFiller = peer.receive(DeleteMsg.class); |
| | | final CSNGenerator csns = new CSNGenerator(REMOTE_DS_ID, 0); |
| | | broker.publish(new DeleteMsg(DN.valueOf("uid=first," + baseDN), csns.newCSN(), |
| | | "11111111-1111-1111-1111-111111111111")); |
| | | assertThat(windowFiller.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isNotNull(); |
| | | |
| | | final CSN blockedCSN = csns.newCSN(); |
| | | broker.publish(new DeleteMsg(DN.valueOf("uid=blocked," + baseDN), blockedCSN, |
| | | "22222222-2222-2222-2222-222222222222")); |
| | | newConnectionTimer().repeatUntilSuccess(() -> |
| | | assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(blockedCSN)); |
| | | } |
| | | |
| | | final long budgetMillis = 2000; |
| | | final List<String> records = errorLogRecordsOf(() -> { |
| | | final long start = System.nanoTime(); |
| | | server.awaitDirectUpdatesForwarded(TimeUnit.MILLISECONDS.toNanos(budgetMillis)); |
| | | assertThat(elapsedMillis(start)) |
| | | .as("both domains share one deadline") |
| | | .isBetween(budgetMillis, budgetMillis + 1500); |
| | | return null; |
| | | }); |
| | | for (DN baseDN : Arrays.asList(baseDN1, baseDN2)) |
| | | { |
| | | final String warning = "RS shutdown could not forward all direct DS updates for " |
| | | + baseDN + " to RS " + REMOTE_RS_ID + ";"; |
| | | assertThat(records.stream().filter(line -> line.contains(warning)).count()).isEqualTo(1); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | peers.forEach(this::closeQuietly); |
| | | brokers.forEach(this::stop); |
| | | removeQuietly(server); |
| | | } |
| | | } |
| | | |
| | | private ReplicationServer newReplicationServer(DSRSShutdownSync shutdownSync, String dbDirName, |
| | | int serverId) throws Exception |
| | | { |
| | |
| | | final ReplicationServerDomain domain = replicationServer.getReplicationServerDomain(baseDN, true); |
| | | final ReplicationServerHandler rsHandler = |
| | | new ReplicationServerHandler(session, 100, replicationServer, 100); |
| | | registerConnectedReplicationServer(domain, baseDN, rsHandler, serverId); |
| | | return rsHandler; |
| | | } |
| | | |
| | | private void registerConnectedReplicationServer(ReplicationServerDomain domain, DN baseDN, |
| | | ReplicationServerHandler rsHandler, int serverId) throws Exception |
| | | { |
| | | rsHandler.serverId = serverId; |
| | | rsHandler.serverURL = "127.0.0.1:1636"; |
| | | rsHandler.setBaseDNAndDomain(baseDN, false); |
| | |
| | | { |
| | | domain.release(); |
| | | } |
| | | return rsHandler; |
| | | } |
| | | |
| | | /** Waits for the barrier to have been told that this peer will not forward the message. */ |
| | |
| | | { |
| | | return; |
| | | } |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN, offlineCSN, REMOTE_RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN, offlineCSN, new ForwardingPeer(REMOTE_RS_ID)); |
| | | } |
| | | }); |
| | | } |
| | |
| | | |
| | | @Override |
| | | public void replicaOfflineMsgDispatched( |
| | | DN baseDN, CSN offlineCSN, Collection<Integer> replicationServerIds) |
| | | DN baseDN, CSN offlineCSN, Collection<ForwardingPeer> peers) |
| | | { |
| | | final Runnable action = whileDispatching.getAndSet(null); |
| | | if (action != null) |
| | | { |
| | | action.run(); |
| | | } |
| | | dispatchedTo.addAll(replicationServerIds); |
| | | super.replicaOfflineMsgDispatched(baseDN, offlineCSN, replicationServerIds); |
| | | for (ForwardingPeer peer : peers) |
| | | { |
| | | dispatchedTo.add(peer.getServerId()); |
| | | } |
| | | super.replicaOfflineMsgDispatched(baseDN, offlineCSN, peers); |
| | | dispatched.countDown(); |
| | | } |
| | | |
| | | @Override |
| | | public void replicaOfflineMsgForwarded(DN baseDN, CSN forwardedCSN, int replicationServerId) |
| | | public void replicaOfflineMsgForwarded(DN baseDN, CSN forwardedCSN, ForwardingPeer peer) |
| | | { |
| | | forwardedBy.add(replicationServerId); |
| | | super.replicaOfflineMsgForwarded(baseDN, forwardedCSN, replicationServerId); |
| | | forwardedBy.add(peer.getServerId()); |
| | | super.replicaOfflineMsgForwarded(baseDN, forwardedCSN, peer); |
| | | } |
| | | |
| | | @Override |
| | | public void replicaOfflineMsgNotForwarded(DN baseDN, int replicationServerId) |
| | | public void replicaOfflineMsgNotForwarded(DN baseDN, ForwardingPeer peer) |
| | | { |
| | | gaveUpOn.add(replicationServerId); |
| | | super.replicaOfflineMsgNotForwarded(baseDN, replicationServerId); |
| | | gaveUpOn.add(peer.getServerId()); |
| | | super.replicaOfflineMsgNotForwarded(baseDN, peer); |
| | | } |
| | | |
| | | /** Waits for put() to have pushed a ReplicaOfflineMsg to the peers of its domain. */ |
| | |
| | | * information: "Portions copyright [year] [name of copyright owner]". |
| | | * |
| | | * Copyright 2026 3A Systems, LLC. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.server; |
| | | |
| | |
| | | import static org.mockito.Mockito.mock; |
| | | import static org.mockito.Mockito.when; |
| | | import static org.opends.messages.ReplicationMessages.ERR_DS_BADLY_DISCONNECTED; |
| | | import static org.opends.messages.ReplicationMessages.ERR_RS_BADLY_DISCONNECTED; |
| | | import static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING; |
| | | |
| | | import java.io.ByteArrayInputStream; |
| | | import java.io.ByteArrayOutputStream; |
| | | import java.io.IOException; |
| | | import java.io.InputStream; |
| | | import java.io.FilterInputStream; |
| | | import java.io.InterruptedIOException; |
| | | import java.io.OutputStream; |
| | | import java.net.ServerSocket; |
| | |
| | | import org.opends.server.replication.protocol.Session; |
| | | import org.opends.server.replication.protocol.StopMsg; |
| | | import org.testng.annotations.Test; |
| | | import org.testng.annotations.DataProvider; |
| | | |
| | | /** Checks the records emitted when a replication server reader loses its peer. */ |
| | | @SuppressWarnings("javadoc") |
| | |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] socketCloseOrigins() |
| | | { |
| | | return new Object[][] { { true }, { false } }; |
| | | } |
| | | |
| | | /** The local socket close wakes a blocked read just as a remote reset does. */ |
| | | @Test(dataProvider = "socketCloseOrigins") |
| | | public void socketCloseReportsOnlyUnexpectedPeerLoss(boolean localClose) throws Exception |
| | | { |
| | | final CountDownLatch reading = new CountDownLatch(1); |
| | | final ExecutorService executor = Executors.newSingleThreadExecutor(); |
| | | try (ServerSocket listener = new ServerSocket(0); |
| | | Socket peer = new Socket("127.0.0.1", listener.getLocalPort()); |
| | | Socket socket = listener.accept()) |
| | | { |
| | | final InputStream input = new FilterInputStream(socket.getInputStream()) |
| | | { |
| | | @Override |
| | | public int read(byte[] bytes, int offset, int length) throws IOException |
| | | { |
| | | reading.countDown(); |
| | | return super.read(bytes, offset, length); |
| | | } |
| | | }; |
| | | try (Session session = new Session(socket, new TestSocket(input))) |
| | | { |
| | | session.setProtocolVersion(ProtocolVersion.getCurrentVersion()); |
| | | final ReplicationServerHandler handler = mock(ReplicationServerHandler.class); |
| | | final ReplicationServer server = mock(ReplicationServer.class); |
| | | when(server.getServerId()).thenReturn(9301); |
| | | final java.lang.reflect.Field field = MessageHandler.class.getDeclaredField("replicationServer"); |
| | | field.setAccessible(true); |
| | | field.set(handler, server); |
| | | when(handler.getBadlyDisconnectedErrorMessage()).thenReturn(ERR_RS_BADLY_DISCONNECTED.get( |
| | | 9301, 9311, session.getReadableRemoteAddress(), DN.valueOf(TEST_ROOT_DN_STRING))); |
| | | final List<String> logged = errorLogRecordsOf(() -> { |
| | | final Future<?> reader = executor.submit(() -> new ServerReader(session, handler).run()); |
| | | assertThat(reading.await(10, TimeUnit.SECONDS)).as("reader entered socket read").isTrue(); |
| | | if (localClose) |
| | | { |
| | | // The writer can close the session before stopServer marks the handler. |
| | | session.close(); |
| | | } |
| | | else |
| | | { |
| | | peer.setSoLinger(true, 0); |
| | | peer.close(); |
| | | } |
| | | reader.get(10, TimeUnit.SECONDS); |
| | | return null; |
| | | }); |
| | | assertThat(logged).filteredOn(s -> s.contains("category=SYNC severity=ERROR msgID=181 ")) |
| | | .hasSize(localClose ? 0 : 1); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | executor.shutdownNow(); |
| | | assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).as("reader stopped").isTrue(); |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void stopMessageIsNotReportedAsBadDisconnection() throws Exception |
| | | { |
| | |
| | | import org.opends.server.DirectoryServerTestCase; |
| | | import org.opends.server.replication.common.CSN; |
| | | import org.testng.annotations.BeforeClass; |
| | | import org.opends.server.replication.service.DSRSShutdownSync.ForwardingPeer; |
| | | import org.testng.annotations.Test; |
| | | |
| | | /** Test the {@link DSRSShutdownSync} class. */ |
| | |
| | | private static final int SERVER_ID = 1; |
| | | private static final int OTHER_SERVER_ID = 2; |
| | | /** A peer replication server the collocated one relays the message to. */ |
| | | private static final int RS_ID = 11; |
| | | private static final int OTHER_RS_ID = 12; |
| | | private static final ForwardingPeer PEER = new ForwardingPeer(11); |
| | | private static final ForwardingPeer OTHER_PEER = new ForwardingPeer(12); |
| | | |
| | | private static DN baseDN1; |
| | | private static DN baseDN2; |
| | |
| | | final CSN offlineCSN = newCSN(SERVER_ID); |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, offlineCSN); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isTrue(); |
| | | } |
| | |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isFalse(); |
| | | |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, refusedByTheBroker, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, refusedByTheBroker, PEER); |
| | | assertThat(shutdownSync.canShutdown(baseDN1)) |
| | | .as("the stale withdrawal was ignored, not turned into a restore") |
| | | .isFalse(); |
| | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)) |
| | | .as("the earlier message went out and nobody has forwarded it yet") |
| | | .isFalse(); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, PEER); |
| | | assertThat(shutdownSync.canShutdown(baseDN1)) |
| | | .as("the forward of the earlier message ends the wait") |
| | | .isTrue(); |
| | |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, sentByTheShutdown); |
| | | shutdownSync.replicaOfflineMsgDispatched( |
| | | baseDN1, sentByTheShutdown, asList(RS_ID, OTHER_RS_ID)); |
| | | baseDN1, sentByTheShutdown, asList(PEER, OTHER_PEER)); |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, refusedByTheBroker); |
| | | shutdownSync.replicaOfflineMsgNotSent(baseDN1, refusedByTheBroker); |
| | | |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, PEER); |
| | | assertThat(shutdownSync.canShutdown(baseDN1)) |
| | | .as("the restored message is still owed the other peer's forward") |
| | | .isFalse(); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, OTHER_RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, OTHER_PEER); |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isTrue(); |
| | | } |
| | | |
| | |
| | | final CSN refusedByTheBroker = newCSN(SERVER_ID, 2); |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, sentByTheShutdown); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, sentByTheShutdown, asList(RS_ID)); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, sentByTheShutdown, asList(PEER)); |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, refusedByTheBroker); |
| | | // not seen: the announcement of the refused message stands in front |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, PEER); |
| | | shutdownSync.replicaOfflineMsgNotSent(baseDN1, refusedByTheBroker); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)) |
| | |
| | | // an import disables then re-enables the replication service |
| | | final CSN sentByTheImport = newCSN(SERVER_ID, 1); |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, sentByTheImport); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheImport, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheImport, PEER); |
| | | Thread.sleep(GRACE_PERIOD + 50); |
| | | |
| | | // the shutdown of the process, much later |
| | |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, queuedByAnEarlierImport); |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, sentByTheShutdown); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, queuedByAnEarlierImport, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, queuedByAnEarlierImport, PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isFalse(); |
| | | |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isTrue(); |
| | | } |
| | |
| | | final DSRSShutdownSync shutdownSync = new DSRSShutdownSync(LONG_GRACE_PERIOD); |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, newCSN(SERVER_ID)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, newCSN(OTHER_SERVER_ID), RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, newCSN(OTHER_SERVER_ID), PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isFalse(); |
| | | } |
| | |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, ofOneReplica); |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, newCSN(OTHER_SERVER_ID)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, ofOneReplica, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, ofOneReplica, PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isFalse(); |
| | | } |
| | |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, ofOneReplica); |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, ofTheOtherReplica); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, ofOneReplica, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, ofTheOtherReplica, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, ofOneReplica, PEER); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, ofTheOtherReplica, PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isTrue(); |
| | | } |
| | |
| | | final CSN offlineCSN = newCSN(SERVER_ID); |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, offlineCSN); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(RS_ID, OTHER_RS_ID)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, RS_ID); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(PEER, OTHER_PEER)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isFalse(); |
| | | } |
| | |
| | | final CSN offlineCSN = newCSN(SERVER_ID); |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, offlineCSN); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(RS_ID, OTHER_RS_ID)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, OTHER_RS_ID); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(PEER, OTHER_PEER)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, PEER); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, OTHER_PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isTrue(); |
| | | } |
| | |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, offlineCSN); |
| | | shutdownSync.replicaOfflineMsgDispatched( |
| | | baseDN1, offlineCSN, Collections.<Integer> emptyList()); |
| | | baseDN1, offlineCSN, Collections.emptyList()); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isTrue(); |
| | | } |
| | |
| | | final CSN offlineCSN = newCSN(SERVER_ID); |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, offlineCSN); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(RS_ID, OTHER_RS_ID)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, RS_ID); |
| | | shutdownSync.replicaOfflineMsgNotForwarded(baseDN1, OTHER_RS_ID); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(PEER, OTHER_PEER)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, PEER); |
| | | shutdownSync.replicaOfflineMsgNotForwarded(baseDN1, OTHER_PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isTrue(); |
| | | } |
| | |
| | | final CSN offlineCSN = newCSN(SERVER_ID); |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, offlineCSN); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(RS_ID, OTHER_RS_ID)); |
| | | shutdownSync.replicaOfflineMsgNotForwarded(baseDN1, OTHER_RS_ID); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(PEER, OTHER_PEER)); |
| | | shutdownSync.replicaOfflineMsgNotForwarded(baseDN1, OTHER_PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isFalse(); |
| | | } |
| | |
| | | final CSN offlineCSN = newCSN(SERVER_ID); |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, offlineCSN); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(RS_ID)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, OTHER_RS_ID); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(PEER)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, OTHER_PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isFalse(); |
| | | } |
| | |
| | | final CSN offlineCSN = newCSN(SERVER_ID); |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, offlineCSN); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isTrue(); |
| | | } |
| | |
| | | final DSRSShutdownSync shutdownSync = new DSRSShutdownSync(LONG_GRACE_PERIOD); |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, newCSN(SERVER_ID)); |
| | | shutdownSync.replicaOfflineMsgNotForwarded(baseDN1, RS_ID); |
| | | shutdownSync.replicaOfflineMsgNotForwarded(baseDN1, PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isFalse(); |
| | | } |
| | |
| | | |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, sentByTheShutdown); |
| | | shutdownSync.replicaOfflineMsgDispatched( |
| | | baseDN1, queuedByAnEarlierImport, asList(RS_ID, OTHER_RS_ID)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, RS_ID); |
| | | baseDN1, queuedByAnEarlierImport, asList(PEER, OTHER_PEER)); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, sentByTheShutdown, PEER); |
| | | |
| | | assertThat(shutdownSync.canShutdown(baseDN1)).isTrue(); |
| | | } |
| | | |
| | | @Test |
| | | public void aDifferentConnectionWithTheSameServerIdCannotReportTheForward() |
| | | { |
| | | final DSRSShutdownSync sync = new DSRSShutdownSync(LONG_GRACE_PERIOD); |
| | | final CSN offlineCSN = newCSN(SERVER_ID); |
| | | final ForwardingPeer replacement = new ForwardingPeer(PEER.getServerId()); |
| | | |
| | | sync.replicaOfflineMsgSent(baseDN1, offlineCSN); |
| | | sync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(replacement)); |
| | | sync.replicaOfflineMsgNotForwarded(baseDN1, PEER); |
| | | assertThat(sync.canShutdown(baseDN1)).isFalse(); |
| | | sync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, PEER); |
| | | assertThat(sync.canShutdown(baseDN1)).isFalse(); |
| | | sync.replicaOfflineMsgForwarded(baseDN1, offlineCSN, replacement); |
| | | assertThat(sync.canShutdown(baseDN1)).isTrue(); |
| | | } |
| | | |
| | | /** |
| | | * The peer which goes away must wake the shutdown up, and not leave it waiting for a forward |
| | | * nobody can report any more. |
| | |
| | | final DSRSShutdownSync shutdownSync = new DSRSShutdownSync(LONG_GRACE_PERIOD); |
| | | final CSN offlineCSN = newCSN(SERVER_ID); |
| | | shutdownSync.replicaOfflineMsgSent(baseDN1, offlineCSN); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(RS_ID)); |
| | | final Thread peerStopper = newPeerStopperThread(shutdownSync, RS_ID); |
| | | shutdownSync.replicaOfflineMsgDispatched(baseDN1, offlineCSN, asList(PEER)); |
| | | final Thread peerStopper = newPeerStopperThread(shutdownSync, PEER); |
| | | |
| | | final long startTime = System.nanoTime(); |
| | | peerStopper.start(); |
| | |
| | | } |
| | | |
| | | /** Stops the peer the message was queued for, as a disconnection during the wait does. */ |
| | | private Thread newPeerStopperThread(final DSRSShutdownSync shutdownSync, final int peerId) |
| | | private Thread newPeerStopperThread(final DSRSShutdownSync shutdownSync, final ForwardingPeer peer) |
| | | { |
| | | return new Thread(new Runnable() |
| | | { |
| | |
| | | try |
| | | { |
| | | Thread.sleep(FORWARD_DELAY); |
| | | shutdownSync.replicaOfflineMsgNotForwarded(baseDN1, peerId); |
| | | shutdownSync.replicaOfflineMsgNotForwarded(baseDN1, peer); |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | |
| | | try |
| | | { |
| | | Thread.sleep(FORWARD_DELAY); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, ofTheFirstDomain, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN1, ofTheFirstDomain, PEER); |
| | | Thread.sleep(FORWARD_DELAY); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN2, ofTheSecondDomain, RS_ID); |
| | | shutdownSync.replicaOfflineMsgForwarded(baseDN2, ofTheSecondDomain, PEER); |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | |
| | | import static java.util.concurrent.TimeUnit.MILLISECONDS; |
| | | import static java.util.concurrent.TimeUnit.SECONDS; |
| | | import static java.util.stream.Collectors.toSet; |
| | | import static org.mockito.Mockito.mock; |
| | | import static org.opends.messages.ReplicationMessages.*; |
| | | import static org.opends.server.util.CollectionUtils.*; |
| | | import static org.testng.Assert.*; |
| | |
| | | import java.net.SocketTimeoutException; |
| | | import java.io.InputStream; |
| | | import java.io.OutputStream; |
| | | import java.lang.reflect.InvocationTargetException; |
| | | import java.util.concurrent.FutureTask; |
| | | import java.util.concurrent.ExecutionException; |
| | | import java.util.Collections; |
| | |
| | | |
| | | import org.forgerock.i18n.LocalizableMessage; |
| | | import org.forgerock.i18n.slf4j.LocalizedLogger; |
| | | import org.mockito.stubbing.Answer; |
| | | import org.opends.server.TestCaseUtils; |
| | | import org.opends.server.backends.task.Task; |
| | | import org.opends.server.replication.ReplicationTestCase; |
| | |
| | | import org.opends.server.replication.protocol.DeleteMsg; |
| | | import org.opends.server.replication.protocol.ErrorMsg; |
| | | import org.opends.server.replication.protocol.ProtocolVersion; |
| | | import org.opends.server.replication.protocol.ReplicaOfflineMsg; |
| | | import org.opends.server.replication.protocol.ReplicationMsg; |
| | | import org.opends.server.replication.protocol.ResetGenerationIdMsg; |
| | | import org.opends.server.replication.protocol.Session; |
| | | import org.opends.server.replication.protocol.TopologyMsg; |
| | | import org.opends.server.replication.protocol.UpdateMsg; |
| | | import org.opends.server.replication.server.ReplServerFakeConfiguration; |
| | |
| | | private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass(); |
| | | private static final Task NO_INIT_TASK = null; |
| | | |
| | | @Test |
| | | public void reportsARefusedPublicationAndRestoresTheSendWindowCredit() throws Exception |
| | | { |
| | | final DN baseDN = DN.valueOf(TestCaseUtils.TEST_ROOT_DN_STRING); |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | final int dsId = 17; |
| | | final ReplicationServer rs = createReplicationServer(18, port, "refusedPublicationDb", 100); |
| | | ReplicationBroker broker = null; |
| | | try |
| | | { |
| | | broker = openReplicationSession(baseDN, dsId, 100, port, 1000, EMPTY_DN_GENID); |
| | | final Session session = broker.getSession(); |
| | | final short negotiatedVersion = session.getProtocolVersion(); |
| | | final int credit = broker.getCurrentSendWindow(); |
| | | assertTrue(credit > 0); |
| | | try |
| | | { |
| | | // A version 7 peer cannot receive a ReplicaOfflineMsg, so the session must reject it. |
| | | session.setProtocolVersion(ProtocolVersion.REPLICATION_PROTOCOL_V7); |
| | | final ReplicaOfflineMsg offline = new ReplicaOfflineMsg(new CSNGenerator(dsId, 0).newCSN()); |
| | | assertFalse(broker.publish(offline, true), "the broker reported a rejected message as published"); |
| | | assertEquals(broker.getCurrentSendWindow(), credit, "a rejected update consumed send-window credit"); |
| | | } |
| | | finally |
| | | { |
| | | session.setProtocolVersion(negotiatedVersion); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | stop(broker); |
| | | remove(rs); |
| | | } |
| | | } |
| | | |
| | | @DataProvider(name = "publishAndReceiveData") |
| | | public Object[][] createpublishAndReceiveData() |
| | | { |
| | |
| | | return initializeFromRemote(domain, NO_INIT_TASK); |
| | | } |
| | | |
| | | /** A request sent on the new session must complete even if the broker was just disconnected. */ |
| | | @Test |
| | | public void initializeRequestSentDuringReconnectCompletes() throws Exception |
| | | { |
| | | DN baseDN = DN.valueOf("o=test"); |
| | | ReplicationServer server = null; |
| | | RecordingExportDomain exporter = null; |
| | | FakeReplicationDomain importer = null; |
| | | ReplicationBroker originalBroker = null; |
| | | try |
| | | { |
| | | int port = TestCaseUtils.findFreePort(); |
| | | server = createReplicationServer(11, port, "initializeDuringReconnect", 100); |
| | | SortedSet<String> servers = newTreeSet("localhost:" + port); |
| | | String exportedData = buildExportedData(10); |
| | | StringBuffer importedData = new StringBuffer(); |
| | | exporter = new RecordingExportDomain(baseDN, 1, servers, 0, exportedData, 10); |
| | | importer = new FakeReplicationDomain(baseDN, 2, servers, 0, null, importedData, 0); |
| | | waitTopologyKnowsReplica(importer, 1); |
| | | waitTopologyKnowsReplica(exporter, 2); |
| | | |
| | | originalBroker = importer.broker; |
| | | Thread initiatingThread = Thread.currentThread(); |
| | | ReplicationBroker connected = originalBroker; |
| | | importer.broker = mock(ReplicationBroker.class, (Answer<Object>) call -> { |
| | | if ("isConnected".equals(call.getMethod().getName()) && Thread.currentThread() == initiatingThread) |
| | | { |
| | | return false; |
| | | } |
| | | try |
| | | { |
| | | return call.getMethod().invoke(connected, call.getArguments()); |
| | | } |
| | | catch (InvocationTargetException e) |
| | | { |
| | | throw e.getCause(); |
| | | } |
| | | }); |
| | | |
| | | RecordingInitializeTask task = new RecordingInitializeTask(); |
| | | importer.initializeFromRemote(1, task); |
| | | assertExportSuccessful(exporter, importer, task, exportedData, importedData); |
| | | } |
| | | finally |
| | | { |
| | | if (originalBroker != null) |
| | | { |
| | | importer.broker = originalBroker; |
| | | } |
| | | disable(exporter, importer); |
| | | remove(server); |
| | | } |
| | | } |
| | | |
| | | private boolean initializeFromRemote(ReplicationDomain domain, Task task) throws DirectoryException |
| | | { |
| | | try { |
| | |
| | | .appendString(details) |
| | | .appendLongUTF8(System.currentTimeMillis()) |
| | | .toByteArray(); |
| | | return (ErrorMsg) ReplicationMsg.generateMsg(bytes, ProtocolVersion.getCurrentVersion()); |
| | | // This payload predates the v9 initialization attempt field. |
| | | return (ErrorMsg) ReplicationMsg.generateMsg(bytes, ProtocolVersion.REPLICATION_PROTOCOL_V8); |
| | | } |
| | | |
| | | /** Returns the details of the ErrorMsgs the replica receives before the one with the provided details. */ |
| | |
| | | import static org.mockito.Mockito.when; |
| | | |
| | | import java.io.ByteArrayOutputStream; |
| | | import java.io.File; |
| | | import java.io.PrintStream; |
| | | import java.lang.reflect.Method; |
| | | import java.nio.charset.StandardCharsets; |
| | |
| | | import org.opends.admin.ads.TopologyCache; |
| | | import org.opends.admin.ads.util.ConnectionWrapper; |
| | | import org.opends.server.DirectoryServerTestCase; |
| | | import org.opends.server.TestCaseUtils; |
| | | import org.opends.server.core.DirectoryServer; |
| | | import org.testng.annotations.Test; |
| | | |
| | | @SuppressWarnings("javadoc") |
| | |
| | | .hasSize(8).endsWith("6442450929"); |
| | | } |
| | | |
| | | @Test |
| | | public void localDisableAllRemovesDomainBelowBackendBaseDN() throws Exception |
| | | { |
| | | TestCaseUtils.startServer(); |
| | | final String baseDN = "o=disable-all"; |
| | | final DN backend = DN.valueOf("ds-cfg-backend-id=disable-all,cn=Backends,cn=config"); |
| | | final DN nestedDN = DN.valueOf("ou=nested," + baseDN); |
| | | final String domains = ",cn=domains,cn=Multimaster Synchronization,cn=Synchronization Providers,cn=config"; |
| | | final DN rootDomain = DN.valueOf("cn=disable-all-root" + domains); |
| | | final DN nestedDomain = DN.valueOf("cn=disable-all-nested" + domains); |
| | | final String replicationServer = "127.0.0.1:" + TestCaseUtils.findFreePort(); |
| | | TestCaseUtils.addEntries( |
| | | "dn: " + backend, |
| | | "objectClass: top", |
| | | "objectClass: ds-cfg-backend", |
| | | "objectClass: ds-cfg-local-backend", |
| | | "objectClass: ds-cfg-memory-backend", |
| | | "ds-cfg-backend-id: disable-all", |
| | | "ds-cfg-java-class: org.opends.server.backends.MemoryBackend", |
| | | "ds-cfg-base-dn: " + baseDN, |
| | | "ds-cfg-enabled: true", |
| | | "ds-cfg-writability-mode: enabled"); |
| | | try |
| | | { |
| | | TestCaseUtils.addEntries( |
| | | "dn: " + baseDN, |
| | | "objectClass: top", |
| | | "objectClass: organization", |
| | | "o: disable-all", |
| | | "", |
| | | "dn: " + nestedDN, |
| | | "objectClass: top", |
| | | "objectClass: organizationalUnit", |
| | | "ou: nested"); |
| | | addReplicationDomain(rootDomain, baseDN, replicationServer, 1); |
| | | addReplicationDomain(nestedDomain, nestedDN.toString(), replicationServer, 2); |
| | | assertThat(DirectoryServer.getEntry(rootDomain)).isNotNull(); |
| | | assertThat(DirectoryServer.getEntry(nestedDomain)).isNotNull(); |
| | | |
| | | final ByteArrayOutputStream output = new ByteArrayOutputStream(); |
| | | final int status = ReplicationCliMain.mainCLI(new String[] { |
| | | "disable", "--configFile", new File(TestCaseUtils.paths.testInstanceRoot, "config/config.ldif").getPath(), |
| | | "--hostname", "127.0.0.1", "--port", String.valueOf(TestCaseUtils.getServerAdminPort()), |
| | | "--bindDN", "cn=Directory Manager", "--adminPassword", "password", "--disableAll", "-X", "-n" |
| | | }, false, output, output); |
| | | |
| | | assertThat(status).as(output.toString()).isZero(); |
| | | assertThat(DirectoryServer.getEntry(rootDomain)).isNull(); |
| | | assertThat(DirectoryServer.getEntry(nestedDomain)).isNull(); |
| | | } |
| | | finally |
| | | { |
| | | for (DN domain : Arrays.asList(nestedDomain, rootDomain)) |
| | | { |
| | | if (DirectoryServer.getEntry(domain) != null) |
| | | { |
| | | final DN externalChangelog = DN.valueOf("cn=external changelog," + domain); |
| | | if (DirectoryServer.getEntry(externalChangelog) != null) |
| | | { |
| | | TestCaseUtils.deleteEntry(externalChangelog); |
| | | } |
| | | TestCaseUtils.deleteEntry(domain); |
| | | } |
| | | } |
| | | TestCaseUtils.deleteEntry(backend); |
| | | } |
| | | } |
| | | |
| | | private static void addReplicationDomain(DN configDN, String baseDN, String replicationServer, int serverID) |
| | | throws Exception |
| | | { |
| | | TestCaseUtils.addEntries( |
| | | "dn: " + configDN, |
| | | "objectClass: top", |
| | | "objectClass: ds-cfg-replication-domain", |
| | | "cn: " + configDN.rdn().getFirstAVA().getAttributeValue(), |
| | | "ds-cfg-base-dn: " + baseDN, |
| | | "ds-cfg-replication-server: " + replicationServer, |
| | | "ds-cfg-server-id: " + serverID); |
| | | } |
| | | |
| | | private static TopologyCache topology(ServerDescriptor... servers) |
| | | { |
| | | final TopologyCache topology = mock(TopologyCache.class); |