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 ¶
- Constants
- func NewHTTPTransport(ctx context.Context, options TLSOptions) (*http.Transport, error)
- func SupportsFeature(versionText string, feature Feature) (bool, error)
- type Authorizer
- type BasicAuth
- type Client
- func (client *Client) DeleteRestart(ctx context.Context, baseURL string) (Response[string], error)
- func (client *Client) DeleteSwitchover(ctx context.Context, baseURL string) (Response[string], error)
- func (client *Client) GetCluster(ctx context.Context, baseURL string) (Response[Cluster], error)
- func (client *Client) GetConfig(ctx context.Context, baseURL string) (Response[DynamicConfig], error)
- func (client *Client) GetFailsafe(ctx context.Context, baseURL string) (Response[FailsafeTopology], error)
- func (client *Client) GetHealth(ctx context.Context, baseURL string, alias HealthAlias, query HealthQuery) (Response[Status], error)
- func (client *Client) GetHistory(ctx context.Context, baseURL string) (Response[History], error)
- func (client *Client) GetLiveness(ctx context.Context, baseURL string) (Response[Empty], error)
- func (client *Client) GetMetrics(ctx context.Context, baseURL string) (Response[string], error)
- func (client *Client) GetPatroni(ctx context.Context, baseURL string) (Response[Status], error)
- func (client *Client) GetReadiness(ctx context.Context, baseURL string, query ReadinessQuery) (Response[Empty], error)
- func (client *Client) GoString() string
- func (client *Client) HeadHealth(ctx context.Context, baseURL string, alias HealthAlias, query HealthQuery) (Response[Empty], error)
- func (client *Client) OptionsHealth(ctx context.Context, baseURL string, alias HealthAlias) (Response[Empty], error)
- func (client *Client) PatchConfig(ctx context.Context, baseURL string, patch DynamicConfig) (Response[DynamicConfig], error)
- func (client *Client) PostCitus(ctx context.Context, baseURL string, event MPPEvent) (Response[string], error)
- func (client *Client) PostFailover(ctx context.Context, baseURL string, request FailoverRequest) (Response[string], error)
- func (client *Client) PostFailsafe(ctx context.Context, baseURL string, request FailsafePeerRequest) (Response[string], error)
- func (client *Client) PostMPP(ctx context.Context, baseURL string, event MPPEvent) (Response[string], error)
- func (client *Client) PostReinitialize(ctx context.Context, baseURL string, request ReinitializeRequest) (Response[string], error)
- func (client *Client) PostReload(ctx context.Context, baseURL string) (Response[string], error)
- func (client *Client) PostRestart(ctx context.Context, baseURL string, request RestartRequest) (Response[string], error)
- func (client *Client) PostSigterm(ctx context.Context, baseURL string) (Response[string], error)
- func (client *Client) PostSwitchover(ctx context.Context, baseURL string, request FailoverRequest) (Response[string], error)
- func (client *Client) PutConfig(ctx context.Context, baseURL string, configuration DynamicConfig) (Response[DynamicConfig], error)
- func (client *Client) String() string
- type ClientOptions
- type Cluster
- type ClusterMember
- type DeliveryState
- type DynamicConfig
- type Empty
- type Endpoint
- type Error
- type ErrorKind
- type FailoverRequest
- type FailsafePeerRequest
- type FailsafeTopology
- type Feature
- type FeatureAvailability
- type HealthAlias
- type HealthQuery
- type History
- type HistoryEntry
- type MPPEvent
- type PatroniIdentity
- type PendingRestartChange
- type ReadinessQuery
- type ReinitializeRequest
- type ReplicationStatus
- type Response
- type RestartRequest
- type Risk
- type ScheduledRestart
- type ScheduledSwitchover
- type Status
- type TLSConfigError
- type TLSOptions
- type TransportCache
- type TransportCacheOptions
- type XLogStatus
Examples ¶
Constants ¶
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 ¶
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.
Types ¶
type BasicAuth ¶
type BasicAuth struct {
// contains filtered or unexported fields
}
func NewBasicAuth ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func NewClient ¶
func NewClient(options ClientOptions) (*Client, error)
func (*Client) DeleteRestart ¶
func (*Client) DeleteSwitchover ¶
func (*Client) GetCluster ¶
func (*Client) GetFailsafe ¶
func (*Client) GetHealth ¶
func (client *Client) GetHealth(ctx context.Context, baseURL string, alias HealthAlias, query HealthQuery) (Response[Status], error)
func (*Client) GetHistory ¶
func (*Client) GetLiveness ¶
func (*Client) GetMetrics ¶
func (*Client) GetPatroni ¶
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) HeadHealth ¶
func (client *Client) HeadHealth(ctx context.Context, baseURL string, alias HealthAlias, query HealthQuery) (Response[Empty], error)
func (*Client) OptionsHealth ¶
func (*Client) PatchConfig ¶
func (client *Client) PatchConfig(ctx context.Context, baseURL string, patch DynamicConfig) (Response[DynamicConfig], error)
func (*Client) PostFailover ¶
func (*Client) PostFailsafe ¶
func (*Client) PostReinitialize ¶
func (*Client) PostReload ¶
func (*Client) PostRestart ¶
func (*Client) PostSigterm ¶
func (*Client) PostSwitchover ¶
func (*Client) PutConfig ¶
func (client *Client) PutConfig(ctx context.Context, baseURL string, configuration DynamicConfig) (Response[DynamicConfig], error)
type ClientOptions ¶
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 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 ¶
EndpointCatalogFor returns only endpoints implemented by the requested supported Patroni version, preserving upstream source order.
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 ¶
type FailoverRequest ¶
type FailsafePeerRequest ¶
type FailsafeTopology ¶
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 ¶
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 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 PatroniIdentity ¶
type PendingRestartChange ¶
type ReadinessQuery ¶
type ReinitializeRequest ¶
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 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 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 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 ¶
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. |
|
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. |