patroni

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 17, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

go-patroni

go-patroni is an independent Go SDK for Patroni and a native Go replacement for patronictl. It can be imported by BOAR, Pig, or any third-party Go application; it has no dependency on BOAR.

The module provides two API levels:

  • a direct, typed REST client for every Patroni 4.1.4 HTTP method/path contract;
  • a higher-level control.Service and runtime that implement Patroni DCS, PostgreSQL, Citus, safety, and patronictl orchestration semantics.

Patroni >=3.0.0,<5.0.0 is the audited compatibility range. Patroni 4.x is the primary target; version-gated features are rejected before an unsupported write is sent. Embedding products may narrow this range per control.Service or runtime.Environment instance without changing package-global state.

Install

The SDK requires Go 1.25 or newer.

go get github.com/pgsty/go-patroni@latest

Install the command-line client independently:

go install github.com/pgsty/go-patroni/cmd/patronictl@latest
patronictl --help

Documentation

Direct REST API

The root package only needs a Patroni REST URL at runtime. It does not require etcd, a Patroni YAML file, or PostgreSQL access.

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    patroni "github.com/pgsty/go-patroni"
)

func main() {
    client, err := patroni.NewClient(patroni.ClientOptions{
        Timeout:    5 * time.Second,
        Authorizer: patroni.NewBasicAuth("patroni", "secret"),
        UserAgent:  "pig/1.0",
    })
    if err != nil {
        log.Fatal(err)
    }

    response, err := client.GetPatroni(context.Background(), "https://db1:8008")
    if err != nil {
        // A typed error describes request, authentication, transport, response,
        // decode, and ambiguous-write delivery states. The response still
        // retains status, headers, and the raw body when they were received.
        log.Fatal(err)
    }
    fmt.Printf("%s %s %s\n", response.Data.Patroni.Name,
        response.Data.Role, response.Data.Patroni.Version)
}

For TLS/mTLS and encrypted private keys, construct a transport with patroni.NewHTTPTransport. Response[T] always retains the status code, headers, and raw response bytes, so newer upstream fields remain available even before a typed DTO is extended. EndpointCatalog exposes all 75 audited method/path rows and their risk classes.

High-level SDK

The high-level runtime reads a normal Patroni patronictl.yaml, connects to etcd3, discovers member REST URLs, and assembles the REST, DCS, and PostgreSQL clients used by control.Service:

environment, err := patroniruntime.NewEnvironment(ctx,
    patroniruntime.EnvironmentOptions{
        Load: config.LoadRequest{Path: "/etc/patroni/patronictl.yaml"},
    })
if err != nil {
    return err
}

rt, err := environment.Open(ctx, patroniruntime.RuntimeOptions{
    Context:       "production",
    Operation:     config.OperationClusterRead,
    ExplicitScope: "postgres-ha",
})
if err != nil {
    return err
}
defer rt.Close()

result := rt.Service.List(ctx, control.ListRequest{
    Targets: []model.Target{rt.Target},
})
if result.Outcome != control.Succeeded {
    return result.Error
}

The omitted imports in that fragment are:

import (
    "github.com/pgsty/go-patroni/config"
    "github.com/pgsty/go-patroni/control"
    "github.com/pgsty/go-patroni/model"
    patroniruntime "github.com/pgsty/go-patroni/runtime"
)

The high-level runtime currently implements Patroni's etcd3 DCS backend. A consumer using another DCS can implement the narrow interfaces in dcs and assemble control.Service directly.

Embed the command suite

Applications that want the complete patronictl command surface can compose it through the public cli package. Product commands are registered as extensions; Patroni parsing, prompting, rendering, and exit behavior stay in one SDK implementation:

root := cli.NewRootCommand(cli.Options{
    Application: cli.Application{
        Name: "my-app", Short: "My Patroni control plane", Version: buildVersion,
        RequestIDPrefix: "my-app-cli",
    },
    Environment: patroniruntime.EnvironmentOptions{
        Load: config.LoadRequest{Path: "/infra/conf/patronictl.yml"},
        UserAgent: "my-app/" + buildVersion,
    },
    Extensions: []cli.Extension{newServeCommand},
})
if err := root.ExecuteContext(ctx); err != nil {
    return err
}

