blob: d5eee035203e99197d3ad08b3a9f9e821eebfedd [file] [log] [blame]
Serge Bazanski42e61c62021-03-18 15:07:18 +01001// 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 Bazanskia959cbd2021-06-17 15:56:51 +020017// cluster implements low-level clustering logic, especially logic regarding to
18// bootstrapping, registering into and joining a cluster. Its goal is to provide
19// the rest of the node code with the following:
20// - A mounted plaintext storage.
21// - Node credentials/identity.
22// - A locally running etcd server if the node is supposed to run one, and a
23// client connection to that etcd cluster if so.
24// - The state of the cluster as seen by the node, to enable code to respond to
25// node lifecycle changes.
Serge Bazanski42e61c62021-03-18 15:07:18 +010026package cluster
27
28import (
Serge Bazanskia959cbd2021-06-17 15:56:51 +020029 "context"
Leopold Schabela5545282021-12-04 23:29:44 +010030 "encoding/base64"
Serge Bazanskia959cbd2021-06-17 15:56:51 +020031 "errors"
Serge Bazanski42e61c62021-03-18 15:07:18 +010032 "fmt"
Leopold Schabela5545282021-12-04 23:29:44 +010033 "io"
34 "net/http"
Lorenz Brun764a2de2021-11-22 16:26:36 +010035 "os"
Mateusz Zalega2930e992022-04-25 12:52:35 +020036 "strings"
Serge Bazanskia959cbd2021-06-17 15:56:51 +020037 "sync"
Serge Bazanski42e61c62021-03-18 15:07:18 +010038
Leopold Schabela5545282021-12-04 23:29:44 +010039 "github.com/cenkalti/backoff/v4"
Serge Bazanskia959cbd2021-06-17 15:56:51 +020040 "google.golang.org/protobuf/proto"
41
42 "source.monogon.dev/metropolis/node/core/consensus"
43 "source.monogon.dev/metropolis/node/core/localstorage"
44 "source.monogon.dev/metropolis/node/core/network"
Serge Bazanski6dff6d62022-01-28 18:15:14 +010045 "source.monogon.dev/metropolis/node/core/roleserve"
Serge Bazanskia959cbd2021-06-17 15:56:51 +020046 "source.monogon.dev/metropolis/pkg/event/memory"
47 "source.monogon.dev/metropolis/pkg/supervisor"
48 apb "source.monogon.dev/metropolis/proto/api"
Mateusz Zalega2930e992022-04-25 12:52:35 +020049 cpb "source.monogon.dev/metropolis/proto/common"
Serge Bazanskia959cbd2021-06-17 15:56:51 +020050 ppb "source.monogon.dev/metropolis/proto/private"
Serge Bazanski42e61c62021-03-18 15:07:18 +010051)
52
Serge Bazanskia959cbd2021-06-17 15:56:51 +020053type state struct {
54 mu sync.RWMutex
Serge Bazanski42e61c62021-03-18 15:07:18 +010055
Serge Bazanskia959cbd2021-06-17 15:56:51 +020056 oneway bool
Serge Bazanski42e61c62021-03-18 15:07:18 +010057
Serge Bazanskia959cbd2021-06-17 15:56:51 +020058 configuration *ppb.SealedConfiguration
Serge Bazanski42e61c62021-03-18 15:07:18 +010059}
60
Serge Bazanskia959cbd2021-06-17 15:56:51 +020061type Manager struct {
62 storageRoot *localstorage.Root
63 networkService *network.Service
Serge Bazanski6dff6d62022-01-28 18:15:14 +010064 roleServer *roleserve.Service
Serge Bazanskia959cbd2021-06-17 15:56:51 +020065 status memory.Value
66
67 state
68
69 // consensus is the spawned etcd/consensus service, if the Manager brought
70 // up a Node that should run one.
71 consensus *consensus.Service
72}
73
74// NewManager creates a new cluster Manager. The given localstorage Root must
75// be places, but not yet started (and will be started as the Manager makes
76// progress). The given network Service must already be running.
Serge Bazanski6dff6d62022-01-28 18:15:14 +010077func NewManager(storageRoot *localstorage.Root, networkService *network.Service, rs *roleserve.Service) *Manager {
Serge Bazanskia959cbd2021-06-17 15:56:51 +020078 return &Manager{
79 storageRoot: storageRoot,
80 networkService: networkService,
Serge Bazanski6dff6d62022-01-28 18:15:14 +010081 roleServer: rs,
Serge Bazanskia959cbd2021-06-17 15:56:51 +020082
83 state: state{},
84 }
85}
86
87func (m *Manager) lock() (*state, func()) {
88 m.mu.Lock()
89 return &m.state, m.mu.Unlock
90}
91
92func (m *Manager) rlock() (*state, func()) {
93 m.mu.RLock()
94 return &m.state, m.mu.RUnlock
95}
96
97// Run is the runnable of the Manager, to be started using the Supervisor. It
98// is one-shot, and should not be restarted.
99func (m *Manager) Run(ctx context.Context) error {
100 state, unlock := m.lock()
101 if state.oneway {
102 unlock()
103 // TODO(q3k): restart the entire system if this happens
104 return fmt.Errorf("cannot restart cluster manager")
105 }
106 state.oneway = true
107 unlock()
108
Lorenz Brun6c35e972021-12-14 03:08:23 +0100109 configuration, err := m.storageRoot.ESP.Metropolis.SealedConfiguration.Unseal()
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200110 if err == nil {
111 supervisor.Logger(ctx).Info("Sealed configuration present. attempting to join cluster")
Mateusz Zalega2930e992022-04-25 12:52:35 +0200112
113 // Read Cluster Directory and unmarshal it. Since the node is already
114 // registered with the cluster, the directory won't be bootstrapped from
115 // Node Parameters.
116 cd, err := m.storageRoot.ESP.Metropolis.ClusterDirectory.Unmarshal()
117 if err != nil {
118 return fmt.Errorf("while reading cluster directory: %w", err)
119 }
120 return m.join(ctx, configuration, cd)
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200121 }
122
123 if !errors.Is(err, localstorage.ErrNoSealed) {
124 return fmt.Errorf("unexpected sealed config error: %w", err)
125 }
126
127 supervisor.Logger(ctx).Info("No sealed configuration, looking for node parameters")
128
129 params, err := m.nodeParams(ctx)
130 if err != nil {
131 return fmt.Errorf("no parameters available: %w", err)
132 }
133
134 switch inner := params.Cluster.(type) {
135 case *apb.NodeParameters_ClusterBootstrap_:
Serge Bazanski5839e972021-11-16 15:46:19 +0100136 err = m.bootstrap(ctx, inner.ClusterBootstrap)
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200137 case *apb.NodeParameters_ClusterRegister_:
Serge Bazanski5839e972021-11-16 15:46:19 +0100138 err = m.register(ctx, inner.ClusterRegister)
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200139 default:
Serge Bazanski5839e972021-11-16 15:46:19 +0100140 err = fmt.Errorf("node parameters misconfigured: neither cluster_bootstrap nor cluster_register set")
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200141 }
Serge Bazanski5839e972021-11-16 15:46:19 +0100142
143 if err == nil {
144 supervisor.Logger(ctx).Info("Cluster enrolment done.")
145 }
146 return err
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200147}
148
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200149func (m *Manager) nodeParamsFWCFG(ctx context.Context) (*apb.NodeParameters, error) {
Lorenz Brun764a2de2021-11-22 16:26:36 +0100150 bytes, err := os.ReadFile("/sys/firmware/qemu_fw_cfg/by_name/dev.monogon.metropolis/parameters.pb/raw")
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200151 if err != nil {
152 return nil, fmt.Errorf("could not read firmware enrolment file: %w", err)
153 }
154
155 config := apb.NodeParameters{}
156 err = proto.Unmarshal(bytes, &config)
157 if err != nil {
158 return nil, fmt.Errorf("could not unmarshal: %v", err)
159 }
160
161 return &config, nil
162}
163
Leopold Schabela5545282021-12-04 23:29:44 +0100164// nodeParamsGCPMetadata attempts to retrieve the node parameters from the
165// GCP metadata service. Returns nil if the metadata service is available,
166// but no node parameters are specified.
167func (m *Manager) nodeParamsGCPMetadata(ctx context.Context) (*apb.NodeParameters, error) {
168 const metadataURL = "http://169.254.169.254/computeMetadata/v1/instance/attributes/metropolis-node-params"
169 req, err := http.NewRequestWithContext(ctx, "GET", metadataURL, nil)
170 if err != nil {
171 return nil, fmt.Errorf("could not create request: %w", err)
172 }
173 req.Header.Set("Metadata-Flavor", "Google")
174 resp, err := http.DefaultClient.Do(req)
175 if err != nil {
176 return nil, fmt.Errorf("HTTP request failed: %w", err)
177 }
178 defer resp.Body.Close()
179 if resp.StatusCode != http.StatusOK {
180 if resp.StatusCode == http.StatusNotFound {
181 return nil, nil
182 }
183 return nil, fmt.Errorf("non-200 status code: %d", resp.StatusCode)
184 }
185 decoded, err := io.ReadAll(base64.NewDecoder(base64.StdEncoding, resp.Body))
186 if err != nil {
187 return nil, fmt.Errorf("cannot decode base64: %w", err)
188 }
189 config := apb.NodeParameters{}
190 err = proto.Unmarshal(decoded, &config)
191 if err != nil {
192 return nil, fmt.Errorf("failed unmarshalling NodeParameters: %w", err)
193 }
194 return &config, nil
195}
196
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200197func (m *Manager) nodeParams(ctx context.Context) (*apb.NodeParameters, error) {
Leopold Schabela5545282021-12-04 23:29:44 +0100198 boardName, err := getDMIBoardName()
199 if err != nil {
200 supervisor.Logger(ctx).Warningf("Could not get board name, cannot detect platform: %v", err)
201 }
202 supervisor.Logger(ctx).Infof("Board name: %q", boardName)
203
204 // When running on GCP, attempt to retrieve the node parameters from the
205 // metadata server first. Retry until we get a response, since we need to
206 // wait for the network service to assign an IP address first.
207 if isGCPInstance(boardName) {
208 var params *apb.NodeParameters
209 op := func() error {
210 supervisor.Logger(ctx).Info("Running on GCP, attempting to retrieve node parameters from metadata server")
211 params, err = m.nodeParamsGCPMetadata(ctx)
212 return err
213 }
214 err := backoff.Retry(op, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
215 if err != nil {
216 supervisor.Logger(ctx).Errorf("Failed to retrieve node parameters: %v", err)
217 }
218 if params != nil {
219 supervisor.Logger(ctx).Info("Retrieved parameters from GCP metadata server")
220 return params, nil
221 }
222 supervisor.Logger(ctx).Infof("\"metropolis-node-params\" metadata not found")
223 }
224
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200225 // Retrieve node parameters from qemu's fwcfg interface or ESP.
226 // TODO(q3k): probably abstract this away and implement per platform/build/...
227 paramsFWCFG, err := m.nodeParamsFWCFG(ctx)
228 if err != nil {
229 supervisor.Logger(ctx).Warningf("Could not retrieve node parameters from qemu fwcfg: %v", err)
230 paramsFWCFG = nil
231 } else {
232 supervisor.Logger(ctx).Infof("Retrieved node parameters from qemu fwcfg")
233 }
Lorenz Brun6c35e972021-12-14 03:08:23 +0100234 paramsESP, err := m.storageRoot.ESP.Metropolis.NodeParameters.Unmarshal()
Serge Bazanskia959cbd2021-06-17 15:56:51 +0200235 if err != nil {
236 supervisor.Logger(ctx).Warningf("Could not retrieve node parameters from ESP: %v", err)
237 paramsESP = nil
238 } else {
239 supervisor.Logger(ctx).Infof("Retrieved node parameters from ESP")
240 }
241 if paramsFWCFG == nil && paramsESP == nil {
242 return nil, fmt.Errorf("could not find node parameters in ESP or qemu fwcfg")
243 }
244 if paramsFWCFG != nil && paramsESP != nil {
245 supervisor.Logger(ctx).Warningf("Node parameters found both in both ESP and qemu fwcfg, using the latter")
246 return paramsFWCFG, nil
247 } else if paramsFWCFG != nil {
248 return paramsFWCFG, nil
249 } else {
250 return paramsESP, nil
251 }
252}
253
Mateusz Zalega2930e992022-04-25 12:52:35 +0200254// logClusterDirectory verbosely logs the whole Cluster Directory passed to it.
255func logClusterDirectory(ctx context.Context, cd *cpb.ClusterDirectory) {
256 for _, node := range cd.Nodes {
Mateusz Zalega2930e992022-04-25 12:52:35 +0200257 var addresses []string
258 for _, add := range node.Addresses {
259 addresses = append(addresses, add.Host)
260 }
Mateusz Zalegade821502022-04-29 16:37:17 +0200261 supervisor.Logger(ctx).Infof(" Addresses: %s", strings.Join(addresses, ","))
Mateusz Zalega2930e992022-04-25 12:52:35 +0200262 }
263}