blob: c36386c01cd8aab6ce320bd388756be2998073d8 [file] [log] [blame]
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
Serge Bazanskif05e80a2021-10-12 11:53:34 +020017// Package consensus implements a runnable that manages an etcd instance which
18// forms part of a Metropolis etcd cluster. This cluster is a foundational
19// building block of Metropolis and its startup/management sequencing needs to
20// be as robust as possible.
Serge Bazanskicb883e22020-07-06 17:47:55 +020021//
Serge Bazanskif05e80a2021-10-12 11:53:34 +020022// Cluster Structure
Serge Bazanskicb883e22020-07-06 17:47:55 +020023//
Serge Bazanskif05e80a2021-10-12 11:53:34 +020024// Each etcd instance listens for two kinds of traffic:
Serge Bazanskicb883e22020-07-06 17:47:55 +020025//
Serge Bazanskif05e80a2021-10-12 11:53:34 +020026// 1. Peer traffic over TLS on a TCP port of the node's main interface. This is
27// where other etcd instances connect to to exchange peer traffic, perform
28// transactions and build quorum. The TLS credentials are stored in a PKI that
29// is managed internally by the consensus runnable, with its state stored in
30// etcd itself.
31//
32// 2. Client traffic over a local domain socket, with access control based on
33// standard Linux user/group permissions. Currently this allows any code running
34// as root on the host namespace full access to the etcd cluster.
35//
36// This means that if code running on a node wishes to perform etcd
37// transactions, it must also run an etcd instance. This colocation of all
38// direct etcd access and the etcd intances themselves effectively delegate all
39// Metropolis control plane functionality to whatever subset of nodes is running
40// consensus and all codes that connects to etcd directly (the Curator).
41//
42// For example, if nodes foo and bar are parts of the control plane, but node
43// worker is not:
44//
45// .---------------------.
46// | node-foo |
47// |---------------------|
48// | .--------------------.
49// | | etcd |<---etcd/TLS--. (node.ConsensusPort)
50// | '--------------------' |
51// | ^ Domain Socket | |
52// | | etcd/plain | |
53// | .--------------------. |
54// | | curator |<---gRPC/TLS----. (node.CuratorServicePort)
55// | '--------------------' | |
56// | ^ Domain Socket | | |
57// | | gRPC/plain | | |
58// | .-----------------. | | |
59// | | node logic | | | |
60// | '-----------------' | | |
61// '---------------------' | |
62// | |
63// .---------------------. | |
64// | node-baz | | |
65// |---------------------| | |
66// | .--------------------. | |
67// | | etcd |<-------------' |
68// | '--------------------' |
69// | ^ Domain Socket | |
70// | | gRPC/plain | |
71// | .--------------------. |
72// | | curator |<---gRPC/TLS----:
73// | '--------------------' |
74// | ... | |
75// '---------------------' |
76// |
77// .---------------------. |
78// | node-worker | |
79// |---------------------| |
80// | .-----------------. | |
81// | | node logic |-------------------'
82// | '-----------------' |
83// '---------------------'
84//
85
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +020086package consensus
87
88import (
89 "context"
Serge Bazanskif05e80a2021-10-12 11:53:34 +020090 "crypto/ed25519"
91 "crypto/x509"
92 "crypto/x509/pkix"
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +020093 "fmt"
Serge Bazanskif05e80a2021-10-12 11:53:34 +020094 "math/big"
Serge Bazanskic1cb37c2023-03-16 17:54:33 +010095 "net"
96 "net/url"
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010097 "time"
98
Lorenz Brund13c1c62022-03-30 19:58:58 +020099 clientv3 "go.etcd.io/etcd/client/v3"
100 "go.etcd.io/etcd/server/v3/embed"
Hendrik Hofstadt8efe51e2020-02-28 12:53:41 +0100101
Serge Bazanskia105db52021-04-12 19:57:46 +0200102 "source.monogon.dev/metropolis/node/core/consensus/client"
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200103 "source.monogon.dev/metropolis/node/core/identity"
Serge Bazanski37110c32023-03-01 13:57:27 +0000104 "source.monogon.dev/metropolis/pkg/event"
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200105 "source.monogon.dev/metropolis/pkg/event/memory"
Serge Bazanski50009e02021-07-07 14:35:27 +0200106 "source.monogon.dev/metropolis/pkg/logtree/unraw"
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200107 "source.monogon.dev/metropolis/pkg/pki"
Serge Bazanski31370b02021-01-07 16:31:14 +0100108 "source.monogon.dev/metropolis/pkg/supervisor"
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +0200109)
110
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200111var (
112 pkiNamespace = pki.Namespaced("/pki/")
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +0200113)
114
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200115func pkiCA() *pki.Certificate {
116 return &pki.Certificate{
117 Name: "CA",
118 Namespace: &pkiNamespace,
119 Issuer: pki.SelfSigned,
120 Template: x509.Certificate{
121 SerialNumber: big.NewInt(1),
122 Subject: pkix.Name{
123 CommonName: "Metropolis etcd CA Certificate",
124 },
125 IsCA: true,
126 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
127 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageOCSPSigning},
128 },
129 }
130}
131
132func pkiPeerCertificate(pubkey ed25519.PublicKey, extraNames []string) x509.Certificate {
133 return x509.Certificate{
134 Subject: pkix.Name{
135 CommonName: identity.NodeID(pubkey),
136 },
137 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
138 ExtKeyUsage: []x509.ExtKeyUsage{
139 x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth,
140 },
141 DNSNames: append(extraNames, identity.NodeID(pubkey)),
142 }
143}
144
145// Service is the etcd cluster member service. See package-level documentation
146// for more information.
Serge Bazanskicb883e22020-07-06 17:47:55 +0200147type Service struct {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200148 config *Config
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100149
Serge Bazanski37110c32023-03-01 13:57:27 +0000150 value memory.Value[*Status]
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200151 ca *pki.Certificate
Serge Bazanskicb883e22020-07-06 17:47:55 +0200152}
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +0200153
Serge Bazanskicb883e22020-07-06 17:47:55 +0200154func New(config Config) *Service {
155 return &Service{
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +0200156 config: &config,
157 }
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +0200158}
159
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200160// Run is a Supervisor runnable that starts the etcd member service. It will
161// become healthy once the member joins the cluster successfully.
162func (s *Service) Run(ctx context.Context) error {
163 // Always re-create CA to make sure we don't have PKI state from previous runs.
164 //
165 // TODO(q3k): make the PKI library immune to this misuse.
166 s.ca = pkiCA()
Lorenz Brun52f7f292020-06-24 16:42:02 +0200167
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200168 // Create log converter. This will ingest etcd logs and pipe them out to this
169 // runnable's leveled logging facilities.
170 //
171 // TODO(q3k): add support for streaming to a sub-logger in the tree to get
172 // cleaner logs.
Serge Bazanskic1cb37c2023-03-16 17:54:33 +0100173
Serge Bazanski50009e02021-07-07 14:35:27 +0200174 fifoPath := s.config.Ephemeral.ServerLogsFIFO.FullPath()
Serge Bazanskic1cb37c2023-03-16 17:54:33 +0100175
176 // This is not where etcd will run, but where its log ingestion machinery lives.
177 // This ensures that the (annoying verbose) etcd logs are contained into just
178 // .etcd.
179 err := supervisor.Run(ctx, "etcd", func(ctx context.Context) error {
180 converter := unraw.Converter{
181 Parser: parseEtcdLogEntry,
182 MaximumLineLength: 8192,
183 LeveledLogger: supervisor.Logger(ctx),
184 }
185 pipe, err := converter.NamedPipeReader(fifoPath)
186 if err != nil {
187 return fmt.Errorf("when creating pipe reader: %w", err)
188 }
189 if err := supervisor.Run(ctx, "piper", pipe); err != nil {
190 return fmt.Errorf("when starting log piper: %w", err)
191 }
192 supervisor.Signal(ctx, supervisor.SignalHealthy)
193 <-ctx.Done()
194 return ctx.Err()
195 })
Serge Bazanski50009e02021-07-07 14:35:27 +0200196 if err != nil {
Serge Bazanskic1cb37c2023-03-16 17:54:33 +0100197 return fmt.Errorf("when starting etcd logger: %w", err)
Serge Bazanski50009e02021-07-07 14:35:27 +0200198 }
199
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200200 // Create autopromoter, which will automatically promote all learners to full
201 // etcd members.
202 if err := supervisor.Run(ctx, "autopromoter", s.autopromoter); err != nil {
203 return fmt.Errorf("when starting autopromtoer: %w", err)
204 }
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +0200205
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200206 // Create selfupdater, which will perform a one-shot update of this member's
207 // peer address in etcd.
Mateusz Zalega619029b2022-05-05 17:18:26 +0200208 if err := supervisor.Run(ctx, "selfupdater", s.selfupdater); err != nil {
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200209 return fmt.Errorf("when starting selfupdater: %w", err)
210 }
211
212 // Prepare cluster PKI credentials.
213 ppki := s.config.Data.PeerPKI
214 jc := s.config.JoinCluster
215 if jc != nil {
Serge Bazanski97d68082022-06-22 13:15:21 +0200216 supervisor.Logger(ctx).Info("JoinCluster set, writing PPKI data to disk...")
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200217 // For nodes that join an existing cluster, or re-join it, always write whatever
218 // we've been given on startup.
219 if err := ppki.WriteAll(jc.NodeCertificate.Raw, s.config.NodePrivateKey, jc.CACertificate.Raw); err != nil {
220 return fmt.Errorf("when writing credentials for join: %w", err)
221 }
222 if err := s.config.Data.PeerCRL.Write(jc.InitialCRL.Raw, 0400); err != nil {
223 return fmt.Errorf("when writing CRL for join: %w", err)
224 }
225 } else {
226 // For other nodes, we should already have credentials from a previous join, or
227 // a previous bootstrap. If none exist, assume we need to bootstrap these
228 // credentials.
229 //
230 // TODO(q3k): once we have node join (ie. node restart from disk) flow, add a
231 // special configuration marker to prevent spurious bootstraps.
232 absent, err := ppki.AllAbsent()
233 if err != nil {
234 return fmt.Errorf("when checking for PKI file absence: %w", err)
235 }
236 if absent {
Serge Bazanski97d68082022-06-22 13:15:21 +0200237 supervisor.Logger(ctx).Info("PKI data absent, bootstrapping.")
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200238 if err := s.bootstrap(ctx, fifoPath); err != nil {
239 return fmt.Errorf("bootstrap failed: %w", err)
240 }
241 } else {
242 supervisor.Logger(ctx).Info("PKI data present, not bootstrapping.")
243 }
244 }
245
Serge Bazanskic1cb37c2023-03-16 17:54:33 +0100246 // If we're joining a cluster, make sure that our peers are actually DNS
247 // resolvable. This prevents us from immediately failing due to transient DNS
248 // issues.
249 if jc := s.config.JoinCluster; jc != nil {
250 supervisor.Logger(ctx).Infof("Waiting for initial peers to be DNS resolvable...")
251 startLogging := time.Now().Add(5 * time.Second)
252 for {
253 allOkay := true
254 shouldLog := time.Now().After(startLogging)
255 for _, node := range jc.ExistingNodes {
256 u, _ := url.Parse(node.URL)
257 if err != nil {
258 // Just pretend this node is up. If the URL is really bad, etcd will complain
259 // more clearly than us. This shouldn't happen, anyway.
260 }
261 host := u.Hostname()
262 _, err := net.LookupIP(host)
263 if err == nil {
264 continue
265 }
266 if shouldLog {
267 supervisor.Logger(ctx).Errorf("Still can't resolve peer %s (%s): %v", node.Name, host, err)
268 }
269 allOkay = false
270 }
271 if allOkay {
272 supervisor.Logger(ctx).Infof("All peers resolvable, continuing startup.")
273 break
274 }
275
276 time.Sleep(100 * time.Millisecond)
277 if shouldLog {
278 startLogging = time.Now().Add(5 * time.Second)
279 }
280 }
281 }
282
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200283 // Start etcd ...
Serge Bazanskic1cb37c2023-03-16 17:54:33 +0100284 supervisor.Logger(ctx).Infof("Starting etcd...")
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200285 cfg := s.config.build(true)
286 server, err := embed.StartEtcd(cfg)
287 if err != nil {
288 return fmt.Errorf("when starting etcd: %w", err)
289 }
290
291 // ... wait for server to be ready...
292 select {
293 case <-ctx.Done():
294 return ctx.Err()
295 case <-server.Server.ReadyNotify():
296 }
297
298 // ... build a client to its' socket...
299 cl, err := s.config.localClient()
300 if err != nil {
301 return fmt.Errorf("getting local client failed: %w", err)
302 }
303
304 // ... and wait until we're not a learner anymore.
305 for {
306 members, err := cl.MemberList(ctx)
307 if err != nil {
308 supervisor.Logger(ctx).Warningf("MemberList failed: %v", err)
309 time.Sleep(time.Second)
310 continue
311 }
312
313 isMember := false
314 for _, member := range members.Members {
315 if member.ID != uint64(server.Server.ID()) {
316 continue
317 }
318 if !member.IsLearner {
319 isMember = true
320 break
321 }
322 }
323 if isMember {
324 break
325 }
326 supervisor.Logger(ctx).Warningf("Still a learner, waiting...")
327 time.Sleep(time.Second)
328 }
329
330 // All done! Report status.
331 supervisor.Logger(ctx).Infof("etcd server ready")
332
333 st := &Status{
334 localPeerURL: cfg.APUrls[0].String(),
335 localMemberID: uint64(server.Server.ID()),
336 cl: cl,
337 ca: s.ca,
338 }
Serge Bazanski98a6ccc2023-06-20 13:09:12 +0200339 st2 := *st
340 s.value.Set(&st2)
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200341
342 // Wait until server dies for whatever reason, update status when that
343 // happens.
344 supervisor.Signal(ctx, supervisor.SignalHealthy)
345 select {
346 case err = <-server.Err():
347 err = fmt.Errorf("server returned error: %w", err)
348 case <-ctx.Done():
349 server.Close()
350 err = ctx.Err()
351 }
Serge Bazanski98a6ccc2023-06-20 13:09:12 +0200352
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200353 st.stopped = true
Serge Bazanski98a6ccc2023-06-20 13:09:12 +0200354 st3 := *st
355 s.value.Set(&st3)
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200356 return err
Serge Bazanskicb883e22020-07-06 17:47:55 +0200357}
358
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200359func clientFor(kv *clientv3.Client, parts ...string) (client.Namespaced, error) {
360 var err error
361 namespaced := client.NewLocal(kv)
362 for _, el := range parts {
363 namespaced, err = namespaced.Sub(el)
Serge Bazanskicb883e22020-07-06 17:47:55 +0200364 if err != nil {
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200365 return nil, fmt.Errorf("when getting sub client: %w", err)
Serge Bazanskicb883e22020-07-06 17:47:55 +0200366 }
Serge Bazanskicb883e22020-07-06 17:47:55 +0200367
Serge Bazanskicb883e22020-07-06 17:47:55 +0200368 }
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200369 return namespaced, nil
370}
Serge Bazanskicb883e22020-07-06 17:47:55 +0200371
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200372// bootstrap performs a procedure to resolve the following bootstrap problems:
373// in order to start an etcd server for consensus, we need it to serve over TLS.
374// However, these TLS certificates also need to be stored in etcd so that
375// further certificates can be issued for new nodes.
376//
377// This was previously solved by a using a special PKI/TLS management system that
378// could first create certificates and keys in memory, then only commit them to
379// etcd. However, this ended up being somewhat brittle in the face of startup
380// sequencing issues, so we're now going with a different approach.
381//
382// This function starts an etcd instance first without any PKI/TLS support,
383// without listening on any external port for peer traffic. Once the instance is
384// running, it uses the standard metropolis pki library to create all required
385// data directly in the running etcd instance. It then writes all required
386// startup data (node private key, member certificate, CA certificate) to disk,
387// so that a 'full' etcd instance can be started.
388func (s *Service) bootstrap(ctx context.Context, fifoPath string) error {
389 supervisor.Logger(ctx).Infof("Bootstrapping PKI: starting etcd...")
Serge Bazanskicb883e22020-07-06 17:47:55 +0200390
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200391 cfg := s.config.build(false)
392 // This will make etcd create data directories and create a fully new cluster if
393 // needed. If we're restarting due to an error, the old cluster data will still
394 // exist.
395 cfg.ClusterState = "new"
Serge Bazanskicb883e22020-07-06 17:47:55 +0200396
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200397 // Start the bootstrap etcd instance...
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +0200398 server, err := embed.StartEtcd(cfg)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100399 if err != nil {
Serge Bazanskib76b8d12023-03-16 00:46:56 +0100400 return fmt.Errorf("failed to start bootstrap etcd: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100401 }
Serge Bazanskib76b8d12023-03-16 00:46:56 +0100402 defer server.Close()
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100403
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200404 // ... wait for it to run ...
Serge Bazanskicb883e22020-07-06 17:47:55 +0200405 select {
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200406 case <-server.Server.ReadyNotify():
Serge Bazanskicb883e22020-07-06 17:47:55 +0200407 case <-ctx.Done():
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200408 return fmt.Errorf("when waiting for bootstrap etcd: %w", err)
Lorenz Brun52f7f292020-06-24 16:42:02 +0200409 }
410
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200411 // ... create a client to it ...
412 cl, err := s.config.localClient()
Lorenz Brun52f7f292020-06-24 16:42:02 +0200413 if err != nil {
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200414 return fmt.Errorf("when getting bootstrap client: %w", err)
Serge Bazanskicb883e22020-07-06 17:47:55 +0200415 }
416
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200417 // ... and build PKI there. This is idempotent, so we will never override
418 // anything that's already in the cluster, instead just retrieve it.
419 supervisor.Logger(ctx).Infof("Bootstrapping PKI: etcd running, building PKI...")
420 clPKI, err := clientFor(cl, "namespaced", "etcd-pki")
421 if err != nil {
422 return fmt.Errorf("when getting pki client: %w", err)
Serge Bazanskicb883e22020-07-06 17:47:55 +0200423 }
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200424 defer clPKI.Close()
425 caCert, err := s.ca.Ensure(ctx, clPKI)
426 if err != nil {
427 return fmt.Errorf("failed to ensure CA certificate: %w", err)
Serge Bazanskicb883e22020-07-06 17:47:55 +0200428 }
429
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200430 // If we're running with a test overridden external address (eg. localhost), we
431 // need to also make that part of the member certificate.
432 var extraNames []string
433 if external := s.config.testOverrides.externalAddress; external != "" {
434 extraNames = []string{external}
435 }
436 memberTemplate := pki.Certificate{
437 Name: identity.NodeID(s.config.nodePublicKey()),
438 Namespace: &pkiNamespace,
439 Issuer: s.ca,
440 Template: pkiPeerCertificate(s.config.nodePublicKey(), extraNames),
441 Mode: pki.CertificateExternal,
442 PublicKey: s.config.nodePublicKey(),
443 }
444 memberCert, err := memberTemplate.Ensure(ctx, clPKI)
445 if err != nil {
446 return fmt.Errorf("failed to ensure member certificate: %w", err)
447 }
Serge Bazanskicb883e22020-07-06 17:47:55 +0200448
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200449 // Retrieve CRL.
450 crlW := s.ca.WatchCRL(clPKI)
451 crl, err := crlW.Get(ctx)
452 if err != nil {
453 return fmt.Errorf("failed to retrieve initial CRL: %w", err)
454 }
455
456 // We have everything we need. Write things to disk.
457 supervisor.Logger(ctx).Infof("Bootstrapping PKI: certificates issued, writing to disk...")
458
459 if err := s.config.Data.PeerPKI.WriteAll(memberCert, s.config.NodePrivateKey, caCert); err != nil {
460 return fmt.Errorf("failed to write bootstrapped certificates: %w", err)
461 }
462 if err := s.config.Data.PeerCRL.Write(crl.Raw, 0400); err != nil {
463 return fmt.Errorf("failed tow rite CRL: %w", err)
464 }
465
466 // Stop the server synchronously (blocking until it's fully shutdown), and
467 // return. The caller can now run the 'full' etcd instance with PKI.
468 supervisor.Logger(ctx).Infof("Bootstrapping PKI: done, stopping server...")
469 server.Close()
Serge Bazanskicb883e22020-07-06 17:47:55 +0200470 return ctx.Err()
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100471}
472
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200473// autopromoter is a runnable which repeatedly attempts to promote etcd learners
474// in the cluster to full followers. This is needed to bring any new cluster
475// members (which are always added as learners) to full membership and make them
476// part of the etcd quorum.
Serge Bazanskicb883e22020-07-06 17:47:55 +0200477func (s *Service) autopromoter(ctx context.Context) error {
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200478 autopromote := func(ctx context.Context, cl *clientv3.Client) {
479 // Only autopromote if our endpoint is a leader. This is a bargain bin version
480 // of leader election: it's simple and cheap, but not very reliable. The most
481 // obvious failure mode is that the instance we contacted isn't a leader by the
482 // time we promote a member, but that's fine - the promotion is idempotent. What
483 // we really use the 'leader election' here for isn't for consistency, but to
484 // prevent the cluster from being hammered by spurious leadership promotion
485 // requests from every etcd member.
486 status, err := cl.Status(ctx, cl.Endpoints()[0])
487 if err != nil {
488 supervisor.Logger(ctx).Warningf("Failed to get endpoint status: %v", err)
489 }
490 if status.Leader != status.Header.MemberId {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200491 return
492 }
493
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200494 members, err := cl.MemberList(ctx)
495 if err != nil {
496 supervisor.Logger(ctx).Warningf("Failed to list members: %v", err)
497 return
498 }
499 for _, member := range members.Members {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200500 if !member.IsLearner {
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100501 continue
502 }
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200503 // Always call PromoteMember since the metadata necessary to decide if we should
504 // is private. Luckily etcd already does consistency checks internally and will
505 // refuse to promote nodes that aren't connected or are still behind on
506 // transactions.
507 if _, err := cl.MemberPromote(ctx, member.ID); err != nil {
Serge Bazanskic7359672020-10-30 16:38:57 +0100508 supervisor.Logger(ctx).Infof("Failed to promote consensus node %s: %v", member.Name, err)
Serge Bazanskicb883e22020-07-06 17:47:55 +0200509 } else {
Serge Bazanskic7359672020-10-30 16:38:57 +0100510 supervisor.Logger(ctx).Infof("Promoted new consensus node %s", member.Name)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100511 }
512 }
513 }
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100514
Serge Bazanski37110c32023-03-01 13:57:27 +0000515 w := s.value.Watch()
Serge Bazanskicb883e22020-07-06 17:47:55 +0200516 for {
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200517 st, err := w.Get(ctx)
518 if err != nil {
519 return fmt.Errorf("status get failed: %w", err)
Lorenz Brun52f7f292020-06-24 16:42:02 +0200520 }
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200521 t := time.NewTicker(5 * time.Second)
522 for {
523 autopromote(ctx, st.cl)
524 select {
525 case <-ctx.Done():
526 t.Stop()
527 return ctx.Err()
528 case <-t.C:
Serge Bazanskicb883e22020-07-06 17:47:55 +0200529 }
530 }
531 }
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +0200532}
533
Serge Bazanski37110c32023-03-01 13:57:27 +0000534func (s *Service) Watch() event.Watcher[*Status] {
535 return s.value.Watch()
536}
537
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200538// selfupdater is a runnable that performs a one-shot (once per Service Run,
539// thus once for each configuration) update of the node's Peer URL in etcd. This
540// is currently only really needed because the first node in the cluster
541// bootstraps itself without any peer URLs at first, and this allows it to then
542// add the peer URLs afterwards. Instead of a runnable, this might as well have
543// been part of the bootstarp logic, but making it a restartable runnable is
544// more robust.
545func (s *Service) selfupdater(ctx context.Context) error {
546 supervisor.Signal(ctx, supervisor.SignalHealthy)
Serge Bazanski37110c32023-03-01 13:57:27 +0000547 w := s.value.Watch()
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200548 for {
549 st, err := w.Get(ctx)
550 if err != nil {
551 return fmt.Errorf("failed to get status: %w", err)
552 }
553
Serge Bazanski5839e972021-11-16 15:46:19 +0100554 if st.localPeerURL != "" {
555 supervisor.Logger(ctx).Infof("Updating local peer URL...")
556 peerURL := st.localPeerURL
557 if _, err := st.cl.MemberUpdate(ctx, st.localMemberID, []string{peerURL}); err != nil {
558 supervisor.Logger(ctx).Warningf("failed to update member: %v", err)
559 time.Sleep(1 * time.Second)
560 continue
561 }
562 } else {
563 supervisor.Logger(ctx).Infof("No local peer URL, not updating.")
Serge Bazanskif05e80a2021-10-12 11:53:34 +0200564 }
565
566 supervisor.Signal(ctx, supervisor.SignalDone)
567 return nil
Serge Bazanskia105db52021-04-12 19:57:46 +0200568 }
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +0200569}