blob: 583d72f5bc6e345e7d985705cee47c6908b0c89a [file] [log] [blame]
Lorenz Brunae0d90d2019-09-05 17:53:56 +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
17package main
18
19import (
Serge Bazanskicdb8c782020-02-17 12:34:02 +010020 "context"
Lorenz Brundd8c80e2019-10-07 16:19:49 +020021 "fmt"
Serge Bazanskie803fc12022-01-25 14:58:24 +010022 "io"
Lorenz Brun0e291a12023-06-01 12:22:45 +020023 "net"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020024 "os"
Serge Bazanski3b098232023-03-16 17:57:02 +010025 "strings"
Serge Bazanskif2f85f52023-03-16 11:51:19 +010026 "time"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020027
Lorenz Brunae0d90d2019-09-05 17:53:56 +020028 "golang.org/x/sys/unix"
Serge Bazanski99f47742021-08-04 20:21:42 +020029
Lorenz Brun0e291a12023-06-01 12:22:45 +020030 "source.monogon.dev/metropolis/node"
Serge Bazanski31370b02021-01-07 16:31:14 +010031 "source.monogon.dev/metropolis/node/core/cluster"
Lorenz Brun6c454342023-06-01 12:23:38 +020032 "source.monogon.dev/metropolis/node/core/devmgr"
Serge Bazanski31370b02021-01-07 16:31:14 +010033 "source.monogon.dev/metropolis/node/core/localstorage"
34 "source.monogon.dev/metropolis/node/core/localstorage/declarative"
35 "source.monogon.dev/metropolis/node/core/network"
Serge Bazanskif9edf522021-06-17 15:57:13 +020036 "source.monogon.dev/metropolis/node/core/roleserve"
Serge Bazanski58ddc092022-06-30 18:23:33 +020037 "source.monogon.dev/metropolis/node/core/rpc/resolver"
Lorenz Brune306d782021-09-01 13:01:06 +020038 timesvc "source.monogon.dev/metropolis/node/core/time"
Lorenz Brun35fcf032023-06-29 04:15:58 +020039 "source.monogon.dev/metropolis/node/core/update"
Serge Bazanski31370b02021-01-07 16:31:14 +010040 "source.monogon.dev/metropolis/pkg/logtree"
41 "source.monogon.dev/metropolis/pkg/supervisor"
42 "source.monogon.dev/metropolis/pkg/tpm"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020043)
44
45func main() {
Serge Bazanskie803fc12022-01-25 14:58:24 +010046 // Set up basic mounts (like /dev, /sys...).
47 if err := setupMounts(); err != nil {
48 panic(fmt.Errorf("could not set up basic mounts: %w", err))
Lorenz Brunae0d90d2019-09-05 17:53:56 +020049 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010050
Serge Bazanskif2f85f52023-03-16 11:51:19 +010051 // Root system logtree.
52 lt := logtree.New()
53
Serge Bazanskie803fc12022-01-25 14:58:24 +010054 // Set up logger for Metropolis. Currently logs everything to /dev/tty0 and
Lorenz Brunf0b22ff2023-05-02 16:04:20 +020055 // /dev/ttyS{0,1}.
Serge Bazanski3b098232023-03-16 17:57:02 +010056 consoles := []console{
57 {
58 path: "/dev/tty0",
59 maxWidth: 80,
60 },
61 {
62 path: "/dev/ttyS0",
63 maxWidth: 120,
64 },
Lorenz Brunf0b22ff2023-05-02 16:04:20 +020065 {
66 path: "/dev/ttyS1",
67 maxWidth: 120,
68 },
Serge Bazanski3b098232023-03-16 17:57:02 +010069 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010070 // Alternative channel that crash handling writes to, and which gets distributed
71 // to the consoles.
72 crash := make(chan string)
73
74 // Open up consoles and set up logging from logtree and crash channel.
Serge Bazanski3b098232023-03-16 17:57:02 +010075 for _, console := range consoles {
76 f, err := os.OpenFile(console.path, os.O_WRONLY, 0)
Serge Bazanskie803fc12022-01-25 14:58:24 +010077 if err != nil {
78 continue
Serge Bazanskic7359672020-10-30 16:38:57 +010079 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010080 reader, err := lt.Read("", logtree.WithChildren(), logtree.WithStream())
81 if err != nil {
82 panic(fmt.Errorf("could not set up root log reader: %v", err))
83 }
Serge Bazanski3b098232023-03-16 17:57:02 +010084 console.reader = reader
85 go func(path string, maxWidth int, f io.Writer) {
Serge Bazanskie803fc12022-01-25 14:58:24 +010086 fmt.Fprintf(f, "\nMetropolis: this is %s. Verbose node logs follow.\n\n", path)
87 for {
Serge Bazanskif2f85f52023-03-16 11:51:19 +010088 select {
89 case p := <-reader.Stream:
Serge Bazanski3b098232023-03-16 17:57:02 +010090 if consoleFilter(p) {
91 fmt.Fprintf(f, "%s\n", p.ConciseString(logtree.MetropolisShortenDict, maxWidth))
92 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010093 case s := <-crash:
94 fmt.Fprintf(f, "%s\n", s)
95 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010096 }
Serge Bazanski3b098232023-03-16 17:57:02 +010097 }(console.path, console.maxWidth, f)
Serge Bazanskie803fc12022-01-25 14:58:24 +010098 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010099
Lorenz Brun4025c9b2022-06-16 16:12:53 +0000100 // Initialize persistent panic handler early
Serge Bazanski5f8414d2022-06-24 13:02:11 +0200101 initPanicHandler(lt, consoles)
Serge Bazanskic7359672020-10-30 16:38:57 +0100102
103 // Initial logger. Used until we get to a supervisor.
104 logger := lt.MustLeveledFor("init")
Serge Bazanski581b0bd2020-03-12 13:36:43 +0100105
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200106 // Linux kernel default is 4096 which is far too low. Raise it to 1M which
107 // is what gVisor suggests.
Lorenz Brun878f5f92020-05-12 16:15:39 +0200108 if err := unix.Setrlimit(unix.RLIMIT_NOFILE, &unix.Rlimit{Cur: 1048576, Max: 1048576}); err != nil {
Serge Bazanskic7359672020-10-30 16:38:57 +0100109 logger.Fatalf("Failed to raise rlimits: %v", err)
Lorenz Brun878f5f92020-05-12 16:15:39 +0200110 }
111
Serge Bazanski662b5b32020-12-21 13:49:00 +0100112 logger.Info("Starting Metropolis node init")
Tim Windelschmidt0b84a9f2023-07-27 14:20:31 +0000113 logger.Infof("Version: %s", node.Version)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200114
Serge Bazanski5df62ba2023-03-22 17:56:46 +0100115 haveTPM := true
Serge Bazanskic7359672020-10-30 16:38:57 +0100116 if err := tpm.Initialize(logger); err != nil {
Serge Bazanski5df62ba2023-03-22 17:56:46 +0100117 logger.Warningf("Failed to initialize TPM 2.0: %v", err)
118 haveTPM = false
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200119 }
120
Lorenz Brun3ecb04a2023-03-16 20:41:20 +0100121 networkSvc := network.New(nil)
122 networkSvc.DHCPVendorClassID = "dev.monogon.metropolis.node.v1"
Lorenz Brun0e291a12023-06-01 12:22:45 +0200123 networkSvc.ExtraDNSListenerIPs = []net.IP{node.ContainerDNSIP}
Lorenz Brune306d782021-09-01 13:01:06 +0200124 timeSvc := timesvc.New()
Lorenz Brun6c454342023-06-01 12:23:38 +0200125 devmgrSvc := devmgr.New()
Leopold Schabel68c58752019-11-14 21:00:59 +0100126
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200127 // This function initializes a headless Delve if this is a debug build or
128 // does nothing if it's not
Lorenz Brun70f65b22020-07-08 17:02:47 +0200129 initializeDebugger(networkSvc)
130
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200131 // Prepare local storage.
132 root := &localstorage.Root{}
133 if err := declarative.PlaceFS(root, "/"); err != nil {
134 panic(fmt.Errorf("when placing root FS: %w", err))
135 }
136
Lorenz Brun35fcf032023-06-29 04:15:58 +0200137 updateSvc := &update.Service{
138 Logger: lt.MustLeveledFor("update"),
139 }
140
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200141 // Make context for supervisor. We cancel it when we reach the trapdoor.
142 ctxS, ctxC := context.WithCancel(context.Background())
143
Serge Bazanski58ddc092022-06-30 18:23:33 +0200144 // Make node-wide cluster resolver.
145 res := resolver.New(ctxS, resolver.WithLogger(func(f string, args ...interface{}) {
146 lt.MustLeveledFor("resolver").WithAddedStackDepth(1).Infof(f, args...)
147 }))
148
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100149 // Function which performs core, one-way initialization of the node. This means
150 // waiting for the network, starting the cluster manager, and then starting all
151 // services related to the node's roles.
152 init := func(ctx context.Context) error {
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200153 // Start storage and network - we need this to get anything else done.
Lorenz Brun35fcf032023-06-29 04:15:58 +0200154 if err := root.Start(ctx, updateSvc); err != nil {
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200155 return fmt.Errorf("cannot start root FS: %w", err)
156 }
Lorenz Brun85ad26a2023-03-27 17:00:00 +0200157 nodeParams, err := getNodeParams(ctx, root)
158 if err != nil {
159 return fmt.Errorf("cannot get node parameters: %w", err)
160 }
161 if nodeParams.NetworkConfig != nil {
162 networkSvc.StaticConfig = nodeParams.NetworkConfig
163 if err := root.ESP.Metropolis.NetworkConfiguration.Marshal(nodeParams.NetworkConfig); err != nil {
164 logger.Errorf("Error writing back network_config from NodeParameters: %v", err)
165 }
166 }
167 if networkSvc.StaticConfig == nil {
168 staticConfig, err := root.ESP.Metropolis.NetworkConfiguration.Unmarshal()
169 if err == nil {
170 networkSvc.StaticConfig = staticConfig
171 } else {
172 logger.Errorf("Unable to load static config, proceeding without it: %v", err)
173 }
Lorenz Brunab583b32023-05-02 22:41:45 +0200174 }
Lorenz Brun6c454342023-06-01 12:23:38 +0200175 if err := supervisor.Run(ctx, "devmgr", devmgrSvc.Run); err != nil {
176 return fmt.Errorf("when starting devmgr: %w", err)
177 }
Lorenz Brunab583b32023-05-02 22:41:45 +0200178 if err := supervisor.Run(ctx, "network", networkSvc.Run); err != nil {
179 return fmt.Errorf("when starting network: %w", err)
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100180 }
Lorenz Brune306d782021-09-01 13:01:06 +0200181 if err := supervisor.Run(ctx, "time", timeSvc.Run); err != nil {
182 return fmt.Errorf("when starting time: %w", err)
183 }
Lorenz Brun1b2df232022-06-14 12:42:03 +0200184 if err := supervisor.Run(ctx, "pstore", dumpAndCleanPstore); err != nil {
185 return fmt.Errorf("when starting pstore: %w", err)
186 }
Tim Windelschmidtd9f1f1e2023-10-31 15:44:35 +0100187 if err := supervisor.Run(ctx, "sysctl", nodeSysctls); err != nil {
188 return fmt.Errorf("when applying sysctls: %w", err)
189 }
Lorenz Brunf95909d2019-09-11 19:48:26 +0200190
Lorenz Brun6eb3fb32023-08-09 17:19:24 +0200191 // The kernel does of course not run in this runnable, only the log pipe
192 // runs in it.
193 if err := supervisor.Run(ctx, "kernel", func(ctx context.Context) error {
194 return logtree.KmsgPipe(ctx, supervisor.Logger(ctx))
195 }); err != nil {
196 return fmt.Errorf("when starting kernel log pipe: %w", err)
197 }
198
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100199 // Start the role service. The role service connects to the curator and runs
200 // all node-specific role code (eg. Kubernetes services).
201 // supervisor.Logger(ctx).Infof("Starting role service...")
202 rs := roleserve.New(roleserve.Config{
203 StorageRoot: root,
204 Network: networkSvc,
Serge Bazanski58ddc092022-06-30 18:23:33 +0200205 Resolver: res,
Serge Bazanskie012b722023-03-29 17:49:04 +0200206 LogTree: lt,
Lorenz Brun35fcf032023-06-29 04:15:58 +0200207 Update: updateSvc,
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100208 })
209 if err := supervisor.Run(ctx, "role", rs.Run); err != nil {
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100210 return fmt.Errorf("failed to start role service: %w", err)
211 }
212
Lorenz Brunac82c0d2022-03-01 13:32:45 +0100213 if err := runDebugService(ctx, rs, lt, root); err != nil {
214 return fmt.Errorf("when starting debug service: %w", err)
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100215 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200216
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100217 // Start cluster manager. This kicks off cluster membership machinery,
218 // which will either start a new cluster, enroll into one or join one.
Lorenz Brun35fcf032023-06-29 04:15:58 +0200219 m := cluster.NewManager(root, networkSvc, rs, updateSvc, nodeParams, haveTPM)
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100220 return m.Run(ctx)
221 }
222
223 // Start the init function in a one-shot runnable. Smuggle out any errors from
224 // the init function and stuff them into the fatal channel. This is where the
225 // system supervisor takes over as the main process management system.
226 fatal := make(chan error)
227 supervisor.New(ctxS, func(ctx context.Context) error {
228 err := init(ctx)
229 if err != nil {
230 fatal <- err
231 select {}
232 }
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200233 return nil
Serge Bazanskic7359672020-10-30 16:38:57 +0100234 }, supervisor.WithExistingLogtree(lt))
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100235
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100236 // Meanwhile, wait for any fatal error from the init process, and handle it
237 // accordingly.
238 err := <-fatal
239 // Log error with primary logging mechanism still active.
240 logger.Infof("Node startup failed: %v", err)
241 // Start shutting down the supervision tree...
Serge Bazanskieac8f732021-10-05 23:30:37 +0200242 ctxC()
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100243 time.Sleep(time.Second)
244 // After a bit, kill all console log readers.
Serge Bazanski3b098232023-03-16 17:57:02 +0100245 for _, console := range consoles {
Serge Bazanskid02f2162023-03-22 17:57:20 +0100246 if console.reader == nil {
247 continue
248 }
Serge Bazanski3b098232023-03-16 17:57:02 +0100249 console.reader.Close()
250 console.reader.Stream = nil
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100251 }
252 // Wait for final logs to flush to console...
253 time.Sleep(time.Second)
254 // Present final message to the console.
255 crash <- ""
256 crash <- ""
Serge Bazanskie6719b32023-03-22 17:57:50 +0100257 crash <- fmt.Sprintf(" Fatal error: %v", err)
258 crash <- fmt.Sprintf(" This node could not be started. Rebooting...")
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100259 time.Sleep(time.Second)
260 // Return to minit, which will reboot this node.
Serge Bazanskie6719b32023-03-22 17:57:50 +0100261 os.Exit(0)
Serge Bazanski57b43752020-07-13 19:17:48 +0200262}
Serge Bazanski3b098232023-03-16 17:57:02 +0100263
264// consoleFilter is used to filter out some uselessly verbose logs from the
265// console.
266//
267// This should be limited to external services, our internal services should
268// instead just have good logging by default.
269func consoleFilter(p *logtree.LogEntry) bool {
270 if p.Raw != nil {
271 return false
272 }
273 if p.Leveled == nil {
274 return false
275 }
276 s := string(p.DN)
277 if strings.HasPrefix(s, "root.role.controlplane.launcher.consensus.etcd") {
278 return p.Leveled.Severity().AtLeast(logtree.WARNING)
279 }
280 // TODO(q3k): turn off RPC traces instead
281 if strings.HasPrefix(s, "root.role.controlplane.launcher.curator.listener.rpc") {
282 return false
283 }
284 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.networked.kubelet") {
285 return p.Leveled.Severity().AtLeast(logtree.WARNING)
286 }
287 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.networked.apiserver") {
288 return p.Leveled.Severity().AtLeast(logtree.WARNING)
289 }
290 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.controller-manager") {
291 return p.Leveled.Severity().AtLeast(logtree.WARNING)
292 }
293 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.scheduler") {
294 return p.Leveled.Severity().AtLeast(logtree.WARNING)
295 }
Lorenz Brun6eb3fb32023-08-09 17:19:24 +0200296 if strings.HasPrefix(s, "root.kernel") {
297 // Linux writes high-severity logs directly to the console anyways and
298 // its low-severity logs are too verbose.
299 return false
300 }
Serge Bazanski6b7731e2023-03-22 17:58:04 +0100301 if strings.HasPrefix(s, "supervisor") {
302 return p.Leveled.Severity().AtLeast(logtree.WARNING)
303 }
Serge Bazanski3b098232023-03-16 17:57:02 +0100304 return true
305}
306
307type console struct {
308 path string
309 maxWidth int
310 reader *logtree.LogReader
311}