An extension receives normalized root state through ExtensionContext.Invocation, so explicit --config-file, --dcs-url/--dcs, --insecure, --context, and --output values do not need to be reparsed. Applications such as Pig that already own a command framework can instead use control and runtime directly; importing cli is optional.

Configuration

The CLI accepts Patroni's standard PATRONICTL_CONFIG_FILE, DCS_URL, -c, -d/--dcs-url, and -k inputs. The optional go_patroni extension adds named contexts and network deadlines without changing Patroni's own fields:

scope: postgres-ha
namespace: /service/

etcd3:
  hosts: [10.10.10.10:2379, 10.10.10.11:2379]

ctl:
  authentication:
    username: patroni
    password: secret

go_patroni:
  default_context: production
  contexts:
    production: {}
    staging:
      scope: postgres-ha-staging
      etcd3:
        hosts: [10.20.20.10:2379]
  network:
    dns_timeout: 5s
    dcs_dial_timeout: 5s
    dcs_request_timeout: 10s
    patroni_timeout: 10s
    postgres_timeout: 30s
    postgres_close_timeout: 5s

Select a context with --context or GO_PATRONI_CONTEXT. The legacy boar extension and BOAR_CONTEXT are accepted for migration, but new consumers should use the product-neutral names.

patronictl compatibility

The Go CLI implements all 19 commands in Patroni 4.1.4's patronictl: dsn, query, remove, reload, restart, reinit, failover, switchover, list, topology, flush, pause, resume, edit-config, show-config, version, history, demote-cluster, and promote-cluster.

It also adds discover, inspect-config, multi-cluster --all, and stable JSON/YAML envelopes through -o. Machine output uses the versioned patroni.pgsty.com/v1alpha1 schema.

The source-pinned compatibility evidence is in compatibility, with the detailed support matrix in docs/compatibility.md. There are currently no declared CLI deviations from the pinned Patroni 4.1.4 command contract.

Package map

Package Purpose
module root Complete Patroni REST API client, TLS, errors, endpoint and feature catalogs
config Tolerant Patroni YAML loading, context overlays, secret-safe projection
model Stable Patroni cluster/member identities and domain objects
dcs Capability-scoped Patroni DCS contracts and state decoding
dcs/etcd3 Native etcd3 implementation, transactions, discovery, and watches
postgres One-shot role-checked PostgreSQL query client
control Adapter-neutral, patronictl-compatible control operations
runtime Configuration-to-client assembly for applications and CLIs
cli Public composition facade for the complete command suite and extensions
cmd/patronictl Standalone native Go command-line client

Safety model

  • Every I/O operation takes a caller-owned context.Context and is bounded.
  • REST writes are never automatically retried.
  • Errors retain whether a write was not sent, may have been sent, or received a response.
  • High-level writes separate preparation from execution, bind plans to the service instance, use DCS compare-and-swap where applicable, and return UNKNOWN rather than claiming a false failure after an ambiguous send.
  • Credentials are not accepted in endpoint URLs and are redacted from string representations, configuration inspection, logs, and machine output.

Development

go test -mod=readonly ./...
go vet ./...
go test -run '^$' -tags=integration ./test/integration
go run ./tools/machineschema -check

The isolated live matrices are opt-in because they start real Patroni, etcd, and PostgreSQL instances. See scripts/test-*-integration.sh.

Releases

Stable releases follow Semantic Versioning and use vMAJOR.MINOR.PATCH tags. Pushing such a tag runs the release workflow, which publishes patronictl archives for Linux and macOS on amd64 and arm64, plus SHA-256 checksums.

License

Apache License 2.0. See LICENSE.

Documentation

Overview

Package patroni provides a native Go client for the Patroni REST API.

