salt.cache._cluster_replicator#
Cross-master cache replication seams.
Free-function entry points for both sides of the delegate-cache-write
flow so each side is testable without instantiating a channel class
or a Cache object. Cache.store and Cache.store_many emit via
fire_peer_cache_write() / fire_peer_cache_write_many() /
fire_delegate_cache_write();
MasterPubServerChannel._handle_delegate_cache_write delegates to
_handle_delegate_cache_write().
- class salt.cache._cluster_replicator.PendingEvent(kind: str, event: bytes, tag: str, bank: str | None = None, key: str | None = None, minion_id: str | None = None, cluster_aes_fp: str = '<unavailable>', enqueued_at: float = <factory>)#
One deferred replication event awaiting a peer's handshake.
The
eventbytes are the pre-packed,cluster_aes-encrypted payload that would have been passed topusher.publish(...); enqueuing stores the exact bytes so the flush path is a trivial publish without re-encrypting.kindis a short string ("cache", "resource") used only for log attribution.tagis the salt event tag the payload was packed under (useful for diagnostics).bank/key/minion_idare optional human-readable attribution fields -- they are NOT used by the flush path, only by the skip/drop logs.cluster_aes_fpis thesecret_fingerprintof the cluster_aes value that was current at encrypt time. The flush path compares it to the current cluster_aes fp; mismatch means a rotation happened between encrypt and flush (D-1b window) and the entry is dropped with a WARN (receiver would log a silent decrypt-fail otherwise). Defaults to"<unavailable>"so legacy tests / callers that construct PendingEvent without stamping still work (but see reviewer Q3:<unavailable>on EITHER side drops the entry, never publishes).
- salt.cache._cluster_replicator.drain_pending_for_peer(peer_host, opts=None)#
Atomically remove and return the list of pending events for
peer_host, filtering out any that have exceeded their TTL.The caller is responsible for publishing the drained events. If publication fails for an entry, the caller should
enqueue_pending()it back (preserving FIFO order via sequential re-enqueue is still FIFO because this function returns the full prefix).- Returns:
list of
PendingEventin FIFO order.
- salt.cache._cluster_replicator.drop_all_pending(reason='cluster_aes changed')#
Discard every pending entry across every peer and return the total number of entries dropped.
Called whenever the local
cluster_aesis replaced: either on operator-triggered rotation (SMaster.rotate_cluster_secret()) or on the initial install reached viacluster/peer/join-replywhen a (re)joining master learns the cluster's existing key. In both cases every queued pre-encrypted event in_PENDING_QUEUESwas packed with the previouscluster_aesvalue and will fail to decrypt on any peer -- the receiver logs a loudFailed to decryptand the write is silently lost. Dropping the queue is the only correctness-preserving option: the entries cannot be re-encrypted (the plaintext is not retained) and forwarding them produces log-noise plus silent-loss.The caller is expected to log the context (rotation vs. initial sync) at the call site. This function emits a single WARN that names the
reasonand the aggregate drop count so an operator forensics walk-back can confirm the invalidation fired.- Parameters:
reason -- Short human string for the audit log; defaults to a generic
"cluster_aes changed".- Returns:
Total count of pending events dropped (sum across every peer queue).
0when no queues were populated.
- salt.cache._cluster_replicator.drop_pending_for_peer(peer_host)#
Discard every pending entry for
peer_host.Called by the publish daemon when a peer is observed to have left the cluster (not currently wired; retained as the correctness- preserving escape hatch for the pending-queue growth invariant).
- salt.cache._cluster_replicator.enqueue_pending(peer_host, event, opts=None)#
Append
eventto the per-peer pending queue forpeer_host.Enforces per-peer cap and TTL at enqueue time. Thread-safe. Returns the queue depth after enqueue.
- Parameters:
peer_host -- Peer's
pull_host(bare host orhost:port).event -- A
PendingEvent.opts -- Master opts dict (optional; controls cap + TTL).
- salt.cache._cluster_replicator.filter_joined_pushers(pushers, discover_replies, peer_keys, opts, context=None, pending_event=None)#
Filter
pushersdown to peers that have completed the cluster handshake.This is the single seam the publish daemon consults before emitting a cluster_aes-encrypted replication event. Peers that have not sent a
discover-replyand whose session key has not been installed cannot decrypt the event and would log a loudFailed to decrypton receive; skipping them here converts the silent-loss failure mode into a WARN on the sender side and lets the sender-side pending queue replay the write when the peer completes its handshake.Catch-up guarantee: a peer skipped by this gate is still delivered the event via the per-peer pending queue -- see
enqueue_pending()+flush_pending_for_peer(). The join-time state-sync stream (seesalt.cluster.state_sync) additionally ships whatever the peer had already missed when it started its handshake. The two mechanisms are redundant: the pending queue covers live writes during the join window; the state-sync covers the pre-join snapshot. Either alone would be sufficient; both together close the race.- Parameters:
pushers -- Iterable of
Pusherobjects (each exposespull_host).discover_replies -- Set of peer ids that have sent us
discover-reply.peer_keys -- Dict of
peer_id -> session_key.opts -- Master opts dict. Consulted for the
cluster_cache_replicate_require_joinedmaster switch -- if False, the gate is inactive and every pusher is kept.context -- Short human-readable label (e.g.
"delegate-cache-write") used only in the skip-log; may beNone.pending_event -- Optional
PendingEventcapturing the pre-encrypted payload to be replayed when a skipped peer finishes its handshake. When supplied, every skipped pusher receives a per-peer enqueue (seeenqueue_pending()).Nonerestores the "skip + warn, no replay" behaviour (used by legacy call sites and the unit tests that exercise the gate in isolation).
- Returns:
(kept, skipped)-- two lists of pushers. Callers that want pre-gate semantics can ignoreskipped; today we just warn.
- salt.cache._cluster_replicator.fire_delegate_cache_write(opts, bank, key, data, expires=None)#
Route a cache write to a single HashRing owner (1-of-N delegation).
Called when the per-bank routing resolves to
"ring"(e.g. thejobsbank by default, for backward compat with the existing ring-sharded job returner).
- salt.cache._cluster_replicator.fire_delegate_cache_write_many(opts, bank, items, expires=None)#
Batched 1-of-N ring-delegation variant of
fire_peer_cache_write_many().
- salt.cache._cluster_replicator.fire_peer_cache_write(opts, bank, key, data, expires=None)#
Fan a cache write out to every peer master (N-of-N replication).
Called by
salt.cache.Cache.store()andsalt.cache.Cache.store_many()when the per-bank routing resolves to"replicate"(the default).This is the single seam tests patch to observe fan-out intent without a real event bus.
- salt.cache._cluster_replicator.fire_peer_cache_write_many(opts, bank, items, expires=None, write_kind='replicate')#
Batched N-of-N replication: fan a list of
(key, data)pairs out to every peer master in a single event.The gate (cluster + isolated-FS + per-bank routing) is evaluated once by the caller -- all items share the same bank so routing is uniform. This cuts the per-write event cost on hot batched paths like
cache.store_manyfor resource grains.- Parameters:
opts -- Master opts dict.
bank -- The shared bank name.
items -- Iterable of
(key, data)tuples.expires -- Optional seconds-from-now expiry applied to every entry in the batch.
write_kind --
"replicate"(default, N-of-N fan-out) or"ring"(1-of-N; seefire_delegate_cache_write_many()). Used to let the receiver dispatch via the same_run_delegate_cache_writepath as the single-item events.
- salt.cache._cluster_replicator.fire_resource_register_write(opts, minion_id, resources, chunk_final=True, chunk_scope=None, chunk_index=None)#
Fire a resource-registry write event for the publish daemon to intercept and dispatch.
The MWorker handling
_register_resourcesruns this to hand the register off to the publish daemon. The daemon (salt.channel.server.MasterPubServerChannel._run_delegate_resource_register_write()) is the single place that owns the ring-vs-broadcast decision, the local-shard mmap write, and the targeted-vs-fan-out peer publish -- because theresource_indexring state only lives in the daemon process (its per-ring Raft groups aren't visible across the MWorker fork boundary).chunk_final+chunk_scope+chunk_indexcarry chunked- register metadata through to peers and the local publish-daemon writer so a multi-chunk register preserves additive mid-stream puts and defers the stale-SRN prune to the terminal chunk. Thechunk_indexfield additionally lets peer masters detect and buffer out-of-order final-chunk arrivals (publish-daemonrun_in_executorhas no FIFO guarantee across chunks). Legacy single-shot callers can omit all three fields and get pre-chunk semantics (full replace, no gap check).- Parameters:
opts -- Master opts dict (must contain
id).minion_id -- The reporting minion.
resources --
{resource_type: [resource_id, ...]}-- the exact dict that was passed to the localupdate_resource_index_chunkcall.chunk_final -- True iff this chunk ends a register window.
chunk_scope --
None/"__all__"for a legacy single- shot register, or a type name for a scoped chunked register.chunk_index -- 0-based monotonic index of this chunk within the register window.
Nonefor legacy single-shot callers.
- async salt.cache._cluster_replicator.flush_pending_for_peer(peer_host, pushers, opts=None)#
Drain the pending queue for
peer_hostand publish each entry through the matching pusher (bare-host orhost:portmatch).Replays run in FIFO order. On publish error for an entry, the remaining un-flushed events are re-enqueued at the front via
enqueue_pending()(preserves ordering), and the method returns early; the next flush attempt will retry.- Parameters:
peer_host -- Peer's
pull_host.pushers -- Iterable of
Pusherobjects.opts -- Master opts dict (for TTL re-check).
- Returns:
Count of events successfully flushed.
- salt.cache._cluster_replicator.log_decrypt_failure(tag, opts, secret, source_peer=None, extra=None)#
Correlatable, rate-limited log for a cluster_aes decrypt failure.
Called from the receiver side (
handle_pool_publish) whenCrypticle.loads()raises on an incoming cluster event. Captures the cluster identity, a short fingerprint of the local cluster_aes (never the key itself), the event tag, and whatever source-peer identifier the caller can supply (the ciphertext is opaque so source_peer may beNoneon wire arrivals).The first failure for a
(tag, source_peer)tuple in each window logs with a full stack trace (log.exception) so the operator still gets the diagnostic signal. Subsequent failures in the same window increment a suppressed-count flushed when the window expires.- Parameters:
tag -- Event tag string (e.g.
cluster/peer/delegate-cache-write).opts -- Master opts dict;
cluster_idis logged.secret -- The local cluster_aes value that failed to decrypt the event (passed in so the caller can pass a bytes value fetched under
SMaster.secrets[...]without re-fetching here).source_peer -- Optional source-peer identifier.
Noneis acceptable; cluster_aes events on the pool channel don't carry a sender id in the ciphertext envelope.extra -- Optional dict of additional key/value pairs to include in the log (e.g. write_kind, bank name on decrypted failures). Each entry is formatted
k=v.
- salt.cache._cluster_replicator.partition_resources_for_dispatch(opts, resources)#
Split
resourcesinto(local_bucket, peer_buckets, ring_active)for the publish-daemon dispatcher.Used by
salt.channel.server.MasterPubServerChannel._run_delegate_resource_register_write()inside the publish daemon process where theresource_indexring is populated. When the ring is empty, returns the fullresourcesas the "broadcast everyone" bucket and no peer buckets. When populated, splits byHashRing.get_owner().- Parameters:
opts -- Master opts dict.
resources --
{resource_type: [resource_id, ...]}.
- Returns:
(local_bucket, peer_buckets, ring_active)wherepeer_bucketsis{owner_node_id: resources_dict}for each remote owner, andring_activeis aboolindicating ring routing is in effect.
- salt.cache._cluster_replicator.peer_is_joined(discover_replies, peer_keys, peer_host)#
Return
Trueifpeer_hosthas completed the cluster discover/join handshake far enough to decrypt cluster_aes events.The handshake has two observable signals:
discover_replies-- this master has received a signedcluster/peer/discover-replyfrom the peer. That reply is sent only after the peer has installed cluster.pub locally, which in turn happens after the peer processed ajoin-reply(which carriedcluster_aes). A peer in this set is therefore guaranteed to have our currentcluster_aes.peer_keys-- this master has received the peer's session AES key via thecluster/peer/<master_id>AES-key broadcast. That broadcast is independent of the discover protocol but it ALSO only fires after the peer has installed cluster_aes (send_aes_key_eventis called from thecluster/peerhandler which itself runs after key installation). Sopeer_keysmembership is a slightly later-but-equivalent signal; we accept it to tolerate restart scenarios wherediscover_repliesis empty but the peer is fully joined.
The host match is lenient:
cluster_peersentries may carry a:portsuffix while the handshake handlers key on the bare host, so we match either form.- Parameters:
discover_replies -- Iterable/set of peer ids that have sent us
discover-reply.peer_keys -- Dict of
peer_id -> session_keyfromMasterPubServerChannel.peer_keys.peer_host -- The peer's
pull_host(orcluster_peersentry).
- Return type:
- salt.cache._cluster_replicator.pending_queue_depth(peer_host=None)#
Return the depth of the pending queue for
peer_host(or the sum of all queues whenpeer_hostisNone).Thread-safe; used by tests and operator telemetry.
- async salt.cache._cluster_replicator.publish_with_latch(peer_host, pusher, event)#
Publish
eventthroughpusherwhile holding the per-peer flush-latch.Serialises with any concurrent
flush_pending_for_peerdrain on the same peer so stale pending entries land on the peer socket BEFORE the live entry -- under last-writer-wins the peer state converges to the live entry.
- salt.cache._cluster_replicator.secret_fingerprint(secret)#
Return the first 8 hex chars of
sha256(secret)for log correlation.Never logs the full secret; the fingerprint is useful for matching an operator's
cluster_aes convergeevents against aFailed to decryptentry in the log stream. Returns"<unavailable>"ifsecretcannot be hashed (missing or wrong type).