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 event bytes are the pre-packed, cluster_aes-encrypted payload that would have been passed to pusher.publish(...); enqueuing stores the exact bytes so the flush path is a trivial publish without re-encrypting.

kind is a short string ("cache", "resource") used only for log attribution. tag is the salt event tag the payload was packed under (useful for diagnostics). bank/key/ minion_id are optional human-readable attribution fields -- they are NOT used by the flush path, only by the skip/drop logs.

cluster_aes_fp is the secret_fingerprint of 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).

bank: str | None = None#
cluster_aes_fp: str = '<unavailable>'#
enqueued_at: float#
event: bytes#
key: str | None = None#
kind: str#
minion_id: str | None = None#
tag: str#
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 PendingEvent in 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_aes is replaced: either on operator-triggered rotation (SMaster.rotate_cluster_secret()) or on the initial install reached via cluster/peer/join-reply when a (re)joining master learns the cluster's existing key. In both cases every queued pre-encrypted event in _PENDING_QUEUES was packed with the previous cluster_aes value and will fail to decrypt on any peer -- the receiver logs a loud Failed to decrypt and 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 reason and 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). 0 when 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 event to the per-peer pending queue for peer_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 or host: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 pushers down 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-reply and whose session key has not been installed cannot decrypt the event and would log a loud Failed to decrypt on 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 (see salt.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 Pusher objects (each exposes pull_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_joined master 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 be None.

  • pending_event -- Optional PendingEvent capturing the pre-encrypted payload to be replayed when a skipped peer finishes its handshake. When supplied, every skipped pusher receives a per-peer enqueue (see enqueue_pending()). None restores 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 ignore skipped; 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. the jobs bank 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() and salt.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_many for 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; see fire_delegate_cache_write_many()). Used to let the receiver dispatch via the same _run_delegate_cache_write path 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_resources runs 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 the resource_index ring 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_index carry 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. The chunk_index field additionally lets peer masters detect and buffer out-of-order final-chunk arrivals (publish-daemon run_in_executor has 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 local update_resource_index_chunk call.

  • 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. None for legacy single-shot callers.

async salt.cache._cluster_replicator.flush_pending_for_peer(peer_host, pushers, opts=None)#

Drain the pending queue for peer_host and publish each entry through the matching pusher (bare-host or host:port match).

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 Pusher objects.

  • 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) when Crypticle.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 be None on 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_id is 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. None is 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 resources into (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 the resource_index ring is populated. When the ring is empty, returns the full resources as the "broadcast everyone" bucket and no peer buckets. When populated, splits by HashRing.get_owner().

Parameters:
  • opts -- Master opts dict.

  • resources -- {resource_type: [resource_id, ...]}.

Returns:

(local_bucket, peer_buckets, ring_active) where peer_buckets is {owner_node_id: resources_dict} for each remote owner, and ring_active is a bool indicating ring routing is in effect.

salt.cache._cluster_replicator.peer_is_joined(discover_replies, peer_keys, peer_host)#

Return True if peer_host has 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 signed cluster/peer/discover-reply from the peer. That reply is sent only after the peer has installed cluster.pub locally, which in turn happens after the peer processed a join-reply (which carried cluster_aes). A peer in this set is therefore guaranteed to have our current cluster_aes.

  • peer_keys -- this master has received the peer's session AES key via the cluster/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_event is called from the cluster/peer handler which itself runs after key installation). So peer_keys membership is a slightly later-but-equivalent signal; we accept it to tolerate restart scenarios where discover_replies is empty but the peer is fully joined.

The host match is lenient: cluster_peers entries may carry a :port suffix 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_key from MasterPubServerChannel.peer_keys.

  • peer_host -- The peer's pull_host (or cluster_peers entry).

Return type:

bool

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 when peer_host is None).

Thread-safe; used by tests and operator telemetry.

async salt.cache._cluster_replicator.publish_with_latch(peer_host, pusher, event)#

Publish event through pusher while holding the per-peer flush-latch.

Serialises with any concurrent flush_pending_for_peer drain 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 converge events against a Failed to decrypt entry in the log stream. Returns "<unavailable>" if secret cannot be hashed (missing or wrong type).