The root package owns HTTP wire contracts and transport behavior. Higher level packages in this module add Patroni configuration, DCS state, PostgreSQL queries, patronictl-compatible orchestration, and CLI adapters.

Index

Examples

Constants

View Source
const (
	PatroniV3       = "3.0.0"
	PatroniV3MPP    = "3.3.0"
	PatroniV4       = "4.0.0"
	PatroniV4Point1 = "4.1.0"
)

Variables

This section is empty.

Functions

func NewHTTPTransport

func NewHTTPTransport(ctx context.Context, options TLSOptions) (*http.Transport, error)

NewHTTPTransport performs cancellation-aware credential file reads and builds a verification-on TLS transport. It retains parsed key material only inside crypto/tls, not plaintext file or passphrase buffers.

func SupportsFeature

func SupportsFeature(versionText string, feature Feature) (bool, error)

SupportsFeature validates version and reports whether Patroni implements a named versioned capability.

Types

type Authorizer

type Authorizer interface {
	Authorize(context.Context, *http.Request) error
}

type BasicAuth

type BasicAuth struct {
	// contains filtered or unexported fields
}

func NewBasicAuth

func NewBasicAuth(username, password string) BasicAuth

func (BasicAuth) Authorize

func (auth BasicAuth) Authorize(_ context.Context, request *http.Request) error

func (BasicAuth) GoString

func (auth BasicAuth) GoString() string

func (BasicAuth) String

func (auth BasicAuth) String() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(options ClientOptions) (*Client, error)

func (*Client) DeleteRestart

func (client *Client) DeleteRestart(ctx context.Context, baseURL string) (Response[string], error)

func (*Client) DeleteSwitchover

func (client *Client) DeleteSwitchover(ctx context.Context, baseURL string) (Response[string], error)

func (*Client) GetCluster

func (client *Client) GetCluster(ctx context.Context, baseURL string) (Response[Cluster], error)

func (*Client) GetConfig

func (client *Client) GetConfig(ctx context.Context, baseURL string) (Response[DynamicConfig], error)

func (*Client) GetFailsafe

func (client *Client) GetFailsafe(ctx context.Context, baseURL string) (Response[FailsafeTopology], error)

func (*Client) GetHealth

func (client *Client) GetHealth(ctx context.Context, baseURL string, alias HealthAlias, query HealthQuery) (Response[Status], error)

func (*Client) GetHistory

func (client *Client) GetHistory(ctx context.Context, baseURL string) (Response[History], error)

func (*Client) GetLiveness

func (client *Client) GetLiveness(ctx context.Context, baseURL string) (Response[Empty], error)

func (*Client) GetMetrics

func (client *Client) GetMetrics(ctx context.Context, baseURL string) (Response[string], error)

func (*Client) GetPatroni

func (client *Client) GetPatroni(ctx context.Context, baseURL string) (Response[Status], error)
Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	patroni "github.com/pgsty/go-patroni"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
		writer.Header().Set("Content-Type", "application/json")
		_, _ = fmt.Fprint(writer, `{"state":"running","role":"primary","patroni":{"version":"4.1.3","scope":"demo","name":"node-1"}}`)
	}))
	defer server.Close()

	client, err := patroni.NewClient(patroni.ClientOptions{})
	if err != nil {
		panic(err)
	}
	response, err := client.GetPatroni(context.Background(), server.URL)
	if err != nil {
		panic(err)
	}
	fmt.Println(response.Data.Patroni.Name, response.Data.Role, response.Data.Patroni.Version)
}
Output:
node-1 primary 4.1.3

func (*Client) GetReadiness

func (client *Client) GetReadiness(ctx context.Context, baseURL string, query ReadinessQuery) (Response[Empty], error)

func (*Client) GoString

func (client *Client) GoString() string

func (*Client) HeadHealth

func (client *Client) HeadHealth(ctx context.Context, baseURL string, alias HealthAlias, query HealthQuery) (Response[Empty], error)

func (*Client) OptionsHealth

