blob: 715a7ac62d5f3f9722443c1ea35548c67d257680 [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 Brunae0d90d2019-09-05 17:53:56 +020023 "os"
Serge Bazanski3b098232023-03-16 17:57:02 +010024 "strings"
Serge Bazanskif2f85f52023-03-16 11:51:19 +010025 "time"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020026
Lorenz Brunae0d90d2019-09-05 17:53:56 +020027 "golang.org/x/sys/unix"
Serge Bazanski99f47742021-08-04 20:21:42 +020028
Serge Bazanski31370b02021-01-07 16:31:14 +010029 "source.monogon.dev/metropolis/node/core/cluster"
30 "source.monogon.dev/metropolis/node/core/localstorage"
31 "source.monogon.dev/metropolis/node/core/localstorage/declarative"
32 "source.monogon.dev/metropolis/node/core/network"
Serge Bazanskif9edf522021-06-17 15:57:13 +020033 "source.monogon.dev/metropolis/node/core/roleserve"
Serge Bazanski58ddc092022-06-30 18:23:33 +020034 "source.monogon.dev/metropolis/node/core/rpc/resolver"
Lorenz Brune306d782021-09-01 13:01:06 +020035 timesvc "source.monogon.dev/metropolis/node/core/time"
Serge Bazanski31370b02021-01-07 16:31:14 +010036 "source.monogon.dev/metropolis/pkg/logtree"
37 "source.monogon.dev/metropolis/pkg/supervisor"
38 "source.monogon.dev/metropolis/pkg/tpm"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020039)
40
41func main() {
Serge Bazanskie803fc12022-01-25 14:58:24 +010042 // Set up basic mounts (like /dev, /sys...).
43 if err := setupMounts(); err != nil {
44 panic(fmt.Errorf("could not set up basic mounts: %w", err))
Lorenz Brunae0d90d2019-09-05 17:53:56 +020045 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010046
Serge Bazanskif2f85f52023-03-16 11:51:19 +010047 // Root system logtree.
48 lt := logtree.New()
49
Serge Bazanskie803fc12022-01-25 14:58:24 +010050 // Set up logger for Metropolis. Currently logs everything to /dev/tty0 and
Lorenz Brunf0b22ff2023-05-02 16:04:20 +020051 // /dev/ttyS{0,1}.
Serge Bazanski3b098232023-03-16 17:57:02 +010052 consoles := []console{
53 {
54 path: "/dev/tty0",
55 maxWidth: 80,
56 },
57 {
58 path: "/dev/ttyS0",
59 maxWidth: 120,
60 },
Lorenz Brunf0b22ff2023-05-02 16:04:20 +020061 {
62 path: "/dev/ttyS1",
63 maxWidth: 120,
64 },
Serge Bazanski3b098232023-03-16 17:57:02 +010065 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010066 // Alternative channel that crash handling writes to, and which gets distributed
67 // to the consoles.
68 crash := make(chan string)
69
70 // Open up consoles and set up logging from logtree and crash channel.
Serge Bazanski3b098232023-03-16 17:57:02 +010071 for _, console := range consoles {
72 f, err := os.OpenFile(console.path, os.O_WRONLY, 0)
Serge Bazanskie803fc12022-01-25 14:58:24 +010073 if err != nil {
74 continue
Serge Bazanskic7359672020-10-30 16:38:57 +010075 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010076 reader, err := lt.Read("", logtree.WithChildren(), logtree.WithStream())
77 if err != nil {
78 panic(fmt.Errorf("could not set up root log reader: %v", err))
79 }
Serge Bazanski3b098232023-03-16 17:57:02 +010080 console.reader = reader
81 go func(path string, maxWidth int, f io.Writer) {
Serge Bazanskie803fc12022-01-25 14:58:24 +010082 fmt.Fprintf(f, "\nMetropolis: this is %s. Verbose node logs follow.\n\n", path)
83 for {
Serge Bazanskif2f85f52023-03-16 11:51:19 +010084 select {
85 case p := <-reader.Stream:
Serge Bazanski3b098232023-03-16 17:57:02 +010086 if consoleFilter(p) {
87 fmt.Fprintf(f, "%s\n", p.ConciseString(logtree.MetropolisShortenDict, maxWidth))
88 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010089 case s := <-crash:
90 fmt.Fprintf(f, "%s\n", s)
91 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010092 }
Serge Bazanski3b098232023-03-16 17:57:02 +010093 }(console.path, console.maxWidth, f)
Serge Bazanskie803fc12022-01-25 14:58:24 +010094 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010095
Lorenz Brun4025c9b2022-06-16 16:12:53 +000096 // Initialize persistent panic handler early
Serge Bazanski5f8414d2022-06-24 13:02:11 +020097 initPanicHandler(lt, consoles)
Serge Bazanskic7359672020-10-30 16:38:57 +010098
99 // Initial logger. Used until we get to a supervisor.
100 logger := lt.MustLeveledFor("init")
Serge Bazanski581b0bd2020-03-12 13:36:43 +0100101
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200102 // Linux kernel default is 4096 which is far too low. Raise it to 1M which
103 // is what gVisor suggests.
Lorenz Brun878f5f92020-05-12 16:15:39 +0200104 if err := unix.Setrlimit(unix.RLIMIT_NOFILE, &unix.Rlimit{Cur: 1048576, Max: 1048576}); err != nil {
Serge Bazanskic7359672020-10-30 16:38:57 +0100105 logger.Fatalf("Failed to raise rlimits: %v", err)
Lorenz Brun878f5f92020-05-12 16:15:39 +0200106 }
107
Serge Bazanski662b5b32020-12-21 13:49:00 +0100108 logger.Info("Starting Metropolis node init")
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200109
Serge Bazanski5df62ba2023-03-22 17:56:46 +0100110 haveTPM := true
Serge Bazanskic7359672020-10-30 16:38:57 +0100111 if err := tpm.Initialize(logger); err != nil {
Serge Bazanski5df62ba2023-03-22 17:56:46 +0100112 logger.Warningf("Failed to initialize TPM 2.0: %v", err)
113 haveTPM = false
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200114 }
115
Lorenz Brun3ecb04a2023-03-16 20:41:20 +0100116 networkSvc := network.New(nil)
117 networkSvc.DHCPVendorClassID = "dev.monogon.metropolis.node.v1"
Lorenz Brune306d782021-09-01 13:01:06 +0200118 timeSvc := timesvc.New()
Leopold Schabel68c58752019-11-14 21:00:59 +0100119
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200120 // This function initializes a headless Delve if this is a debug build or
121 // does nothing if it's not
Lorenz Brun70f65b22020-07-08 17:02:47 +0200122 initializeDebugger(networkSvc)
123
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200124 // Prepare local storage.
125 root := &localstorage.Root{}
126 if err := declarative.PlaceFS(root, "/"); err != nil {
127 panic(fmt.Errorf("when placing root FS: %w", err))
128 }
129
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200130 // Make context for supervisor. We cancel it when we reach the trapdoor.
131 ctxS, ctxC := context.WithCancel(context.Background())
132
Serge Bazanski58ddc092022-06-30 18:23:33 +0200133 // Make node-wide cluster resolver.
134 res := resolver.New(ctxS, resolver.WithLogger(func(f string, args ...interface{}) {
135 lt.MustLeveledFor("resolver").WithAddedStackDepth(1).Infof(f, args...)
136 }))
137
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100138 // Function which performs core, one-way initialization of the node. This means
139 // waiting for the network, starting the cluster manager, and then starting all
140 // services related to the node's roles.
141 init := func(ctx context.Context) error {
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200142 // Start storage and network - we need this to get anything else done.
143 if err := root.Start(ctx); err != nil {
144 return fmt.Errorf("cannot start root FS: %w", err)
145 }
Lorenz Brun85ad26a2023-03-27 17:00:00 +0200146 nodeParams, err := getNodeParams(ctx, root)
147 if err != nil {
148 return fmt.Errorf("cannot get node parameters: %w", err)
149 }
150 if nodeParams.NetworkConfig != nil {
151 networkSvc.StaticConfig = nodeParams.NetworkConfig
152 if err := root.ESP.Metropolis.NetworkConfiguration.Marshal(nodeParams.NetworkConfig); err != nil {
153 logger.Errorf("Error writing back network_config from NodeParameters: %v", err)
154 }
155 }
156 if networkSvc.StaticConfig == nil {
157 staticConfig, err := root.ESP.Metropolis.NetworkConfiguration.Unmarshal()
158 if err == nil {
159 networkSvc.StaticConfig = staticConfig
160 } else {
161 logger.Errorf("Unable to load static config, proceeding without it: %v", err)
162 }
163 if err := supervisor.Run(ctx, "network", networkSvc.Run); err != nil {
164 return fmt.Errorf("when starting network: %w", err)
165 }
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100166 }
Lorenz Brune306d782021-09-01 13:01:06 +0200167 if err := supervisor.Run(ctx, "time", timeSvc.Run); err != nil {
168 return fmt.Errorf("when starting time: %w", err)
169 }
Lorenz Brun1b2df232022-06-14 12:42:03 +0200170 if err := supervisor.Run(ctx, "pstore", dumpAndCleanPstore); err != nil {
171 return fmt.Errorf("when starting pstore: %w", err)
172 }
Lorenz Brunf95909d2019-09-11 19:48:26 +0200173
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100174 // Start the role service. The role service connects to the curator and runs
175 // all node-specific role code (eg. Kubernetes services).
176 // supervisor.Logger(ctx).Infof("Starting role service...")
177 rs := roleserve.New(roleserve.Config{
178 StorageRoot: root,
179 Network: networkSvc,
Serge Bazanski58ddc092022-06-30 18:23:33 +0200180 Resolver: res,
Serge Bazanskie012b722023-03-29 17:49:04 +0200181 LogTree: lt,
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100182 })
183 if err := supervisor.Run(ctx, "role", rs.Run); err != nil {
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100184 return fmt.Errorf("failed to start role service: %w", err)
185 }
186
Lorenz Brunac82c0d2022-03-01 13:32:45 +0100187 if err := runDebugService(ctx, rs, lt, root); err != nil {
188 return fmt.Errorf("when starting debug service: %w", err)
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100189 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200190
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100191 // Start cluster manager. This kicks off cluster membership machinery,
192 // which will either start a new cluster, enroll into one or join one.
Serge Bazanski5df62ba2023-03-22 17:56:46 +0100193 m := cluster.NewManager(root, networkSvc, rs, nodeParams, haveTPM)
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100194 return m.Run(ctx)
195 }
196
197 // Start the init function in a one-shot runnable. Smuggle out any errors from
198 // the init function and stuff them into the fatal channel. This is where the
199 // system supervisor takes over as the main process management system.
200 fatal := make(chan error)
201 supervisor.New(ctxS, func(ctx context.Context) error {
202 err := init(ctx)
203 if err != nil {
204 fatal <- err
205 select {}
206 }
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200207 return nil
Serge Bazanskic7359672020-10-30 16:38:57 +0100208 }, supervisor.WithExistingLogtree(lt))
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100209
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100210 // Meanwhile, wait for any fatal error from the init process, and handle it
211 // accordingly.
212 err := <-fatal
213 // Log error with primary logging mechanism still active.
214 logger.Infof("Node startup failed: %v", err)
215 // Start shutting down the supervision tree...
Serge Bazanskieac8f732021-10-05 23:30:37 +0200216 ctxC()
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100217 time.Sleep(time.Second)
218 // After a bit, kill all console log readers.
Serge Bazanski3b098232023-03-16 17:57:02 +0100219 for _, console := range consoles {
Serge Bazanskid02f2162023-03-22 17:57:20 +0100220 if console.reader == nil {
221 continue
222 }
Serge Bazanski3b098232023-03-16 17:57:02 +0100223 console.reader.Close()
224 console.reader.Stream = nil
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100225 }
226 // Wait for final logs to flush to console...
227 time.Sleep(time.Second)
228 // Present final message to the console.
229 crash <- ""
230 crash <- ""
Serge Bazanskie6719b32023-03-22 17:57:50 +0100231 crash <- fmt.Sprintf(" Fatal error: %v", err)
232 crash <- fmt.Sprintf(" This node could not be started. Rebooting...")
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100233 time.Sleep(time.Second)
234 // Return to minit, which will reboot this node.
Serge Bazanskie6719b32023-03-22 17:57:50 +0100235 os.Exit(0)
Serge Bazanski57b43752020-07-13 19:17:48 +0200236}
Serge Bazanski3b098232023-03-16 17:57:02 +0100237
238// consoleFilter is used to filter out some uselessly verbose logs from the
239// console.
240//
241// This should be limited to external services, our internal services should
242// instead just have good logging by default.
243func consoleFilter(p *logtree.LogEntry) bool {
244 if p.Raw != nil {
245 return false
246 }
247 if p.Leveled == nil {
248 return false
249 }
250 s := string(p.DN)
251 if strings.HasPrefix(s, "root.role.controlplane.launcher.consensus.etcd") {
252 return p.Leveled.Severity().AtLeast(logtree.WARNING)
253 }
254 // TODO(q3k): turn off RPC traces instead
255 if strings.HasPrefix(s, "root.role.controlplane.launcher.curator.listener.rpc") {
256 return false
257 }
258 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.networked.kubelet") {
259 return p.Leveled.Severity().AtLeast(logtree.WARNING)
260 }
261 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.networked.apiserver") {
262 return p.Leveled.Severity().AtLeast(logtree.WARNING)
263 }
264 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.controller-manager") {
265 return p.Leveled.Severity().AtLeast(logtree.WARNING)
266 }
267 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.scheduler") {
268 return p.Leveled.Severity().AtLeast(logtree.WARNING)
269 }
Serge Bazanski6b7731e2023-03-22 17:58:04 +0100270 if strings.HasPrefix(s, "supervisor") {
271 return p.Leveled.Severity().AtLeast(logtree.WARNING)
272 }
Serge Bazanski3b098232023-03-16 17:57:02 +0100273 return true
274}
275
276type console struct {
277 path string
278 maxWidth int
279 reader *logtree.LogReader
280}