|
| 1 | +package ha |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/tls" |
| 5 | + "crypto/x509" |
| 6 | + "database/sql" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "net/http" |
| 10 | + "net/url" |
| 11 | + "os" |
| 12 | + "strings" |
| 13 | + "time" |
| 14 | + |
| 15 | + clientv3 "go.etcd.io/etcd/client/v3" |
| 16 | + |
| 17 | + "github.com/block/proto-fleet/server/internal/infrastructure/db" |
| 18 | + "github.com/block/proto-fleet/server/internal/runtimejobs" |
| 19 | +) |
| 20 | + |
| 21 | +// Config keeps HA opt-in so existing single-instance deployments remain |
| 22 | +// standalone and do not need etcd or Patroni credentials. |
| 23 | +type Config struct { |
| 24 | + Enabled bool `help:"Enable active/passive Fleet runtime ownership." default:"false" env:"ENABLED"` |
| 25 | + ClusterPath string `help:"Patroni DCS cluster path." default:"/service/proto-fleet" env:"CLUSTER_PATH"` |
| 26 | + EtcdEndpoints []string `help:"Comma-separated HTTPS etcd endpoints." env:"ETCD_ENDPOINTS" sep:","` |
| 27 | + EtcdUsername string `help:"Read-only etcd observer username." default:"fleet-observer" env:"ETCD_USERNAME"` |
| 28 | + EtcdPasswordFile string `help:"Path to the etcd observer password file." default:"/etc/proto-fleet/ha/fleet-etcd-password" env:"ETCD_PASSWORD_FILE" type:"path"` |
| 29 | + ServiceCAFile string `help:"Path to the CA that signs etcd and Patroni service certificates." default:"/etc/proto-fleet/ha/service-ca.crt" env:"SERVICE_CA_FILE" type:"path"` |
| 30 | + LeaseDuration time.Duration `help:"Fleet active lease duration." default:"10s" env:"LEASE_DURATION"` |
| 31 | + RenewInterval time.Duration `help:"Fleet active lease renewal interval." default:"3s" env:"RENEW_INTERVAL"` |
| 32 | + RetryInterval time.Duration `help:"Passive ownership retry interval." default:"1s" env:"RETRY_INTERVAL"` |
| 33 | + DialTimeout time.Duration `help:"etcd connection timeout." default:"5s" env:"DIAL_TIMEOUT"` |
| 34 | +} |
| 35 | + |
| 36 | +// NewConfiguredRuntime creates a standalone runtime unless HA is explicitly |
| 37 | +// enabled. In HA mode, cleanup closes the etcd client. |
| 38 | +func NewConfiguredRuntime( |
| 39 | + config Config, |
| 40 | + conn *sql.DB, |
| 41 | + group *runtimejobs.Group, |
| 42 | + reaper activationReaper, |
| 43 | + healthy func() bool, |
| 44 | +) (*Runtime, func() error, error) { |
| 45 | + if !config.Enabled { |
| 46 | + runtime, err := NewStandaloneRuntime(group, healthy) |
| 47 | + return runtime, func() error { return nil }, err |
| 48 | + } |
| 49 | + if err := config.Validate(); err != nil { |
| 50 | + return nil, nil, err |
| 51 | + } |
| 52 | + |
| 53 | + password, err := readRuntimeSecret(config.EtcdPasswordFile) |
| 54 | + if err != nil { |
| 55 | + return nil, nil, fmt.Errorf("read HA etcd password: %w", err) |
| 56 | + } |
| 57 | + tlsConfig, err := loadServiceTLS(config.ServiceCAFile) |
| 58 | + if err != nil { |
| 59 | + return nil, nil, err |
| 60 | + } |
| 61 | + etcd, err := NewEtcdClient(clientv3.Config{ |
| 62 | + Endpoints: config.EtcdEndpoints, |
| 63 | + Username: config.EtcdUsername, |
| 64 | + Password: password, |
| 65 | + TLS: tlsConfig.Clone(), |
| 66 | + DialTimeout: config.DialTimeout, |
| 67 | + }) |
| 68 | + if err != nil { |
| 69 | + return nil, nil, fmt.Errorf("create HA etcd client: %w", err) |
| 70 | + } |
| 71 | + |
| 72 | + transport, ok := http.DefaultTransport.(*http.Transport) |
| 73 | + if !ok { |
| 74 | + _ = etcd.Close() |
| 75 | + return nil, nil, errors.New("default HTTP transport is not configurable for HA") |
| 76 | + } |
| 77 | + patroniTransport := transport.Clone() |
| 78 | + patroniTransport.TLSClientConfig = tlsConfig.Clone() |
| 79 | + cleanup := func() error { |
| 80 | + patroniTransport.CloseIdleConnections() |
| 81 | + return etcd.Close() |
| 82 | + } |
| 83 | + patroni := NewPatroniHTTPClient(&http.Client{ |
| 84 | + Transport: patroniTransport, |
| 85 | + Timeout: defaultHAHTTPTimeout, |
| 86 | + }) |
| 87 | + queries := db.NewFailoverResettingQuerier(db.NewRetryDB(conn)) |
| 88 | + observer, err := NewObserver(config.ClusterPath, etcd, queries, patroni) |
| 89 | + if err != nil { |
| 90 | + _ = cleanup() |
| 91 | + return nil, nil, err |
| 92 | + } |
| 93 | + coordinator, err := NewCoordinator(observer, NewLeaseStore(conn), CoordinatorConfig{ |
| 94 | + LeaseDuration: config.LeaseDuration, |
| 95 | + RenewInterval: config.RenewInterval, |
| 96 | + RetryInterval: config.RetryInterval, |
| 97 | + }) |
| 98 | + if err != nil { |
| 99 | + _ = cleanup() |
| 100 | + return nil, nil, err |
| 101 | + } |
| 102 | + runtime, err := NewRuntime(coordinator, group, reaper, healthy) |
| 103 | + if err != nil { |
| 104 | + _ = cleanup() |
| 105 | + return nil, nil, err |
| 106 | + } |
| 107 | + return runtime, cleanup, nil |
| 108 | +} |
| 109 | + |
| 110 | +func (config Config) Validate() error { |
| 111 | + if !config.Enabled { |
| 112 | + return nil |
| 113 | + } |
| 114 | + if config.ClusterPath == "" || len(config.EtcdEndpoints) == 0 || config.EtcdUsername == "" || |
| 115 | + config.EtcdPasswordFile == "" || config.ServiceCAFile == "" || config.DialTimeout <= 0 { |
| 116 | + return errors.New("enabled HA requires cluster path, etcd endpoints and credentials, service CA, and a positive dial timeout") |
| 117 | + } |
| 118 | + for _, endpoint := range config.EtcdEndpoints { |
| 119 | + parsed, err := url.Parse(endpoint) |
| 120 | + if err != nil || parsed.Scheme != "https" || parsed.Host == "" { |
| 121 | + return fmt.Errorf("HA etcd endpoint must be an HTTPS URL: %q", endpoint) |
| 122 | + } |
| 123 | + } |
| 124 | + return nil |
| 125 | +} |
| 126 | + |
| 127 | +func readRuntimeSecret(path string) (string, error) { |
| 128 | + contents, err := os.ReadFile(path) |
| 129 | + if err != nil { |
| 130 | + return "", fmt.Errorf("read secret file: %w", err) |
| 131 | + } |
| 132 | + secret := strings.TrimSpace(string(contents)) |
| 133 | + if secret == "" { |
| 134 | + return "", errors.New("secret file is empty") |
| 135 | + } |
| 136 | + return secret, nil |
| 137 | +} |
| 138 | + |
| 139 | +func loadServiceTLS(path string) (*tls.Config, error) { |
| 140 | + contents, err := os.ReadFile(path) |
| 141 | + if err != nil { |
| 142 | + return nil, fmt.Errorf("read HA service CA: %w", err) |
| 143 | + } |
| 144 | + roots := x509.NewCertPool() |
| 145 | + if !roots.AppendCertsFromPEM(contents) { |
| 146 | + return nil, errors.New("HA service CA contains no certificates") |
| 147 | + } |
| 148 | + return &tls.Config{ |
| 149 | + MinVersion: tls.VersionTLS13, |
| 150 | + RootCAs: roots, |
| 151 | + }, nil |
| 152 | +} |
0 commit comments