func (client *Client) OptionsHealth(ctx context.Context, baseURL string, alias HealthAlias) (Response[Empty], error)

func (*Client) PatchConfig

func (client *Client) PatchConfig(ctx context.Context, baseURL string, patch DynamicConfig) (Response[DynamicConfig], error)

func (*Client) PostCitus

func (client *Client) PostCitus(ctx context.Context, baseURL string, event MPPEvent) (Response[string], error)

func (*Client) PostFailover

func (client *Client) PostFailover(ctx context.Context, baseURL string, request FailoverRequest) (Response[string], error)

func (*Client) PostFailsafe

func (client *Client) PostFailsafe(ctx context.Context, baseURL string, request FailsafePeerRequest) (Response[string], error)

func (*Client) PostMPP

func (client *Client) PostMPP(ctx context.Context, baseURL string, event MPPEvent) (Response[string], error)

func (*Client) PostReinitialize

func (client *Client) PostReinitialize(ctx context.Context, baseURL string, request ReinitializeRequest) (Response[string], error)

func (*Client) PostReload

func (client *Client) PostReload(ctx context.Context, baseURL string) (Response[string], error)

func (*Client) PostRestart

func (client *Client) PostRestart(ctx context.Context, baseURL string, request RestartRequest) (Response[string], error)

func (*Client) PostSigterm

func (client *Client) PostSigterm(ctx context.Context, baseURL string) (Response[string], error)

func (*Client) PostSwitchover

func (client *Client) PostSwitchover(ctx context.Context, baseURL string, request FailoverRequest) (Response[string], error)

func (*Client) PutConfig

func (client *Client) PutConfig(ctx context.Context, baseURL string, configuration DynamicConfig) (Response[DynamicConfig], error)

func (*Client) String

func (client *Client) String() string

type ClientOptions

type ClientOptions struct {
	HTTPClient       *http.Client
	Transport        http.RoundTripper
	Authorizer       Authorizer
	Logger           *slog.Logger
	Timeout          time.Duration
	MaxResponseBytes int64
	UserAgent        string
}

type Cluster

type Cluster struct {
	Members             []ClusterMember      `json:"members"`
	Scope               string               `json:"scope,omitempty"`
	Pause               *bool                `json:"pause,omitempty"`
	ScheduledSwitchover *ScheduledSwitchover `json:"scheduled_switchover,omitempty"`
}

type ClusterMember

type ClusterMember struct {
	Name                 string                          `json:"name"`
	Role                 string                          `json:"role"`
	State                string                          `json:"state"`
	APIURL               string                          `json:"api_url,omitempty"`
	Host                 string                          `json:"host,omitempty"`
	Port                 *int                            `json:"port,omitempty"`
	Timeline             *int                            `json:"timeline,omitempty"`
	PendingRestart       *bool                           `json:"pending_restart,omitempty"`
	PendingRestartReason map[string]PendingRestartChange `json:"pending_restart_reason,omitempty"`
	ScheduledRestart     *ScheduledRestart               `json:"scheduled_restart,omitempty"`
	Tags                 map[string]any                  `json:"tags,omitempty"`
	LSN                  json.RawMessage                 `json:"lsn,omitempty"`
	Lag                  json.RawMessage                 `json:"lag,omitempty"`
	ReceiveLSN           json.RawMessage                 `json:"receive_lsn,omitempty"`
	ReceiveLag           json.RawMessage                 `json:"receive_lag,omitempty"`
	ReplayLSN            json.RawMessage                 `json:"replay_lsn,omitempty"`
	ReplayLag            json.RawMessage                 `json:"replay_lag,omitempty"`
}

type DeliveryState

type DeliveryState string
const (
	DeliveryNotSent          DeliveryState = "NOT_SENT"
	DeliveryMaybeSent        DeliveryState = "MAYBE_SENT"
	DeliveryResponseReceived DeliveryState = "RESPONSE_RECEIVED"
)

type DynamicConfig

type DynamicConfig map[string]any

type Empty

type Empty struct{}

type Endpoint

