clusterer_controller: zero-config HA clusterer control module with automatic sharing tag management via encrypted UDP multicast#4074
Conversation
|
Thank you very much for the contribution, I really like the idea behind it. I do see though that it is marked as a Draft - is it still work in progress, or has it reached to its final state? Let us know when it is ready to review. |
|
Hi, |
9034536 to
2cf5b36
Compare
Port of the clusterer_controller module and its clusterer-module integration to the devel branch: zero-config HA clusterer control over encrypted UDP multicast, per-cluster node identity, hybrid native+controller topologies, cl_ctr_* MI/variables/functions, join flood-DoS hardening, and input validation. Devel adaptations: - cc_discover_bin_sockets() iterates protos[PROTO_BIN].listeners as struct socket_info_full (next/prev), reading the embedded socket_info. - The clusterer core edits are re-seated onto devel's clusterer.c / clusterer_mod.c / node_info.h, merging cleanly with the new bridges feature and the clusterer_enable_rerouting guard. Robustness / log hygiene: - cc_decrypt_pkt distinguishes bootstrap-key failures (real wrong-password / foreign-cluster / tampering -> WARN) from transient session-key mismatches during a (re)key or split-brain heal (-> DBG). - the split-brain defer budget resets on a fresh higher-IP JOIN_REQ so a lower-IP node waits for a live higher-IP peer instead of self-promoting (bounded by CC_JOIN_DEFER_HARDMAX); JOIN_REQ sends are rate-limited. - clusterer: the seed sync-fallback on a fresh start is downgraded from ERROR to DBG (the SYNC_IN_PROGRESS partial-sync failure path is unchanged). - cc_elect_master enforces "MASTER_ALIVE keepalive armed <=> I am the elected master": a node demoted purely by election now stops broadcasting MASTER_ALIVE, fixing an oscillation where a lower-IP node flapped between two masters. Validated end-to-end on a 3-node cluster: controller / native / hybrid modes, master failover and election stability (staggered + simultaneous starts converge to a single stable master), multiple controller clusters sharing one BIN socket (distinct multicast per cluster), MI outputs and error paths, buffer overrun/underrun fuzzing, wrong-password rejection, and config-mismatch. Docs and generated README included (admin guide + HA test appendix).
2cf5b36 to
34f1042
Compare
|
Now it's ready for review, thanks! |
992d376 to
f93b82d
Compare
… consistency Two startup sanity checks for a previously silent misconfiguration: - clusterer_controller is only meaningful when the clusterer module has use_controller=1 (the global switch that pre-creates the controller-managed cluster stubs, sets each one's controller_managed flag so they never touch the DB, and arms the guard that stops the controller from hijacking a native cluster of the same id). If use_controller=0 there is no controller-managed cluster and those safety mechanisms are off, so mod_init now FAILS (refuse to start) rather than driving clusters clusterer never authorised. Hybrid setups keep use_controller=1 - only the per-cluster kind differs - so this never trips them. - The mirror case, use_controller=1 but no clusterer_controller module bound the controller API, logs an ERROR at clusterer child_init (the pre-created controller-managed stubs would never obtain an identity). clusterer does NOT abort here: its native/hybrid clusters still work; only the controller-stub clusters are dead. Plumbing: the clusterer_ctrl binds struct now carries clusterer's use_controller value, and load_clusterer_ctrl_binds() sets clusterer_ctrl_bound so clusterer can tell whether a controller registered. Verified on all permutations: pure controller, hybrid, native-only, and both mismatches.
f93b82d to
4348580
Compare
|
Follow-up commit Since this PR is already open for review, I added this as a distinct follow-up commit rather than squashing it into the main one, so the incremental change is easy to review and the existing review isn't disrupted by a force-push of the main commit. It enforces consistency between
Hybrid environments are unaffected. |
…ples
Reviewed all config examples so every cluster is clearly and self-containedly
defined, per reviewer feedback:
- Show modparam("clusterer","cluster_id",N) for each controller-managed cluster
in the full-config and multi-cluster examples (previously several relied on
the implicit auto-create-on-capability-registration path, so the cluster
never appeared "defined" in the snippet).
- Hybrid DB example: note that native cluster 10 is defined by rows in the
clusterer DB table (not a modparam), and fix the misleading "this node id in
cluster 10" comment (my_node_id is a single global id across all DB clusters).
- Add the missing "Hybrid, no DB" (static) example to the admin guide, with the
required db_mode=0 (without it my_node_info/neighbor_node_info are ignored).
- Comment use_controller as the global switch throughout.
No behavior change - documentation only. README regenerated.
Add a per-cluster 'cluster_options' modparam - the same "key=value, key=value"
idiom as my_node_info - so a cluster is marked controller-managed with:
modparam("clusterer", "cluster_options", "cluster_id=1, use_controller=1")
cluster_id is required; use_controller is a 0/1 flag defaulting to 0 (native),
and only use_controller=1 pre-creates the controller-managed stub (which never
touches the DB and is guarded against hijacking a native cluster of the same
id). Native clusters need no cluster_options line at all. Every other clusterer
setting (db_mode, ping_*, my_node_id, sharing_tag, ...) stays a global modparam.
The controller-managed ids and the clusterer_controller 'cluster' entries must
match EXACTLY. clusterer_controller aborts at startup, naming the offending id,
if either side references a cluster the other does not:
- a managed id with no 'cluster' config has no BIN socket or crypto params;
- a 'cluster' config for an unmanaged id has nothing legitimate to drive.
The controller loads the clusterer's controller-managed id set through the ctrl
binds (managed_count/managed_ids) to run this check pre-fork.
The interim 'use_controller'/'cluster_id' int modparams (never released) are
kept registered only to fail with a migration hint.
Docs (admin guide, tests appendix, README) rewritten to the cluster_options
form; every example gives each cluster an explicit definition.
82e123e to
b7a173e
Compare
|
Config API for controller-managed clusters is now the per-cluster Same The controller-managed ids and the Verified locally (the build links wolfSSL, so the controller runs without a node): the new syntax loads, a managed id with no controller config aborts, a controller config for an unmanaged id aborts, and matching config starts. Docs (admin guide, tests appendix, README) and the PR description are updated to this form. |
…ude clusterer_controller by default
Make clusterer_controller an opt-in module and ensure the bundled clusterer
module is completely unchanged when it is not built.
Build wiring:
- Add clusterer_controller to exclude_modules in Makefile.conf.template, so a
stock build skips it (like the other modules with external-lib deps). Enable
it via include_modules.
- The top-level Makefile exports CLUSTERER_CTRL_SUPPORT=1 iff clusterer_controller
is in the configured build (mirrors the module-selection rule, so it is stable
across 'make all' and single-module rebuilds); clusterer/Makefile turns that
into -DCLUSTERER_CTRL_SUPPORT.
clusterer side, all under #ifdef CLUSTERER_CTRL_SUPPORT:
- the clusterer_ctrl API (clusterer_ctrl.c) and the cluster_options /
use_controller / cluster_id modparams + load_clusterer_ctrl_binds export;
- the controller stub pre-create loop, the child_init guard, the shm current_id
mirror, the on-demand stub, and the shtag_managed / controller_managed logic.
- The per-cluster identity and hybrid-db_mode accessors (cluster_self_id,
cl_db_mode, GET_CURRENT_ID, use_controller) get #else fallbacks to the stock
globals (current_id / db_mode / 0), so their call sites compile to the exact
upstream object code with no per-site #ifdef. add_node_info's internal self_id
parameter is likewise gated (falls back to current_id).
Result: a build without clusterer_controller produces the stock clusterer module -
no cluster_options parameter (rejected as unknown), no behavioural change, no added
exports. Verified with unifdef -UCLUSTERER_CTRL_SUPPORT against the base: no semantic
difference from upstream. Enabling the controller rebuilds clusterer with the hooks;
the two are a matched pair.
Docs: new "Building the Module" section (admin guide + README).
|
Follow-up Previously the clusterer-side integration (the
So clusterer_controller can be completely omitted — a build without it produces the stock upstream clusterer module: no Verified with |
… is present
The libsodium build previously still linked the bundled static wolfSSL for
X25519, HKDF-SHA256 and the RNG. Static linking pulled in megabytes of
unrelated wolfSSL code via internal dependency chains: the module's own code is
~100 KB, yet the .so was 5.5 MB - including a 1.27 MB TLS session cache and
~1.26 MB of ECC tables (p256/p384/p521/p1024) for curves the module never uses.
With libsodium detected the module is now built sodium-only:
- X25519: crypto_scalarmult / crypto_scalarmult_base (scalar clamped
internally per RFC 7748; all-zero shared secrets from low-order peer
points are rejected);
- HKDF-SHA256: a local RFC 5869 construction on crypto_auth_hmacsha256
(libsodium 1.0.18 has no native HKDF; every use in the module needs
exactly 32 output bytes, so expand is a single HMAC iteration) -
verified against the RFC 5869 A.1 test vector;
- RNG: randombytes_buf via a new cc_random_bytes() helper; workers call
randombytes_stir() after fork.
The Makefile links wolfSSL only in the no-libsodium fallback (AES-256-GCM +
scrypt, unchanged). Module .so size: 5,571,656 -> 337,232 bytes (-94%), with
libsodium linked dynamically (target hosts need the runtime package, e.g.
libsodium23 - already required by the sodium suite before this change).
No wire-format change within either suite; the suites remain mutually
incompatible as before. Verified: both flavors build; a local two-node
cluster on the sodium build forms end-to-end (Argon2id bootstrap, JOIN_REQ ->
KEY_GRANT X25519 wrap/unwrap across processes, HKDF session key, XChaCha AEAD,
sticky election designating the backup).
Docs: dependencies/building/security sections updated; README regenerated.
No behaviour change; a code-quality pass on the single-file module. - cc_seal_and_send(): every one of the ten packet senders repeated the same ~13-line tail (encrypt in place, build the multicast sockaddr, sendto, error log). Factor it into one helper. The multicast destination is now resolved once per cluster in mod_init (main process) into cl->mcast_dest and inherited by the forked workers - so it no longer rebuilds inet_addr()/htons() on every send, and mod_destroy's GOODBYE (which runs in the main process) uses the same path. Senders keep only their own success log via the helper's return value. - cc_peer_by_ip_locked(): the "find a peer entry by IP" scan was open-coded in many places; add a helper and use it where the lookup is standalone (cc_upsert_peer_locked, cc_update_peer_bin_locked). The fused election / member-list / prune loops are left as-is. - cc_recv_one(): reuse the is_bootstrap flag instead of re-memcmp'ing the packet magic three more times; drop the unreachable payload_len < 0 check (the minimum-length gate at the top already guarantees it is non-negative). Verified on a local two-node sodium cluster: join via KEY_GRANT + NODE_ASSIGN, sticky backup designation, master-death failover promotion, and graceful GOODBYE on shutdown - zero controller errors. Both build flavors (sodium-only and wolfSSL fallback) compile clean.
Devel-specific changes
Everything below this section describes the feature as a whole. This section
collects the parts that are specific to the devel/4.1 branch — the core-API
adaptations, plus a few robustness/log fixes made while validating it on
hardware.
Port adaptations (devel core API)
socket_inforefactor.cc_discover_bin_sockets()iteratesprotos[PROTO_BIN].listenersasstruct socket_info_full(withnext/prev)and reads the embedded
socket_info— the socket-list change that landed ondevel.
clustereredits. The core edits are merged onto devel'sclusterer.c/clusterer_mod.c/node_info.h. They combine cleanly withdevel's new inter-cluster
bridgesfeature and theclusterer_enable_reroutingguard — the receive-path "is this for me?"check is now
dest_id != cluster_self_id(cl)and honours the reroutingguard. Per-cluster identity (
cluster_self_id()) is used everywhere a nodemust know its own id in a specific cluster.
clusterer_controllerandthe
clusterermodule — no OpenSIPS core files are modified.sodium-only (XChaCha20-Poly1305 + Argon2id, and X25519 / HKDF-SHA256 /
RNG from libsodium too — WolfSSL is not linked, keeping the module binary a
few hundred KB instead of several MB); without it, WolfSSL provides the
fallback (AES-256-GCM + scrypt). All nodes in a cluster must be built the
same way.
The
clusterermodule is a strict no-op unless at least one cluster isregistered as controller-managed via a
cluster_optionsline withuse_controller=1; the controller is opt-in.Startup stabilisation & log hygiene (devel-only fixes)
A near-simultaneous cold start always converged, but was noisy. Four fixes make
it clean and deterministic:
clusterer_controller: bootstrap vs session decrypt failures.cc_decrypt_pktnow distinguishes a bootstrap-key failure (a realJOIN_REQ→ genuinely wrong password / foreign cluster / tampering → staysWARN) from a transient session-key mismatch during a (re)key or split-brainheal (→
DBG). A healthy start no longer logs alarming "wrong password ortampered" lines.
clusterer_controller: no premature self-promotion. The split-braindefer budget resets on a fresh higher-IP
JOIN_REQ, so a lower-IP node keepswaiting for a demonstrably-live higher-IP peer to take master instead of
self-promoting into a divergent-key split brain. A new absolute cap
(
CC_JOIN_DEFER_HARDMAX) still guarantees termination if a peer is stuckjoining forever.
clusterer_controller:JOIN_REQrate-limit (CC_JOIN_REQ_MIN_US) so akey-mismatch burst cannot flood the multicast group.
clusterer: seed sync-fallback is not an error. On a fresh start a seednode queues a capability sync (e.g.
dialog-dlg-repl), finds no peer withdata, and after
seed_fb_intervalfalls back to synced.sync_check_timerlogged this at ERROR ("Sync request aborted! (no donor found in due
time)") — but that is the seed fallback working as designed, so it is
downgraded to
DBG. The genuine partial-sync failure path (theSYNC_IN_PROGRESStimeout) is unchanged.Net effect on a simultaneous 3-node start: "wrong password" warnings several →
0; nodes wrongly self-promoting → only the highest-IP node;
JOIN_REQseen ~30+ → ~5; sync
ERRORs several → 0. Wrong-password rejection isunchanged (the mismatched node still defers then shuts down, and the healthy
cluster is undisturbed).
Hybrid clusters (native + controller in one instance)
A single instance can run DB-native / statically-provisioned clusters and
controller-managed clusters side by side (e.g. a fixed DB replication
cluster alongside a zero-config controller HA cluster). A
cluster_idisexclusively one kind or the other; declaring the same id both ways is
rejected at startup. See Changes to the
clusterermodule → hybrid below forthe rules and config examples.
Validated on devel:
db_mode=0, staticmy_node_info) +controller cluster 1 both initialise; the controller pre-creates its
cluster-1 stub and never touches the DB path of cluster 10.
aborts module init with a clear error, so the ambiguity can never reach
runtime.
Overview
This PR introduces
clusterer_controller, a new OpenSIPS module that drives the existingclusterermodule's topology automatically at runtime. Rather than replacing the clusterer, it acts as a control plane on top of it — dynamically adding and removing nodes, electing a master, and managing sharing tag failover, without requiring a database, static node lists, or manual configuration.The
clusterermodule itself is unchanged in its normal mode of operation. For any cluster without acluster_optionsuse_controller=1line, the clusterer behaves exactly as before — DB-backed or static neighbor config, standard sharing tag event routes and MI commands, no multicast involvement whatsoever. The controller is strictly opt-in, per cluster.Peer discovery is done via authenticated, encrypted UDP multicast (AES-256-GCM by default; XChaCha20-Poly1305 + Argon2id when the module is built against libsodium). Nodes announce themselves on a shared multicast group and elect a master deterministically (master / backup / member roles, see below), and the master assigns node IDs and maintains the member list. All of this is fed into the
clusterermodule at runtime through a newclusterer_ctrlAPI, so every existingclustererconsumer (dialog, usrloc, dispatcher, etc.) works without any changes to how they use the clusterer.By default, multicast operates within a single LAN segment. For multi-site deployments, discovery can be extended across routable networks using multicast routing protocols such as PIM-SM (Protocol Independent Multicast — Sparse Mode) or similar services, provided the network infrastructure supports it.
The result is a fully identical config across all nodes — the only difference between machines is the BIN socket IP address.
How it works
Each node joins a multicast group and broadcasts a
JOIN_REQ. The master responds with aKEY_GRANT(handing the joiner the cluster session key) andNODE_ASSIGNpackets that allocate anode_idto every member and feed it into theclusterermodule via theclusterer_ctrlAPI. The master periodically broadcastsMEMBER_LISTso late joiners and re-joiners converge quickly, and a 1-secondMASTER_ALIVEkeepalive lets peers detect master failure within ~3 seconds.Each cluster has three roles: master (the active coordinator), backup (the standby that takes over on master failure — always the highest-IP non-master) and member. Election is deterministic across nodes and needs no negotiation round-trips. The
master_stickinessparameter (default1) keeps a live master in place: a higher-IP node that joins becomes the backup rather than preempting the master, so joins cause no handover (the previous backup simply drops to member if the newcomer has a higher IP). Withmaster_stickiness=0the highest-IP node always becomes master.On master failure — graceful
GOODBYEor keepalive timeout — the backup is promoted immediately. Because the session key is generated once at cluster bootstrap and preserved across every master change, the new master reuses the key every member already holds: no re-keying and no re-join storm.Split-brain is prevented and healed by three cooperating mechanisms:
JOIN_REQs, so at the join deadline a node that has seen a higher-IP starter defers self-promotion (bounded) and joins it instead. Only the highest-IP starter becomes master, so independent-key lone masters never form in the first place.MASTER_ALIVE; the lower-IP one yields.MASTER_ALIVE, so each emits a bootstrap-keyMASTER_BEACON(readable by any correctly-configured node). On hearing a beacon from a superior partition (larger member count, ties broken by higher IP), a node re-joins that master and adopts its key, converging the whole cluster onto one master and key.Because node identity and peer lists are injected into
clustererat runtime, no DB reads or staticneighbormodparams are needed. All existing clusterer consumers continue to work transparently.Node state machine
Each cluster's worker runs its own copy of this state machine (state lives in shm —
cl->peers->node_stateplus theis_master/is_backuprole flags):stateDiagram-v2 [*] --> Joining : worker start Joining --> Joining : defer and retry (higher-IP peer joining / transient auth failures) Joining --> Member : KEY_GRANT / MEMBER_LIST Joining --> Master : join deadline + highest IP (bootstrap, generates session key) Joining --> Terminated : JOIN_REJECT targeted at us, or auth failures after defer budget Terminated --> [*] : exit(-1) state "Active (CC_NODE_ACTIVE)" as Active { Member --> Backup : elected backup (highest-IP non-master) Backup --> Member : displaced by higher-IP joiner Backup --> Master : master dead ~3 s / GOODBYE / KEY_HANDOFF Member --> Master : election win (no backup, or stickiness=0 preemption) Master --> Member : superior master seen / beacon merge (re-JOIN, adopt winner's key) } Active --> [*] : GOODBYE (graceful shutdown)Joining (
CC_NODE_NEW) — entered at worker start. The node multicastsJOIN_REQ(rate-limited) and is receive-only: it never sendsALIVEorMASTER_ALIVE. Three ways out:KEY_GRANT(session key handed over;node_idarrives viaNODE_ASSIGN) or aMEMBER_LISTfrom the current master.query_time) expires with no master answering and this node is the highest-IP joiner — it self-promotes and generates the cluster session key (bootstrap). The defer and retry self-loop is what prevents split-brain here: if a higher-IP peer is also still joining, or auth failures might be transient, the node re-arms the deadline (bounded by the defer budget) instead of promoting.JOIN_REJECTtargeted at this node (wrong password oron_config_mismatch=reject), or the deadline passing with the undecryptable-packet threshold hit after the full defer budget — the "wrong password?" shutdown.Active (
CC_NODE_ACTIVE) — the three roles are the same state, differing only in duties (member/backup sendALIVEeveryquery_time; the master also sends the 1-secondMASTER_ALIVE,MEMBER_LIST,NODE_ASSIGN,KEY_GRANTand the periodic bootstrap-keyMASTER_BEACON):MASTER_ALIVE, ~3 s), a gracefulGOODBYE, orKEY_HANDOFF. The session key is preserved across the handover, so no re-key storm.master_stickiness=0. With stickiness on (the default), a live master is never displaced by a joiner.MASTER_BEACONorMASTER_ALIVEfrom a superior master (larger member count, tie broken by higher IP) demotes this one, which re-joins to adopt the winner's key while staying active.Not drawn to keep the diagram readable: an active node that sees session-key mismatches from its own master sends a re-key
JOIN_REQwithout leaving the active state.New module: clusterer_controller
Key parameters
cluster(repeatable, required) — defines a cluster to participate in. Value is a comma-separated key=value string:id=N— positive integer cluster identifier, must match thecluster_idused by clusterer consumers (dialog, usrloc, etc.)multicast=A.B.C.D:PORT— IPv4 multicast group and UDP port. Address must be in the 224.0.0.0/4 range. Two clusters on the same LAN can share the same address with different ports, or use entirely different addresses — both isolate traffic correctly.password=STRING— per-cluster shared secret; falls back to the globalpasswordmodparam if not setbin_socket=bin:IP:PORT— BIN socket to advertise to clusterer peers for this cluster; required when multiple clusters are definedmanage_shtags=0|1— per-cluster override for automatic sharing tag failover; falls back to the globalmanage_shtagsmodparam if not set, regardless of modparam order in the config filepassword(default:3eCrEt*5629) — the shared cluster secret. A per-cluster bootstrap key is derived from it with a memory-hard KDF (scrypt, or Argon2id in the libsodium build); the session key is agreed via X25519 ECDH (see Security). All nodes in a cluster must use the same password. Change this in production.manage_shtags(default:1) — global default for automatic sharing tag management. Can be overridden per cluster via themanage_shtags=key in theclusterstring.master_stickiness(default:1) — controls whether a live master is kept when a higher-IP node joins.1(sticky) = the master stays and the higher-IP joiner becomes the backup, minimising handovers;0= the highest-IP node always becomes master. Global default, overridable per cluster via themaster_stickiness=key in theclusterstring.query_time(default:5) — heartbeat interval in seconds. Controls the election window (3 × query_time) and the peer purge window (6 × query_time). Valid range: 1–60.on_config_mismatch(default:reject) — policy when a node's consistency-critical settings (manage_shtags,master_stickiness,query_time) differ from the running cluster:reject(refuse the join, node shuts down),warn(join but logCONFIG MISMATCH), oradopt(adopt the cluster's settings at runtime). See Security.my_ip(default: auto-detected) — pin the controller identity to a specific local IPv4 address. Useful on multi-homed hosts.interface(default: auto-detected) — pin the controller to a named network interface (e.g.eth0). Ignored ifmy_ipis set.Automatic sharing tag management (
manage_shtags)When
manage_shtags=1(the default), the controller master is the single authority for sharing tag state in theclusterermodule. No script-level event routes or MI commands are needed to handle failover:backupstate regardless of the=activevalue in the clusterer config. This prevents a restarting node from stealing the active tag from a running cluster.query_time × 3seconds with no master response.manage_shtags=1, theclusterer_set_tag_activeMI command and$shtag()script variable setter are blocked for controller-managed clusters, preventing accidental conflicts with automatic failover.manage_shtagscan be set globally and overridden per cluster, regardless of the order modparams appear in the config file:Minimal config (identical on all nodes, only BIN socket IP differs)
Multiple clusters
Clusters are isolated by their multicast address and/or port, so you can use the same multicast address with different ports, or entirely different addresses — both work:
Each cluster runs an independent controller worker process with its own election, membership, and sharing tag state. Packets from different clusters never mix: every packet carries a 2-byte cluster_id in its cleartext header, and a node silently drops any packet whose cluster_id differs from its own before decryption — so multiple clusters can even share the same multicast address and port without interfering, and foreign traffic never trips the wrong-password machinery. Two clusters merge only if they are configured identically (same address, port, cluster_id and password).
MI commands
cl_ctr_list_members— list the current members of each cluster with theirnode_id, status (master/backup/member) and BIN sockets.cl_ctr_node_info node_id=N— full info for a specific node across all clusters.cl_ctr_list_config— list every configured cluster and its resolved effective settings (multicast, my_ip, bin_socket, query_time, master_stickiness, manage_shtags,shtag_mode, member_count). The password is never exposed. Useful for confirming a per-cluster override took effect.cl_ctr_shtag_force cluster_id=N node_id=M— pin the active sharing tag to a chosen node, overriding automatic master-driven allocation (master-only). The override is carried inMEMBER_LIST, survives master fail-over, and auto-clears if the forced node departs.shtag_modethen reportsoverride:M.cl_ctr_shtag_auto cluster_id=N— clear the override and resume automatic, master-driven sharing-tag allocation (master-only).Script variables
Read-only pseudo-variables expose live cluster state to the routing script (read from shared memory, so available in every process — SIP workers included), so a check like only the master runs this job needs no MI round-trip. Each takes an optional cluster id: the bare form (
$cl_ctr_role) resolves the sole configured cluster, while an explicit id ($cl_ctr_role(2)) reads any specific cluster — so a node that participates in several clusters can query each one independently. With more than one cluster defined the bare form returns NULL and logs a one-time warning, so the cluster must be named.$cl_ctr_role—master/backup/member/joining$cl_ctr_is_master—1/0$cl_ctr_master_ip,$cl_ctr_backup_ip— current master / backup IP (NULL if none)$cl_ctr_node_id— this node'snode_idin that cluster (a node may hold different ids in different clusters)$cl_ctr_my_ip,$cl_ctr_members— controller identity IP; live member count$cl_ctr_shtag_mode(auto/forced),$cl_ctr_forced_node— sharing-tag allocation mode and pinned node idThe convention is queries are nouns (variables), actions are verbs (MI commands): this node's own state is read through the variables above and changed through MI (
cl_ctr_shtag_force/cl_ctr_shtag_auto). Script action functions (verbs — e.g.cl_ctr_set_maintenance()for a node to change its own state from the routing logic) are planned together with node maintenance mode; see the Roadmap.Input validation. The optional cluster-id key is parsed at config load: a non-numeric, negative, zero, or out-of-range value (capped at 9 digits so it can never overflow into a valid-looking id) is rejected with a descriptive error and fails the config check rather than binding to the wrong cluster. The per-peer functions below are equally defensive at runtime — an out-of-range, negative, or non-numeric argument passed via
$varresolves to not-found rather than faulting.Script functions
Per-peer lookups take two arguments
(cluster_id, node_id)and so are functions (a comma inside a pvar's parens is ambiguous once the pvar is used as a function argument). Booleans return true/false forif(); value lookups write an output variable:cl_ctr_node_is_master(cluster_id, node_id)— true if that node is mastercl_ctr_node_present(cluster_id, node_id)— true ifnode_idis a live membercl_ctr_get_node_role(cluster_id, node_id, $out)— writesmaster/backup/membercl_ctr_get_node_ip(cluster_id, node_id, $out)— writes that node's IPSecurity
cluster_id, and the nonce — everything meaningful (type, seq, IPs, pubkeys, salts, member lists) is inside the sealed payload. The magic andcluster_idare bound into the AEAD tag as AAD, so a captured packet can't be re-stamped onto anothercluster_idon a shared multicast+password group. The AEAD is AES-256-GCM (WolfSSL) by default, or XChaCha20-Poly1305 when built against libsodium (its 192-bit nonce removes any random-nonce collision concern) — a build-time choice; all nodes in a cluster must match, and the active suite is logged at startup.JOIN_REJECTafter repeated bootstrap-decrypt failures. A wrong-password node can't read that reject, so it also self-detects — while joining it counts undecryptable packets from other peers and, at the join deadline, shuts down ("cannot authenticate — wrong password?") instead of self-promoting into a lone split-brain master. An active member ignores JOIN_REJECT, so a correct-password peer can never be evicted. A full peer table rejects new spoofed-IP joins.manage_shtags,master_stickinessandquery_time— a per-node mismatch would otherwise cause silent, inconsistent failover/sharing-tag behaviour (e.g. a master withmanage_shtags=0leaves no node holding the active tag). Each node advertises these effective settings in its ALIVE heartbeat and JOIN_REQ; theon_config_mismatchmodparam picks the policy when a node tries to join an established cluster with different settings:reject(default) — the master returns a JOIN_REJECT and the misconfigured node shuts down with a clear message;warn— the node joins but a single deduplicatedCONFIG MISMATCHwarning is logged;adopt— the joining node adopts the running cluster's settings at runtime (andcl_ctr_list_configthen reports the adopted values).node_idallocation & identity: ids are allocated only by the current master, serialised under the peer-table lock — a joining node never picks its own. The master hands out the lowest unused id from the live peer table, so a node that has failed but not yet timed out still holds its slot and its id is never reused for a different joiner — new nodes get a distinct id even during the failure-detection window. A node that restarts and rejoins from the same address reuses its previous id (and its replay counter is reset), so ids stay stable across restarts. Peers are keyed by source IP, so each node must present a stable, unique source address: two nodes behind one address (e.g. NAT) would share a slot/node_id.MASTER_ALIVEand beacons fail the AEAD tag or the per-source sequence check and are dropped before any election logic runs); the residual exposure is a malicious insider that already holds the key. Per-node keypairs with enrolment/revocation — distrust one node without re-keying the cluster — are on the Roadmap.Changes to the
clusterermoduleOpt-in build — zero change to stock clusterer
clusterer_controlleris excluded from the default build (added toexclude_modulesinMakefile.conf.template), like the other modules with external-library dependencies. You enable it by adding it toinclude_modules:All of the clusterer-side integration below (the
clusterer_ctrlAPI, thecluster_optionsmodparam, and every Phase-0/Phase-1/controller hook) is compiled only when clusterer_controller is part of the build. The top-level Makefile detects that and passes-DCLUSTERER_CTRL_SUPPORTto the clusterer module; a small self-contained wiring inclusterer/Makefileacts on it.If clusterer_controller is not built, the clusterer module is the stock upstream module — same behaviour, same exported parameters and commands. Verified with
unifdef -UCLUSTERER_CTRL_SUPPORTagainst the base: the stock-preprocessed source has no semantic difference from upstream (the only textual residue is call sites using accessor macros that expand to the upstream globals, e.g.cluster_self_id(cl)→current_id). Concretely, in a stock buildclusterer.socontains nocluster_optionsstring and rejects the parameter as unknown; a nativemy_node_info/DB config loads unchanged. Enabling the controller rebuilds clusterer with the hooks — the two are always a matched pair.New controller API (
clusterer_ctrl)A new
clusterer_ctrl.c/.hpair exposes a load-time API (load_clusterer_ctrl_binds) through which an external module can drive theclusterertopology at runtime:set_my_identity(cluster_id, node_id, bin_url)— register this node's identity post-forkadd_node / remove_node— add/remove peers at runtimeupdate_identity— correct node_id after master assignmentsync_current_id— sync process-localcurrent_idafter forkactivate_backup_shtags / force_backup_shtags— sharing tag controlset_shtag_managed— lock a cluster's tags against manual changescluster_options/use_controllermode and hybrid topologiesEach
modparam("clusterer","cluster_options","cluster_id=N, use_controller=1")registers clusterNas a controller-driven stub at startup; its identity and peer list are filled in post-fork by the controller — no DB or static neighbor config for those. Any cluster without such a line is completely unaffected: DB loading, static neighbors, sharing-tag event routes and MI commands all work exactly as before.use_controlleris a per-cluster option carried incluster_options(default0). So one instance can run native clusters (DB-backed or staticmy_node_info/neighbor_node_info) and controller-managed clusters side by side. Each cluster is flaggedcontroller_managed(acluster_optionsline setuse_controller=1) or native; a controller cluster always behaves asdb_mode=0even when native clusters are DB-backed (cl_db_mode(cl)), the two kinds share onecluster_idnamespace, and declaring the same id both ways is rejected.my_node_id/db_urlare required only when native clusters exist. This lets a fixed DB-provisioned replication cluster coexist with a zero-config controller HA cluster in one process — see Hybrid Topologies in the admin guide.Config examples:
Controller-only — two controller clusters sharing one BIN socket:
Hybrid — a DB-native cluster 10 next to a controller cluster 1:
Hybrid, no DB — a static native cluster 7 next to a controller cluster 1:
Here
my_node_id=5is this node's id in the native cluster 7; in cluster 1 the controller assigns an id at runtime, which may differ.Per-cluster node identity (
node_id/cluster_id)Every clusterer packet already carries a
cluster_id, and each cluster keeps its own membership. The change here is how a node's own identity is represented.Before. A node's identity was a single global
current_id(themy_node_idmodparam). Classic clusterer works because an operator gives a node the samenode_idin every cluster it belongs to —add_node_info()finds "me" in each cluster by matchingnode_id == current_id, and every runtime check (the "this message is from myself" source check, outgoing id stamps, topology and capability comparisons,cl_get_my_index) reads that one global.The problem the controller introduces. Each controller cluster's master allocates
node_ids independently (lowest free id in that cluster). So the same node can legitimately benode_id=1in one cluster andnode_id=2in another — the ids diverge. A single globalcurrent_idcannot represent that:clusterer_ctrl_sync_current_id()collapsed it to the first cluster's value, so for every other cluster the node mis-identified itself. Concretely, a peer whose id equalled the stale global was treated as "me" (and vice-versa), and outgoing packets were stamped with the wrong source id — silently breaking replication for the divergent cluster. This also affected two controller clusters with different membership, not just hybrids.The change. Identity is now per-cluster. The authoritative source is
cl->current_node->node_id, which already lives in shared memory, exposed through a small accessorcluster_self_id(cl)(returns-1— matches no node — before this cluster's identity is established). Specifically:add_node_info()takes an explicitself_idfor the self/peer decision instead of reading the global; native load/provision passmy_node_id(unchanged behaviour), the controller and runtime-topology callers pass the per-cluster id.cl_get_my_index— usescluster_self_id(cl).msg_add_trailer()stamps the source id per cluster.The legacy global
current_id/GET_CURRENT_IDremains only on the native DB/static provisioning path (where a node uses one id across all its clusters, by the operator's own configuration) and for theget_my_id()API. Result: within a hybrid or multi-controller-cluster instance,cluster_idselects the cluster andnode_idis meaningful within that cluster, independently — validated live with a node holdingnode_id=3in one cluster andnode_id=2in another, replicating cleanly in both.Testing
Built against OpenSIPS 4.1.0-dev (clean
make all; crypto suiteXChaCha20-Poly1305 + Argon2idvia libsodium). Modules load against the freshcore with no version-control mismatch and initialise cleanly. All scenarios
below were validated end-to-end on a live 3-node cluster (
10.22.23.191–193)with dialog replication and sharing-tag failover:
make all(core + all non-excluded modules); modules load with no version-control mismatch; BIN socket discovered viasocket_info_full; crypto initialised, no leaks/crasheskill -9)master_stickiness=1the current master stays put; no tag disruptionmaster_stickiness=0MASTER_BEACON; ~5 JOIN_REQ total, 0 spurious "wrong password" warningscluster_optionsuse_controller=1line, staticmy_node_info: clusterer mesh up, static shtag, no auto-promote on node loss (native semantics)id=1,id=2) on distinct multicast endpoints share onebin:IP:3857: both form independently, both BIN linksUp, 0 decrypt/cross-talk errors (each BIN packet'scluster_iddemuxes); two clusters on the same multicast are rejected at startupcannot authenticate … wrong password?) instead of forming a lone split-brain master; live cluster undisturbed (0 session-mismatch/demote); a corrected node rejoinstest/cc_join_reject_test.py)JOIN_REJECT; a fake-MASTER_ALIVEflood is ignored (no re-JOIN churn)cl_ctr_shtag_forcepins the active tag to a non-master (all nodes reportoverride:N), survives a masterkill -9, auto-clears when the forced node departs;cl_ctr_shtag_autorestores; error paths rejectedcl_ctr_list_members/node_info/list_config/shtag_force/shtag_autocorrect; error paths non-master 409, bad node 404, bad cluster 404on_config_mismatch=reject: divergentmanage_shtagsnode rejected and self-shuts-down; reverting lets it rejoinFull failover walk-throughs are in
modules/clusterer_controller/doc/clusterer_controller_tests.xml.Note on MI access under 4.1
opensips-cli0.3.3 cannot drive the 4.1 MI interface (it misparses the commandlisting and reports
no command '<x>' in module 'mi'even for core commandslike
uptime). Until the CLI is updated, use themi_httptransport, e.g.:(the
httpdlistener binds the node IP, not loopback). This is atooling-version issue, not a module or core defect.
Limitations (alpha)
query_time— but strict NTP is not required for correctness; replay protection is sequence-number based, not time-window basedRoadmap (not in this PR)
Planned follow-ups (also documented under Planned Features in the admin guide):
Node maintenance mode — take a node out of duty for a rolling upgrade while it stays in the cluster (keeps replicating, answers pings, stays in
cl_ctr_list_members) but is excluded from election and sheds its sharing tags (acl_ctr_shtag_forcepin auto-clears). Two levels:evicted(out of election/tags; the script refuses new work while dialogs finish) andfull(additionally marks the node down for clusterer consumers). State is cluster-wide (carried in ALIVE/MEMBER_LIST, survives failover) and runtime-only. Interfaces: MIcl_ctr_maintenance(any node, master propagates), script functioncl_ctr_set_maintenance(), read-only vars$cl_ctr_maintenance/$cl_ctr_node_maint(cid,nid)($cl_ctr_rolegains amaintenancevalue), and eventE_CL_CTR_MAINTENANCE.Statistics — role, member count, master changes, joins/leaves,
JOIN_REJECTs, decrypt failures, config mismatches, split-brain merges viaget_statistics/monitoring.Events —
E_CL_CTR_*raised on state transitions (became master, demoted, node joined/left, split-brain merged, config mismatch, auth reject) forevent_route/subscribers.Per-node identity & stronger admission crypto — move beyond the single shared secret to per-node keypairs with enrolment and revocation, so one node can be distrusted without re-keying the whole cluster (closing the insider-trust limitation noted under Security). Candidate directions: a standard handshake (Noise) for admission, and a PAKE (CPace/SPAKE2) to remove offline password-guessing on captured bootstrap packets.
IPv6 multicast — the control plane currently uses IPv4 multicast (groups in
224.0.0.0/4). Add IPv6 multicast support (ff00::/8groups,AF_INET6sockets and membership) so the controller can run on IPv6-only or dual-stack deployments.