blob: 0538478530fdda4d4b70a1330d54db7396f8bac5 [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 Bazanski6dff6d62022-01-28 18:15:14 +010033 "source.monogon.dev/metropolis/node/core/network/hostsfile"
Serge Bazanskif9edf522021-06-17 15:57:13 +020034 "source.monogon.dev/metropolis/node/core/roleserve"
Serge Bazanski58ddc092022-06-30 18:23:33 +020035 "source.monogon.dev/metropolis/node/core/rpc/resolver"
Lorenz Brune306d782021-09-01 13:01:06 +020036 timesvc "source.monogon.dev/metropolis/node/core/time"
Serge Bazanski31370b02021-01-07 16:31:14 +010037 "source.monogon.dev/metropolis/pkg/logtree"
38 "source.monogon.dev/metropolis/pkg/supervisor"
39 "source.monogon.dev/metropolis/pkg/tpm"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020040)
41
42func main() {
Serge Bazanskie803fc12022-01-25 14:58:24 +010043 // Set up basic mounts (like /dev, /sys...).
44 if err := setupMounts(); err != nil {
45 panic(fmt.Errorf("could not set up basic mounts: %w", err))
Lorenz Brunae0d90d2019-09-05 17:53:56 +020046 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010047
Serge Bazanskif2f85f52023-03-16 11:51:19 +010048 // Root system logtree.
49 lt := logtree.New()
50
Serge Bazanskie803fc12022-01-25 14:58:24 +010051 // Set up logger for Metropolis. Currently logs everything to /dev/tty0 and
52 // /dev/ttyS0.
Serge Bazanski3b098232023-03-16 17:57:02 +010053 consoles := []console{
54 {
55 path: "/dev/tty0",
56 maxWidth: 80,
57 },
58 {
59 path: "/dev/ttyS0",
60 maxWidth: 120,
61 },
62 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010063 // Alternative channel that crash handling writes to, and which gets distributed
64 // to the consoles.
65 crash := make(chan string)
66
67 // Open up consoles and set up logging from logtree and crash channel.
Serge Bazanski3b098232023-03-16 17:57:02 +010068 for _, console := range consoles {
69 f, err := os.OpenFile(console.path, os.O_WRONLY, 0)
Serge Bazanskie803fc12022-01-25 14:58:24 +010070 if err != nil {
71 continue
Serge Bazanskic7359672020-10-30 16:38:57 +010072 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010073 reader, err := lt.Read("", logtree.WithChildren(), logtree.WithStream())
74 if err != nil {
75 panic(fmt.Errorf("could not set up root log reader: %v", err))
76 }
Serge Bazanski3b098232023-03-16 17:57:02 +010077 console.reader = reader
78 go func(path string, maxWidth int, f io.Writer) {
Serge Bazanskie803fc12022-01-25 14:58:24 +010079 fmt.Fprintf(f, "\nMetropolis: this is %s. Verbose node logs follow.\n\n", path)
80 for {
Serge Bazanskif2f85f52023-03-16 11:51:19 +010081 select {
82 case p := <-reader.Stream:
Serge Bazanski3b098232023-03-16 17:57:02 +010083 if consoleFilter(p) {
84 fmt.Fprintf(f, "%s\n", p.ConciseString(logtree.MetropolisShortenDict, maxWidth))
85 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010086 case s := <-crash:
87 fmt.Fprintf(f, "%s\n", s)
88 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010089 }
Serge Bazanski3b098232023-03-16 17:57:02 +010090 }(console.path, console.maxWidth, f)
Serge Bazanskie803fc12022-01-25 14:58:24 +010091 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010092
Lorenz Brun4025c9b2022-06-16 16:12:53 +000093 // Initialize persistent panic handler early
Serge Bazanski5f8414d2022-06-24 13:02:11 +020094 initPanicHandler(lt, consoles)
Serge Bazanskic7359672020-10-30 16:38:57 +010095
96 // Initial logger. Used until we get to a supervisor.
97 logger := lt.MustLeveledFor("init")
Serge Bazanski581b0bd2020-03-12 13:36:43 +010098
Serge Bazanski216fe7b2021-05-21 18:36:16 +020099 // Linux kernel default is 4096 which is far too low. Raise it to 1M which
100 // is what gVisor suggests.
Lorenz Brun878f5f92020-05-12 16:15:39 +0200101 if err := unix.Setrlimit(unix.RLIMIT_NOFILE, &unix.Rlimit{Cur: 1048576, Max: 1048576}); err != nil {
Serge Bazanskic7359672020-10-30 16:38:57 +0100102 logger.Fatalf("Failed to raise rlimits: %v", err)
Lorenz Brun878f5f92020-05-12 16:15:39 +0200103 }
104
Serge Bazanski662b5b32020-12-21 13:49:00 +0100105 logger.Info("Starting Metropolis node init")
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200106
Serge Bazanskic7359672020-10-30 16:38:57 +0100107 if err := tpm.Initialize(logger); err != nil {
Lorenz Brun8b786892022-01-13 14:21:16 +0100108 logger.Warningf("Failed to initialize TPM 2.0, attempting fallback to untrusted: %v", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200109 }
110
Serge Bazanskid8af5bf2021-03-16 13:38:29 +0100111 networkSvc := network.New()
Lorenz Brune306d782021-09-01 13:01:06 +0200112 timeSvc := timesvc.New()
Leopold Schabel68c58752019-11-14 21:00:59 +0100113
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200114 // This function initializes a headless Delve if this is a debug build or
115 // does nothing if it's not
Lorenz Brun70f65b22020-07-08 17:02:47 +0200116 initializeDebugger(networkSvc)
117
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200118 // Prepare local storage.
119 root := &localstorage.Root{}
120 if err := declarative.PlaceFS(root, "/"); err != nil {
121 panic(fmt.Errorf("when placing root FS: %w", err))
122 }
123
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200124 // Make context for supervisor. We cancel it when we reach the trapdoor.
125 ctxS, ctxC := context.WithCancel(context.Background())
126
Serge Bazanski58ddc092022-06-30 18:23:33 +0200127 // Make node-wide cluster resolver.
128 res := resolver.New(ctxS, resolver.WithLogger(func(f string, args ...interface{}) {
129 lt.MustLeveledFor("resolver").WithAddedStackDepth(1).Infof(f, args...)
130 }))
131
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100132 // Function which performs core, one-way initialization of the node. This means
133 // waiting for the network, starting the cluster manager, and then starting all
134 // services related to the node's roles.
135 init := func(ctx context.Context) error {
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200136 // Start storage and network - we need this to get anything else done.
137 if err := root.Start(ctx); err != nil {
138 return fmt.Errorf("cannot start root FS: %w", err)
139 }
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100140 if err := supervisor.Run(ctx, "network", networkSvc.Run); err != nil {
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200141 return fmt.Errorf("when starting network: %w", err)
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100142 }
Lorenz Brune306d782021-09-01 13:01:06 +0200143 if err := supervisor.Run(ctx, "time", timeSvc.Run); err != nil {
144 return fmt.Errorf("when starting time: %w", err)
145 }
Lorenz Brun1b2df232022-06-14 12:42:03 +0200146 if err := supervisor.Run(ctx, "pstore", dumpAndCleanPstore); err != nil {
147 return fmt.Errorf("when starting pstore: %w", err)
148 }
Lorenz Brunf95909d2019-09-11 19:48:26 +0200149
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100150 // Start the role service. The role service connects to the curator and runs
151 // all node-specific role code (eg. Kubernetes services).
152 // supervisor.Logger(ctx).Infof("Starting role service...")
153 rs := roleserve.New(roleserve.Config{
154 StorageRoot: root,
155 Network: networkSvc,
Serge Bazanski58ddc092022-06-30 18:23:33 +0200156 Resolver: res,
Serge Bazanskie012b722023-03-29 17:49:04 +0200157 LogTree: lt,
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100158 })
159 if err := supervisor.Run(ctx, "role", rs.Run); err != nil {
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100160 return fmt.Errorf("failed to start role service: %w", err)
161 }
162
163 // Start the hostsfile service.
164 hostsfileSvc := hostsfile.Service{
165 Config: hostsfile.Config{
166 Roleserver: rs,
167 Network: networkSvc,
168 Ephemeral: &root.Ephemeral,
Mateusz Zalegab30a41d2022-04-29 17:14:50 +0200169 ESP: &root.ESP,
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100170 },
171 }
172 if err := supervisor.Run(ctx, "hostsfile", hostsfileSvc.Run); err != nil {
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100173 return fmt.Errorf("failed to start hostsfile service: %w", err)
174 }
175
Lorenz Brunac82c0d2022-03-01 13:32:45 +0100176 if err := runDebugService(ctx, rs, lt, root); err != nil {
177 return fmt.Errorf("when starting debug service: %w", err)
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100178 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200179
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100180 // Start cluster manager. This kicks off cluster membership machinery,
181 // which will either start a new cluster, enroll into one or join one.
182 m := cluster.NewManager(root, networkSvc, rs)
183 return m.Run(ctx)
184 }
185
186 // Start the init function in a one-shot runnable. Smuggle out any errors from
187 // the init function and stuff them into the fatal channel. This is where the
188 // system supervisor takes over as the main process management system.
189 fatal := make(chan error)
190 supervisor.New(ctxS, func(ctx context.Context) error {
191 err := init(ctx)
192 if err != nil {
193 fatal <- err
194 select {}
195 }
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200196 return nil
Serge Bazanskic7359672020-10-30 16:38:57 +0100197 }, supervisor.WithExistingLogtree(lt))
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100198
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100199 // Meanwhile, wait for any fatal error from the init process, and handle it
200 // accordingly.
201 err := <-fatal
202 // Log error with primary logging mechanism still active.
203 logger.Infof("Node startup failed: %v", err)
204 // Start shutting down the supervision tree...
Serge Bazanskieac8f732021-10-05 23:30:37 +0200205 ctxC()
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100206 time.Sleep(time.Second)
207 // After a bit, kill all console log readers.
Serge Bazanski3b098232023-03-16 17:57:02 +0100208 for _, console := range consoles {
Serge Bazanskid02f2162023-03-22 17:57:20 +0100209 if console.reader == nil {
210 continue
211 }
Serge Bazanski3b098232023-03-16 17:57:02 +0100212 console.reader.Close()
213 console.reader.Stream = nil
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100214 }
215 // Wait for final logs to flush to console...
216 time.Sleep(time.Second)
217 // Present final message to the console.
218 crash <- ""
219 crash <- ""
Serge Bazanskie6719b32023-03-22 17:57:50 +0100220 crash <- fmt.Sprintf(" Fatal error: %v", err)
221 crash <- fmt.Sprintf(" This node could not be started. Rebooting...")
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100222 time.Sleep(time.Second)
223 // Return to minit, which will reboot this node.
Serge Bazanskie6719b32023-03-22 17:57:50 +0100224 os.Exit(0)
Serge Bazanski57b43752020-07-13 19:17:48 +0200225}
Serge Bazanski3b098232023-03-16 17:57:02 +0100226
227// consoleFilter is used to filter out some uselessly verbose logs from the
228// console.
229//
230// This should be limited to external services, our internal services should
231// instead just have good logging by default.
232func consoleFilter(p *logtree.LogEntry) bool {
233 if p.Raw != nil {
234 return false
235 }
236 if p.Leveled == nil {
237 return false
238 }
239 s := string(p.DN)
240 if strings.HasPrefix(s, "root.role.controlplane.launcher.consensus.etcd") {
241 return p.Leveled.Severity().AtLeast(logtree.WARNING)
242 }
243 // TODO(q3k): turn off RPC traces instead
244 if strings.HasPrefix(s, "root.role.controlplane.launcher.curator.listener.rpc") {
245 return false
246 }
247 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.networked.kubelet") {
248 return p.Leveled.Severity().AtLeast(logtree.WARNING)
249 }
250 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.networked.apiserver") {
251 return p.Leveled.Severity().AtLeast(logtree.WARNING)
252 }
253 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.controller-manager") {
254 return p.Leveled.Severity().AtLeast(logtree.WARNING)
255 }
256 if strings.HasPrefix(s, "root.role.kubernetes.run.kubernetes.scheduler") {
257 return p.Leveled.Severity().AtLeast(logtree.WARNING)
258 }
Serge Bazanski6b7731e2023-03-22 17:58:04 +0100259 if strings.HasPrefix(s, "supervisor") {
260 return p.Leveled.Severity().AtLeast(logtree.WARNING)
261 }
Serge Bazanski3b098232023-03-16 17:57:02 +0100262 return true
263}
264
265type console struct {
266 path string
267 maxWidth int
268 reader *logtree.LogReader
269}