type Endpoint struct {
	ID       string
	Method   string
	Path     string
	Risk     Risk
	Request  string
	Response string
	Since    string
}

func EndpointCatalog

func EndpointCatalog() []Endpoint

EndpointCatalog returns all 75 method/path rows in pinned Patroni source order. Callers receive a copy and cannot mutate the package contract.

func EndpointCatalogFor

func EndpointCatalogFor(versionText string) ([]Endpoint, error)

EndpointCatalogFor returns only endpoints implemented by the requested supported Patroni version, preserving upstream source order.

func (Endpoint) AvailableIn

func (endpoint Endpoint) AvailableIn(version model.Version) bool

AvailableIn reports whether this method/path contract exists in a supported Patroni version. Version-specific semantics are described by FeatureCatalog.

type Error

type Error struct {
	Kind       ErrorKind
	Method     string
	Endpoint   string
	Delivery   DeliveryState
	StatusCode int
	// contains filtered or unexported fields
}

Error intentionally omits the base URL, request body, response body, and underlying error text from formatting. Unwrap is available for explicit diagnostics and errors.Is/errors.As.

func (*Error) AmbiguousWrite

func (err *Error) AmbiguousWrite() bool

func (*Error) Error

func (err *Error) Error() string

func (*Error) GoString

func (err *Error) GoString() string

func (*Error) Unwrap

func (err *Error) Unwrap() error

type ErrorKind

type ErrorKind string
const (
	ErrorRequest        ErrorKind = "REQUEST"
	ErrorAuthentication ErrorKind = "AUTHENTICATION"
	ErrorTransport      ErrorKind = "TRANSPORT"
	ErrorResponseBody   ErrorKind = "RESPONSE_BODY"
	ErrorDecode         ErrorKind = "DECODE"
)

type FailoverRequest

type FailoverRequest struct {
	Leader      string `json:"leader,omitempty"`
	Candidate   string `json:"candidate,omitempty"`
	Member      string `json:"member,omitempty"`
	ScheduledAt string `json:"scheduled_at,omitempty"`
}

type FailsafePeerRequest

type FailsafePeerRequest struct {
	Name    string           `json:"name"`
	ConnURL string           `json:"conn_url"`
	APIURL  string           `json:"api_url"`
	Slots   map[string]int64 `json:"slots,omitempty"`
}

type FailsafeTopology

type FailsafeTopology map[string]string

type Feature

type Feature string
const (
	FeatureCoreRESTAPI            Feature = "core-rest-api"
	FeatureMPPEndpoint            Feature = "mpp-endpoint"
	FeatureQuorumStatus           Feature = "quorum-status"
	FeatureFailsafeLSNHeader      Feature = "failsafe-lsn-header"
	FeatureReadinessLagMode       Feature = "readiness-lag-mode"
	FeatureReinitializeFromLeader Feature = "reinitialize-from-leader"
	FeatureStandbyClusterCLI      Feature = "standby-cluster-cli"
)

type FeatureAvailability

type FeatureAvailability struct {
	Feature     Feature
	Since       string
	Description string
}

func FeatureCatalog

func FeatureCatalog() []FeatureAvailability

FeatureCatalog returns a copy of the audited Patroni version capability matrix. The catalog is pinned against upstream 3.0.0 through 4.1.4.

type HealthAlias

type HealthAlias string
const (
	HealthRoot                HealthAlias = "/"
	HealthPrimary             HealthAlias = "/primary"
	HealthMaster              HealthAlias = "/master"
	HealthReadWrite           HealthAlias = "/read-write"
	HealthLeader              HealthAlias = "/leader"
	HealthStandbyLeader       HealthAlias = "/standby-leader"
	HealthStandbyLeaderLegacy HealthAlias = "/standby_leader"
	HealthReplica             HealthAlias = "/replica"
	HealthReadOnly            HealthAlias = "/read-only"
	HealthQuorum              HealthAlias = "/quorum"
	HealthReadOnlyQuorum      HealthAlias = "/read-only-quorum"
	HealthSync                HealthAlias = "/sync"
	HealthSynchronous         HealthAlias = "/synchronous"
	HealthReadOnlySync        HealthAlias = "/read-only-sync"
	HealthReadOnlySynchronous HealthAlias = "/read-only-synchronous"
	HealthAsync               HealthAlias = "/async"
	HealthAsynchronous        HealthAlias = "/asynchronous"
	HealthAny                 HealthAlias = "/health"
)

