Documentation
¶
Overview ¶
Package leader elects the Leader (C-02.FR-10, ADR-0007): one replica holds a session advisory lock with a constant key on a dedicated connection and runs the closed list of Leader tasks in tasks.go. The lock has a bounded lease: the Leader pings over the lock's own session and stops every Leader task as soon as a ping fails or none has succeeded for FencingTimeout, while PostgreSQL ends a silent lock session, and so releases the lock, within ServerBound. The lease runs on the real clock, so the development clock never fences a Leader.
Index ¶
- Constants
- func BoundSession(ctx context.Context, c *pgx.Conn, d time.Duration) error
- func Dial(connect func(context.Context) (*pgx.Conn, error), serverBound time.Duration) func(context.Context) (Session, error)
- func Notices(ctx context.Context, q Queries, now time.Time) ([]organization.Notice, error)
- func Register(k *Keeper)
- func Tasks(w Work) func() []Task
- type Alive
- type Downtime
- type DowntimeRecorder
- type Keeper
- type PruneTable
- type Queries
- type Session
- type Store
- type Task
- type Wakes
- type Work
Constants ¶
const ( // AliveMarkInterval is leader.alive_mark_interval: how often the Leader writes the alive mark. AliveMarkInterval = 30 * time.Second // AbsenceNotice is leader.absence_notice: an alive mark older than this means that no replica leads, and a gap // longer than this, with no replica running, is downtime. AbsenceNotice = 2 * time.Minute // The recovery window after downtime, recovery.banner_duration (P-01): until the longest repeat interval // learned from Alertmanager has passed, at most RecoveryMax; RecoveryUnlearned when nothing is learned. RecoveryMax = time.Hour RecoveryUnlearned = 15 * time.Minute )
const ( // PingInterval is leader.ping_interval: how often the Leader pings over its lock session and another replica // tries to take the lock. PingInterval = 5 * time.Second // FencingTimeout is leader.fencing_timeout: the Leader stops every Leader task when no ping succeeded for this // long. It is shorter than ServerBound, so the old Leader normally stops before another one can take the lock. FencingTimeout = 15 * time.Second // ServerBound is leader.server_bound: PostgreSQL ends a silent lock session, and releases the lock, within it. ServerBound = 30 * time.Second // LockKey is the session advisory lock of the Leader. It follows the keys of internal/db. LockKey int64 = 0x6d75_7374_6572_0003 )
const ( HeartbeatCheckInterval = 10 * time.Second StaleScanInterval = 30 * time.Second )
HeartbeatCheckInterval is how often the Leader runs the Heartbeat check, and StaleScanInterval the Stale scan.
const AlertGroupGaugeInterval = 15 * time.Second
AlertGroupGaugeInterval is how often the Leader counts the open Alert Groups for muster_alert_groups.
const BacklogInterval = 15 * time.Second
BacklogInterval is how often the Leader counts the pending Stored Snapshots for muster_ingest_backlog.
const BridgePollingInterval = 10 * time.Second
BridgePollingInterval is how soon the Leader runs the polling of Bridge events again after it stopped with an error, such as a failed read of the Connections; while it runs, it polls without pause.
const DeliveryQueueInterval = 15 * time.Second
DeliveryQueueInterval is how often the Leader counts the pending deliveries for muster_delivery_queue, reads the health of the Destinations for muster_destination_broken and the Storms of the Routes for muster_storm_active.
const MaintenanceInterval = time.Hour
MaintenanceInterval is how often the hourly Leader tasks run: partition maintenance, replica pruning, short-lived pruning, the retention of the Alerts view and the Alert Group retention, and the re-render after a key rotation, whose interval is the fallback of a lost notification.
const OIDCSecretExpiryInterval = 5 * time.Minute
OIDCSecretExpiryInterval is how often the Leader checks the expiry date of the OIDC client secret (C-19.FR-5); a change of the OIDC settings is seen at the next run.
const OutgoingHeartbeatPoll = 5 * time.Second
OutgoingHeartbeatPoll is how often the Leader looks whether the outgoing heartbeat is due; the sender measures outgoing_heartbeat.interval on the business clock, so the poll only bounds how late a send is.
const PruneBatch = 1000
PruneBatch is the most rows one delete of short-lived pruning removes, so that a large backlog is deleted in short statements that hold their row locks briefly.
const RequestLogPruningInterval = time.Minute
RequestLogPruningInterval is how often the Leader prunes the Request log to its bounds (C-23.FR-4).
const SlackSocketModeInterval = 10 * time.Second
SlackSocketModeInterval is how soon the Leader runs the Slack sockets again after they stopped with an error, such as a failed read of the Connections; while they run, they hold their connections.
const TelegramPollingInterval = 10 * time.Second
TelegramPollingInterval is how soon the Leader runs the Telegram polling again after it stopped with an error, such as a failed read of the Connections; while it runs, it polls without pause.
Variables ¶
This section is empty.
Functions ¶
func BoundSession ¶
BoundSession bounds a session connection like a lock session: PostgreSQL ends it once it has been silent for d. Partition maintenance bounds its session with it, so that the maintenance lock of a frozen process goes too.
func Dial ¶
func Dial(connect func(context.Context) (*pgx.Conn, error), serverBound time.Duration) func(context.Context) (Session, error, )
Dial returns the connector of lock sessions over connect, which opens a session connection to PostgreSQL. Each session sets idle_session_timeout and TCP keepalive parameters, so that PostgreSQL ends it once it has been silent for serverBound and releases the lock.
func Notices ¶
Notices reads the state of the Organization-wide notices at now, a business time: "recovering after downtime" until runtime_state.recovery_until, and "no replica is leading" while the alive mark is older than AbsenceNotice.
func Tasks ¶
Tasks returns the closed list of Leader tasks (ADR-0007): partition maintenance and retention, the alive mark, the pruning of replica records, the pruning of short-lived state, the ingestion backlog, the retention of the Alerts view, the Heartbeat check, the Stale scan, the count of open Alert Groups, the Alert Group retention, the count of pending deliveries, the retention of Thread replies and of outgoing webhook events, the long polling of Telegram Connections, the OIDC client secret expiry check, the outgoing heartbeat (C-02.FR-10), the re-render of the open Root messages after a key rotation (C-20.FR-7), which also runs when a key was activated, the polling of the events of Bridge Connections in poll mode (C-22.FR-11), the pruning of the Request log (C-23.FR-4) and the Socket Mode connections of Slack Connections (C-24.FR-9). Later capabilities add theirs at the end of the list. The Keeper calls the result at every leadership, so each one starts with a takeover; the Heartbeat check waits for it, so that it measures the timeouts from the end of a downtime the takeover records (C-07.FR-4).
Types ¶
type Alive ¶
type Alive struct {
// contains filtered or unexported fields
}
Alive keeps the alive mark of the Leader in runtime_state, on the business clock, which downtime and the recovery window follow too.
func (*Alive) OnDowntime ¶
func (a *Alive) OnDowntime(f DowntimeRecorder) *Alive
OnDowntime has every downtime the Leader records also recorded by f, in the same transaction, in each Organization.
func (*Alive) TakeOver ¶
TakeOver records this replica as the Leader. When neither a Leader nor any other replica was alive for longer than AbsenceNotice, the gap is downtime: it is stored in downtime_periods, logged as downtime_recorded and opens the recovery window. It runs in one transaction that locks runtime_state, so two Leaders that overlap record one downtime.
type DowntimeRecorder ¶
DowntimeRecorder records a downtime in the Organization orgID inside the transaction tx in which the Leader records it: the open Alert Groups get their "Muster was unavailable" entries (C-09.FR-18).
type Keeper ¶
type Keeper struct {
// contains filtered or unexported fields
}
Keeper competes for the Leader lock and, while it holds it, runs the Leader tasks.
func NewKeeper ¶
func NewKeeper(connect func(context.Context) (Session, error), realClock clock.Clock, log *logging.Logger, replica string, tasks func() []Task, ) *Keeper
NewKeeper returns the Keeper of the replica id. connect opens lock sessions (Dial); the lease runs on the real clock; tasks returns the Leader tasks at every leadership (Tasks).
type PruneTable ¶
type PruneTable struct {
// Name is the table, as the log line and the table label of the metric name it.
Name string
// Delete deletes at most limit rows of the Organization orgID that can no longer be used at now and returns how
// many it deleted. It skips rows that are locked, so a busy row waits for the next run.
Delete func(ctx context.Context, orgID int64, now time.Time, limit int32) (int64, error)
}
PruneTable is one short-lived table of short-lived pruning.
type Queries ¶
type Queries interface {
EnsureRuntimeState(ctx context.Context, updatedAt time.Time) error
LockRuntimeState(ctx context.Context) (dbgen.LockRuntimeStateRow, error)
GetRuntimeState(ctx context.Context) (dbgen.GetRuntimeStateRow, error)
LatestOtherReplicaRefresh(ctx context.Context, arg dbgen.LatestOtherReplicaRefreshParams) (time.Time, error)
RecordDowntime(ctx context.Context, arg dbgen.RecordDowntimeParams) error
LatestDowntimeEnd(ctx context.Context) (time.Time, error)
TakeOver(ctx context.Context, arg dbgen.TakeOverParams) error
MarkAlive(ctx context.Context, arg dbgen.MarkAliveParams) (int64, error)
ListOrganizationIDs(ctx context.Context) ([]int64, error)
LongestLearnedRepeatInterval(ctx context.Context, orgID int64) (int64, error)
// DBTX is the connection or the transaction the queries run on, for what other packages record with them.
DBTX() dbgen.DBTX
}
Queries are the Leader's queries; *dbgen.Queries implements them.
type Session ¶
type Session interface {
// TryLock tries to take the Leader lock without waiting.
TryLock(ctx context.Context) (bool, error)
// Ping proves that the session, and with it the lock, is still there.
Ping(ctx context.Context) error
// Close ends the session, which releases the lock.
Close(ctx context.Context) error
}
Session is the dedicated session connection that holds the Leader lock.
type Task ¶
type Task struct {
Name string
Every time.Duration
Run func(ctx context.Context) error
// Wake, when set, runs the task out of its interval.
Wake <-chan struct{}
}
Task is one Leader task: it runs when the lock is taken and then every Every, and at once when Wake delivers, until the lock is lost. Every Leader task is safe to run twice, because a frozen old Leader can overlap with its successor for a moment (ADR-0007).
type Wakes ¶
type Wakes struct {
// contains filtered or unexported fields
}
Wakes runs Leader tasks out of their interval: in development mode, the development clock moved, and the Heartbeat check and the Stale scan act at the new time at once instead of at their next tick.
type Work ¶
type Work struct {
// Alive keeps the alive mark, records downtime and opens the recovery window.
Alive *Alive
// MaintainPartitions creates and drops partitions; it logs its own failures.
MaintainPartitions func(ctx context.Context) error
// PruneReplicas removes the records of replicas gone for replica.prune_after.
PruneReplicas func(ctx context.Context) error
// Short-lived pruning deletes the rows of short-lived tables that can no longer be used (schema.md, section 6),
// per Organization, on the business clock, and logs and counts them.
Organizations func(ctx context.Context) ([]int64, error)
Business clock.Clock
Log *logging.Logger
// PruneAuth are the short-lived tables of internal/auth: sessions and sign-in throttles. A story that adds a
// short-lived table adds a field for its domain here, lists it in shortLived and adds the table name to
// metrics.ShortLivedTables.
PruneAuth []PruneTable
// PruneUsers are the short-lived tables of internal/users: password setup links.
PruneUsers []PruneTable
// PruneOIDC are the short-lived tables of internal/oidc: the OIDC redirects in flight.
PruneOIDC []PruneTable
// PruneDelivery are the short-lived tables of internal/delivery: the copy buffer of Telegram comment Threads.
PruneDelivery []PruneTable
// PruneAccountLinks are the short-lived tables of internal/accountlinks: the Account link requests.
PruneAccountLinks []PruneTable
// PruneConnections are the short-lived tables of internal/connections: the ids of the events of Bridge
// Connections handled within bridge.event_dedup_window.
PruneConnections []PruneTable
// IngestBacklog sets muster_ingest_backlog from the pending Stored Snapshots of the Organizations.
IngestBacklog func(ctx context.Context, orgs []int64) error
// AlertRetention deletes, in batches, the Alerts of the Organization orgID resolved longer than
// retention.alert_details before now (C-06.FR-19) and returns how many it deleted.
AlertRetention func(ctx context.Context, orgID int64, now time.Time) (int64, error)
// HeartbeatCheck makes the overdue live Heartbeats of the Organizations lost and exports muster_heartbeat_lost
// (C-07.FR-4, C-07.FR-8).
HeartbeatCheck func(ctx context.Context, orgs []int64) error
// StaleScan runs the Stale scan of the Organization orgID (C-06.FR-9, C-07.FR-5).
StaleScan func(ctx context.Context, orgID int64) error
// AlertGroupGauges sets muster_alert_groups from the open Alert Groups of the Organization orgID (C-09).
AlertGroupGauges func(ctx context.Context, orgID int64) error
// AlertGroupRetention deletes, in batches, the details and the summary rows of the Alert Groups of the
// Organization orgID past their retention periods at now (C-09.FR-16) and returns how many of each it deleted.
AlertGroupRetention func(ctx context.Context, orgID int64, now time.Time) (details, summaries int64, err error)
// DeliveryQueue sets muster_delivery_queue from the pending deliveries and due Thread replies of the Organization
// orgID, muster_destination_broken from the health of its Destinations and muster_storm_active from the Storms of
// its Routes (C-11.FR-6, FR-9, FR-17).
DeliveryQueue func(ctx context.Context, orgID int64) error
// ThreadReplyRetention deletes, in batches, the Thread replies of the Organization orgID that are sent, dropped or
// not delivered and older than retention.alert_details at now, and returns how many it deleted.
ThreadReplyRetention func(ctx context.Context, orgID int64, now time.Time) (int64, error)
// WebhookEventRetention deletes, in batches, the outgoing webhook events of the Organization orgID that are
// delivered or not delivered and older than retention.alert_details at now, and returns how many it deleted.
WebhookEventRetention func(ctx context.Context, orgID int64, now time.Time) (int64, error)
// OIDCSecretExpiry raises and resolves MusterOIDCSecretExpiring for the Organization orgID (C-19.FR-5).
OIDCSecretExpiry func(ctx context.Context, orgID int64) error
// OutgoingHeartbeat sends the outgoing heartbeat of the Organization orgID when it is due (C-19.FR-7).
OutgoingHeartbeat func(ctx context.Context, orgID int64) error
// TelegramPolling runs the long polling of the Telegram Connections of the Organization orgID until ctx ends
// (C-14.FR-1): it stops every poller before it returns, and a failed read of the Connections returns early.
TelegramPolling func(ctx context.Context, orgID int64) error
// RerenderAfterRotation recomputes, in batches, the Desired state of the deliveries of the open Alert Groups of
// the Organization orgID whose buttons a key other than the active one signed, after a key activation (C-20.FR-7,
// ADR-0011); it first switches this replica to the active key.
RerenderAfterRotation func(ctx context.Context, orgID int64) error
// KeyringChanged wakes the re-render after a rotation when a key was activated, on any replica's notification.
KeyringChanged *Wakes
// BridgePolling runs the polling of the events of the Bridge Connections in poll mode of the Organization orgID
// until ctx ends (C-22.FR-11): it stops every poll before it returns, and a failed read of the Connections returns
// early.
BridgePolling func(ctx context.Context, orgID int64) error
// RequestLogPruning deletes, in batches, the records of the Request log of the Organization orgID older than
// request_log.max_age at now or past the newest request_log.max_records of their owner, and returns how many it
// deleted (C-23.FR-4).
RequestLogPruning func(ctx context.Context, orgID int64, now time.Time) (int64, error)
// SlackSocketMode holds the Socket Mode connections of the Slack Connections in socket mode of the Organization
// orgID until ctx ends (C-24.FR-9): it closes every one of them before it returns, and a failed read of the
// Connections returns early.
SlackSocketMode func(ctx context.Context, orgID int64) error
// ClockMoved, in development mode, wakes the alive mark, the Heartbeat check, the Stale scan, the Alert Group
// retention, the retention of Thread replies and of outgoing webhook events, the short-lived pruning, the OIDC client
// secret expiry check, the outgoing heartbeat and the pruning of the Request log when the development clock moved, so
// that the alive mark keeps up with the business clock and the Leader is not taken for absent; nil otherwise.
ClockMoved *Wakes
}
Work is what the Leader tasks of this release act on.