blob: d40942d43bd4af9010a7944794df5f1736a45905 [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"
Serge Bazanski31370b02021-01-07 16:31:14 +010039 "source.monogon.dev/metropolis/pkg/logtree"
40 "source.monogon.dev/metropolis/pkg/supervisor"
41 "source.monogon.dev/metropolis/pkg/tpm"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020042)
43
44func main() {
Serge Bazanskie803fc12022-01-25 14:58:24 +010045 // Set up basic mounts (like /dev, /sys...).
46 if err := setupMounts(); err != nil {
47 panic(fmt.Errorf("could not set up basic mounts: %w", err))
Lorenz Brunae0d90d2019-09-05 17:53:56 +020048 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010049
Serge Bazanskif2f85f52023-03-16 11:51:19 +010050 // Root system logtree.
51 lt := logtree.New()
52
Serge Bazanskie803fc12022-01-25 14:58:24 +010053 // Set up logger for Metropolis. Currently logs everything to /dev/tty0 and
Lorenz Brunf0b22ff2023-05-02 16:04:20 +020054 // /dev/ttyS{0,1}.
Serge Bazanski3b098232023-03-16 17:57:02 +010055 consoles := []console{
56 {
57 path: "/dev/tty0",
58 maxWidth: 80,
59 },
60 {
61 path: "/dev/ttyS0",
62 maxWidth: 120,
63 },
Lorenz Brunf0b22ff2023-05-02 16:04:20 +020064 {
65 path: "/dev/ttyS1",
66 maxWidth: 120,
67 },
Serge Bazanski3b098232023-03-16 17:57:02 +010068 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010069 // Alternative channel that crash handling writes to, and which gets distributed
70 // to the consoles.
71 crash := make(chan string)
72
73 // Open up consoles and set up logging from logtree and crash channel.
Serge Bazanski3b098232023-03-16 17:57:02 +010074 for _, console := range consoles {
75 f, err := os.OpenFile(console.path, os.O_WRONLY, 0)
Serge Bazanskie803fc12022-01-25 14:58:24 +010076 if err != nil {
77 continue
Serge Bazanskic7359672020-10-30 16:38:57 +010078 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010079 reader, err := lt.Read("", logtree.WithChildren(), logtree.WithStream())
80 if err != nil {
81 panic(fmt.Errorf("could not set up root log reader: %v", err))
82 }
Serge Bazanski3b098232023-03-16 17:57:02 +010083 console.reader = reader
84 go func(path string, maxWidth int, f io.Writer) {
Serge Bazanskie803fc12022-01-25 14:58:24 +010085 fmt.Fprintf(f, "\nMetropolis: this is %s. Verbose node logs follow.\n\n", path)
86 for {
Serge Bazanskif2f85f52023-03-16 11:51:19 +010087 select {
88 case p := <-reader.Stream:
Serge Bazanski3b098232023-03-16 17:57:02 +010089 if consoleFilter(p) {
90 fmt.Fprintf(f, "%s\n", p.ConciseString(logtree.MetropolisShortenDict, maxWidth))
91 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010092 case s := <-crash:
93 fmt.Fprintf(f, "%s\n", s)
94 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010095 }
Serge Bazanski3b098232023-03-16 17:57:02 +010096 }(console.path, console.maxWidth, f)
Serge Bazanskie803fc12022-01-25 14:58:24 +010097 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010098
Lorenz Brun4025c9b2022-06-16 16:12:53 +000099 // Initialize persistent panic handler early
Serge Bazanski5f8414d2022-06-24 13:02:11 +0200100 initPanicHandler(lt, consoles)
Serge Bazanskic7359672020-10-30 16:38:57 +0100101
102 // Initial logger. Used until we get to a supervisor.
103 logger := lt.MustLeveledFor("init")
Serge Bazanski581b0bd2020-03-12 13:36:43 +0100104
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200105 // Linux kernel default is 4096 which is far too low. Raise it to 1M which
106 // is what gVisor suggests.
Lorenz Brun878f5f92020-05-12 16:15:39 +0200107 if err := unix.Setrlimit(unix.RLIMIT_NOFILE, &unix.Rlimit{Cur: 1048576, Max: 1048576}); err != nil {
Serge Bazanskic7359672020-10-30 16:38:57 +0100108 logger.Fatalf("Failed to raise rlimits: %v", err)
Lorenz Brun878f5f92020-05-12 16:15:39 +0200109 }
110
Serge Bazanski662b5b32020-12-21 13:49:00 +0100111 logger.Info("Starting Metropolis node init")
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200112
Serge Bazanski5df62ba2023-03-22 17:56:46 +0100113 haveTPM := true
Serge Bazanskic7359672020-10-30 16:38:57 +0100114 if err := tpm.Initialize(logger); err != nil {
Serge Bazanski5df62ba2023-03-22 17:56:46 +0100115 logger.Warningf("Failed to initialize TPM 2.0: %v", err)
116 haveTPM = false
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200117 }
118
Lorenz Brun3ecb04a2023-03-16 20:41:20 +0100119 networkSvc := network.New(nil)
120 networkSvc.DHCPVendorClassID = "dev.monogon.metropolis.node.v1"
Lorenz Brun0e291a12023-06-01 12:22:45 +0200121 networkSvc.ExtraDNSListenerIPs = []net.IP{node.ContainerDNSIP}
Lorenz Brune306d782021-09-01 13:01:06 +0200122 timeSvc := timesvc.New()
Lorenz Brun6c454342023-06-01 12:23:38 +0200123 devmgrSvc := devmgr.New()
Leopold Schabel68c58752019-11-14 21:00:59 +0100124
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200125 // This function initializes a headless Delve if this is a debug build or
126 // does nothing if it's not
Lorenz Brun70f65b22020-07-08 17:02:47 +0200127 initializeDebugger(networkSvc)
128
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200129 // Prepare local storage.
130 root := &localstorage.Root{}
131 if err := declarative.PlaceFS(root, "/"); err != nil {
132 panic(fmt.Errorf("when placing root FS: %w", err))
133 }
134
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200135 // Make context for supervisor. We cancel it when we reach the trapdoor.
136 ctxS, ctxC := context.WithCancel(context.Background())
137
Serge Bazanski58ddc092022-06-30 18:23:33 +0200138 // Make node-wide cluster resolver.
139 res := resolver.New(ctxS, resolver.WithLogger(func(f string, args ...interface{}) {
140 lt.MustLeveledFor("resolver").WithAddedStackDepth(1).Infof(f, args...)
141 }))
142
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100143 // Function which performs core, one-way initialization of the node. This means
144 // waiting for the network, starting the cluster manager, and then starting all
145 // services related to the node's roles.
146 init := func(ctx context.Context) error {
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200147 // Start storage and network - we need this to get anything else done.
148 if err := root.Start(ctx); err != nil {
149 return fmt.Errorf("cannot start root FS: %w", err)
150 }
Lorenz Brun85ad26a2023-03-27 17:00:00 +0200151 nodeParams, err := getNodeParams(ctx, root)
152 if err != nil {
153 return fmt.Errorf("cannot get node parameters: %w", err)
154 }
155 if nodeParams.NetworkConfig != nil {
156 networkSvc.StaticConfig = nodeParams.NetworkConfig
157 if err := root.ESP.Metropolis.NetworkConfiguration.Marshal(nodeParams.NetworkConfig); err != nil {
158 logger.Errorf("Error writing back network_config from NodeParameters: %v", err)
159 }
160 }
161 if networkSvc.StaticConfig == nil {
162 staticConfig, err := root.ESP.Metropolis.NetworkConfiguration.Unmarshal()
163 if err == nil {
164 networkSvc.StaticConfig = staticConfig
165 } else {
166 logger.Errorf("Unable to load static config, proceeding without it: %v", err)
167 }
Lorenz Brunab583b32023-05-02 22:41:45 +0200168 }
Lorenz Brun6c454342023-06-01 12:23:38 +0200169 if err := supervisor.Run(ctx, "devmgr", devmgrSvc.Run); err != nil {
170 return fmt.Errorf("when starting devmgr: %w", err)
171 }
Lorenz Brunab583b32023-05-02 22:41:45 +0200172 if err := supervisor.Run(ctx, "network", networkSvc.Run); err != nil {
173 return fmt.Errorf("when starting network: %w", err)
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100174 }
Lorenz Brune306d782021-09-01 13:01:06 +0200175 if err := supervisor.Run(ctx, "time", timeSvc.Run); err != nil {
176 return fmt.Errorf("when starting time: %w", err)
177 }
Lorenz Brun1b2df232022-06-14 12:42:03 +0200178 if err := supervisor.Run(ctx, "pstore", dumpAndCleanPstore); err != nil {
179 return fmt.Errorf("when starting pstore: %w", err)
180 }
Lorenz Brunf95909d2019-09-11 19:48:26 +0200181
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100182 // Start the role service. The role service connects to the curator and runs
183 // all node-specific role code (eg. Kubernetes services).
184 // supervisor.Logger(ctx).Infof("Starting role service...")
185 rs := roleserve.New(roleserve.Config{
186 StorageRoot: root,
187 Network: networkSvc,
Serge Bazanski58ddc092022-06-30 18:23:33 +0200188 Resolver: res,
Serge Bazanskie012b722023-03-29 17:49:04 +0200189 LogTree: lt,
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100190 })
191 if err := supervisor.Run(ctx, "role", rs.Run); err != nil {
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100192 return fmt.Errorf("failed to start role service: %w", err)
193 }
194
Lorenz Brunac82c0d2022-03-01 13:32:45 +0100195 if err := runDebugService(ctx, rs, lt, root); err != nil {
196 return fmt.Errorf("when starting debug service: %w", err)
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100197 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200198
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100199 // Start cluster manager. This kicks off cluster membership machinery,
200 // which will either start a new cluster, enroll into one or join one.
Serge Bazanski5df62ba2023-03-22 17:56:46 +0100201 m := cluster.NewManager(root, networkSvc, rs, nodeParams, haveTPM)
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100202 return m.Run(ctx)
203 }
204
205 // Start the init function in a one-shot runnable. Smuggle out any errors from
206 // the init function and stuff them into the fatal channel. This is where the
207 // system supervisor takes over as the main process management system.
208 fatal := make(chan error)
209 supervisor.New(ctxS, func(ctx context.Context) error {
210 err := init(ctx)
211 if err != nil {
212 fatal <- err
213 select {}
214 }
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200215 return nil
Serge Bazanskic7359672020-10-30 16:38:57 +0100216 }, supervisor.WithExistingLogtree(lt))
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100217
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100218 // Meanwhile, wait for any fatal error from the init process, and handle it
219 // accordingly.
220 err := <-fatal
221 // Log error with primary logging mechanism still active.
222 logger.Infof("Node startup failed: %v", err)
223 // Start shutting down the supervision tree...
Serge Bazanskieac8f732021-10-05 23:30:37 +0200224 ctxC()
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100225 time.Sleep(time.Second)
226 // After a bit, kill all console log readers.
Serge Bazanski3b098232023-03-16 17:57:02 +0100227 for _, console := range consoles {
Serge Bazanskid02f2162023-03-22 17:57:20 +0100228 if console.reader == nil {
229 continue
230 }
Serge Bazanski3b098232023-03-16 17:57:02 +0100231 console.reader.Close()
232 console.reader.Stream = nil
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100233 }
234 // Wait for final logs to flush to console...
235 time.Sleep(time.Second)
236 // Present final message to the console.
237 crash <- ""
238 crash <- ""
Serge Bazanskie6719b32023-03-22 17:57:50 +0100239 crash <- fmt.Sprintf(" Fatal error: %v", err)
240 crash <- fmt.Sprintf(" This node could not be started. Rebooting...")
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100241 time.Sleep(time.Second)
242 // Return to minit, which will reboot this node.
Serge Bazanskie6719b32023-03-22 17:57:50 +0100243 os.Exit(0)
Serge Bazanski57b43752020-07-13 19:17:48 +0200244}
Serge Bazanski3b098232023-03-16 17:57:02 +0100245
246// consoleFilter is used to filter out some uselessly verbose logs from the
247// console.
248//
249// This should be limited to external services, our internal services should
250// instead just have good logging by default.
251func consoleFilter(p *logtree.LogEntry) bool {
252 if p.Raw != nil {
253 return false
254 }
255 if p.Leveled == nil {
256 return false
257 }
258 s := string(p.DN)
259 if strings.HasPrefix(s, "root.role.controlplane.launcher.consensus.etcd") {
260 return p.Leveled.Severity().AtLeast(logtree.WARNING)
261 }
262 // TODO(q3k): turn off RPC traces instead
263 if strings.HasPrefix(s, "root.role.controlplane.launcher.curator.listener.rpc") {
264 return false
265 }
266 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.networked.kubelet") {
267 return p.Leveled.Severity().AtLeast(logtree.WARNING)
268 }
269 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.networked.apiserver") {
270 return p.Leveled.Severity().AtLeast(logtree.WARNING)
271 }
272 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.controller-manager") {
273 return p.Leveled.Severity().AtLeast(logtree.WARNING)
274 }
275 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.scheduler") {
276 return p.Leveled.Severity().AtLeast(logtree.WARNING)
277 }
Serge Bazanski6b7731e2023-03-22 17:58:04 +0100278 if strings.HasPrefix(s, "supervisor") {
279 return p.Leveled.Severity().AtLeast(logtree.WARNING)
280 }
Serge Bazanski3b098232023-03-16 17:57:02 +0100281 return true
282}
283
284type console struct {
285 path string
286 maxWidth int
287 reader *logtree.LogReader
288}