func HealthAliases

func HealthAliases() []HealthAlias

func HealthAliasesFor

func HealthAliasesFor(versionText string) ([]HealthAlias, error)

HealthAliasesFor returns the health aliases implemented by the requested supported Patroni version.

type HealthQuery

type HealthQuery struct {
	Lag string
	// ReplicationState is retained for source compatibility only. Patroni does
	// not implement replication_state as a health-query filter.
	// Deprecated: use Lag and Tags, or inspect Status.ReplicationState.
	ReplicationState string
	Tags             map[string]string
}

type History

type History []HistoryEntry

type HistoryEntry

type HistoryEntry struct {
	Timeline  int64
	LSN       int64
	Reason    string
	Timestamp string
	Member    string
	Extra     []json.RawMessage
}

func (HistoryEntry) MarshalJSON

func (entry HistoryEntry) MarshalJSON() ([]byte, error)

func (*HistoryEntry) UnmarshalJSON

func (entry *HistoryEntry) UnmarshalJSON(data []byte) error

type MPPEvent

type MPPEvent struct {
	Type     string  `json:"type"`
	Group    int     `json:"group"`
	Leader   string  `json:"leader"`
	Timeout  float64 `json:"timeout"`
	Cooldown float64 `json:"cooldown"`
}

type PatroniIdentity

type PatroniIdentity struct {
	Version string `json:"version"`
	Scope   string `json:"scope"`
	// Name is absent from Patroni 3.0 and 3.1 status responses and is empty
	// after decoding those historical payloads. Patroni added it in 3.2.0.
	Name string `json:"name"`
}

type PendingRestartChange

type PendingRestartChange struct {
	OldValue any `json:"old_value,omitempty"`
	NewValue any `json:"new_value,omitempty"`
}

type ReadinessQuery

type ReadinessQuery struct {
	Lag  string
	Mode string
}

type ReinitializeRequest

type ReinitializeRequest struct {
	Force      bool `json:"force"`
	FromLeader bool `json:"from_leader"`
}

type ReplicationStatus

type ReplicationStatus struct {
	Username        string `json:"usename,omitempty"`
	ApplicationName string `json:"application_name,omitempty"`
	ClientAddress   string `json:"client_addr,omitempty"`
	State           string `json:"state,omitempty"`
	SyncState       string `json:"sync_state,omitempty"`
	SyncPriority    *int   `json:"sync_priority,omitempty"`
}

type Response

type Response[T any] struct {
	StatusCode int         `json:"status_code"`
	Header     http.Header `json:"header"`
	Data       T           `json:"data"`
	Raw        []byte      `json:"raw"`
}

type RestartRequest

type RestartRequest struct {
	Schedule        string `json:"schedule,omitempty"`
	Role            string `json:"role,omitempty"`
	PostgresVersion string `json:"postgres_version,omitempty"`
	// Timeout accepts either a JSON number of seconds or a Patroni duration
	// string. Callers should use a numeric Go value or a string such as "30s".
	Timeout        any   `json:"timeout,omitempty"`
	RestartPending *bool `json:"restart_pending,omitempty"`
}

type Risk

type Risk string
const (
	RiskRead                  Risk = "read"
	RiskAdminWrite            Risk = "admin-write"
	RiskAvailabilityWrite     Risk = "availability-write"
	RiskPeerInternalRead      Risk = "peer-internal-read"
	RiskPeerInternal          Risk = "peer-internal"
	RiskTestPlatformDangerous Risk = "test-platform-dangerous"
)

type ScheduledRestart

type ScheduledRestart struct {
	Schedule        string `json:"schedule,omitempty"`
	Role            string `json:"role,omitempty"`
	PostgresVersion string `json:"postgres_version,omitempty"`
	// Timeout is either a JSON number of seconds or a Patroni duration string,
	// such as "30" or "30s". Patroni accepts and may publish both forms.
	Timeout        any   `json:"timeout,omitempty"`
	RestartPending *bool `json:"restart_pending,omitempty"`
}

type ScheduledSwitchover

type ScheduledSwitchover struct {
	At   string `json:"at,omitempty"`
	From string `json:"from,omitempty"`
	To   string `json:"to,omitempty"`
}

type Status

type Status struct {
	State                    string                          `json:"state,omitempty"`
	PostmasterStartTime      string                          `json:"postmaster_start_time,omitempty"`
	Role                     string                          `json:"role,omitempty"`
	ServerVersion            *int                            `json:"server_version,omitempty"`
	XLog                     XLogStatus                      `json:"xlog,omitempty"`
	Timeline                 *int                            `json:"timeline,omitempty"`
	Replication              []ReplicationStatus             `json:"replication,omitempty"`
	ReplicationState         string                          `json:"replication_state,omitempty"`
	ClusterUnlocked          *bool                           `json:"cluster_unlocked,omitempty"`
	FailsafeModeIsActive     *bool                           `json:"failsafe_mode_is_active,omitempty"`
	Pause                    *bool                           `json:"pause,omitempty"`
	DCSLastSeen              *int64                          `json:"dcs_last_seen,omitempty"`
	Tags                     map[string]any                  `json:"tags,omitempty"`
	DatabaseSystemIdentifier string                          `json:"database_system_identifier,omitempty"`
	PendingRestart           *bool                           `json:"pending_restart,omitempty"`
	PendingRestartReason     map[string]PendingRestartChange `json:"pending_restart_reason,omitempty"`
	ScheduledRestart         *ScheduledRestart               `json:"scheduled_restart,omitempty"`
	WatchdogFailed           *bool                           `json:"watchdog_failed,omitempty"`
	LoggerQueueSize          *int                            `json:"logger_queue_size,omitempty"`
	LoggerRecordsLost        *int                            `json:"logger_records_lost,omitempty"`
	SyncStandby              *bool                           `json:"sync_standby,omitempty"`
	QuorumStandby            *bool                           `json:"quorum_standby,omitempty"`
	Patroni                  PatroniIdentity                 `json:"patroni"`
}

Status is the wire DTO returned by health aliases and GET /patroni. Unknown fields are tolerated and remain available in Response.Raw.

type TLSConfigError

type TLSConfigError struct {
	Field string
	// contains filtered or unexported fields
}

func (*TLSConfigError) Error

func (err *TLSConfigError) Error() string

func (*TLSConfigError) GoString

func (err *TLSConfigError) GoString() string

func (*TLSConfigError) Unwrap

func (err *TLSConfigError) Unwrap() error

type TLSOptions

type TLSOptions struct {
	CAFile             string
	CertFile           string
	KeyFile            string
	ServerName         string
	InsecureSkipVerify bool
	// IncludeSystemCAs augments an explicit CAFile with the host root pool.
	// By default an explicit CAFile is the exclusive trust bundle, matching
	// Patroni ctl.cacert/restapi.cafile behavior.
	IncludeSystemCAs bool
	// contains filtered or unexported fields
}

func (TLSOptions) GoString

func (options TLSOptions) GoString() string

func (TLSOptions) String

func (options TLSOptions) String() string

func (TLSOptions) WithKeyPassword

func (options TLSOptions) WithKeyPassword(password string) TLSOptions

WithKeyPassword returns a copy with a protected key passphrase. Formatting TLSOptions never exposes the passphrase; only transport construction reads it, and temporary copies are cleared after parsing.

type TransportCache

type TransportCache struct {
	// contains filtered or unexported fields
}

TransportCache is an instance-scoped, rotation-aware LRU transport cache. The fingerprint includes file contents and TLS settings, so replacing a certificate/key creates a new pool without process-global mutable state.

func NewTransportCache

func NewTransportCache() *TransportCache

func NewTransportCacheWithOptions added in v0.2.0

func NewTransportCacheWithOptions(options TransportCacheOptions) (*TransportCache, error)

func (*TransportCache) CloseIdleConnections

func (cache *TransportCache) CloseIdleConnections()

func (*TransportCache) Purge added in v0.2.0

func (cache *TransportCache) Purge()

Purge closes idle connections and forgets every cached fingerprint. Active connections remain valid according to net/http transport semantics.

func (*TransportCache) Transport

func (cache *TransportCache) Transport(ctx context.Context, options TLSOptions) (*http.Transport, error)

type TransportCacheOptions added in v0.2.0

type TransportCacheOptions struct {
	// MaxEntries bounds retained certificate fingerprints. Zero uses the
	// default; negative values are invalid.
	MaxEntries int
}

type XLogStatus

type XLogStatus struct {
	Location          *int64 `json:"location,omitempty"`
	ReceivedLocation  *int64 `json:"received_location,omitempty"`
	ReplayedLocation  *int64 `json:"replayed_location,omitempty"`
	ReplayedTimestamp any    `json:"replayed_timestamp,omitempty"`
	Paused            *bool  `json:"paused,omitempty"`
}

Directories

Path Synopsis
Package cli composes the go-patroni patronictl-compatible command suite into standalone binaries and larger applications.
Package cli composes the go-patroni patronictl-compatible command suite into standalone binaries and larger applications.
cmd
patronictl command
Package config loads Patroni YAML tolerantly, retains its raw yaml.Node, and projects only the fields required by a selected Patroni operation.
Package config loads Patroni YAML tolerantly, retains its raw yaml.Node, and projects only the fields required by a selected Patroni operation.
Package control implements adapter-neutral Patroni cluster operations with patronictl-compatible selection, planning, execution, verification, and outcome semantics.
Package control implements adapter-neutral Patroni cluster operations with patronictl-compatible selection, planning, execution, verification, and outcome semantics.
dcs
Package dcs defines Patroni-oriented etcd3 state and capability-scoped DCS operations.
Package dcs defines Patroni-oriented etcd3 state and capability-scoped DCS operations.
etcd3
Package etcd3 implements the Patroni DCS interfaces on etcd v3, including bounded snapshots, discovery, watches, compare-and-swap, and cluster removal.
Package etcd3 implements the Patroni DCS interfaces on etcd v3, including bounded snapshots, discovery, watches, compare-and-swap, and cluster removal.
internal
cli
Package cli is the standalone patronictl Cobra adapter.
Package cli is the standalone patronictl Cobra adapter.
secret
Package secret provides values and sanitizers that are safe by default for fmt, JSON, YAML, and slog.
Package secret provides values and sanitizers that are safe by default for fmt, JSON, YAML, and slog.
version
Package version owns build metadata injected by release ldflags.
Package version owns build metadata injected by release ldflags.
Package model contains normalized Patroni domain types.
Package model contains normalized Patroni domain types.
Package postgres implements the SDK's native one-shot PostgreSQL query client.
Package postgres implements the SDK's native one-shot PostgreSQL query client.
Package runtime wires Patroni configuration to concrete SDK clients.
Package runtime wires Patroni configuration to concrete SDK clients.
tools
compatgen command
Command compatgen regenerates go-patroni compatibility inventories from the pinned Patroni source checkout.
Command compatgen regenerates go-patroni compatibility inventories from the pinned Patroni source checkout.
machineschema command
Command machineschema generates the exhaustive Go patronictl CLI machine-result schema, per-kind canonical examples, and a structural compatibility contract from the adapter-owned kind/type catalog.
Command machineschema generates the exhaustive Go patronictl CLI machine-result schema, per-kind canonical examples, and a structural compatibility contract from the adapter-owned kind/type catalog.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL