blob: b36f6ce58f62f3ef7ebf364393b1d5800489c8e7 [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 Bazanskif2f85f52023-03-16 11:51:19 +010024 "time"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020025
Lorenz Brunae0d90d2019-09-05 17:53:56 +020026 "golang.org/x/sys/unix"
Serge Bazanski99f47742021-08-04 20:21:42 +020027
Serge Bazanski31370b02021-01-07 16:31:14 +010028 "source.monogon.dev/metropolis/node/core/cluster"
29 "source.monogon.dev/metropolis/node/core/localstorage"
30 "source.monogon.dev/metropolis/node/core/localstorage/declarative"
31 "source.monogon.dev/metropolis/node/core/network"
Serge Bazanski6dff6d62022-01-28 18:15:14 +010032 "source.monogon.dev/metropolis/node/core/network/hostsfile"
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
51 // /dev/ttyS0.
Serge Bazanski5f8414d2022-06-24 13:02:11 +020052 consoles := []string{"/dev/tty0", "/dev/ttyS0"}
Serge Bazanskif2f85f52023-03-16 11:51:19 +010053 // Logtree readers that will be used to retrieve data from the root logtree and
54 // write them to consoles. We keep a reference to them as we want to be able to
55 // close them after a fatal error, allowing us to clearly output an error to the
56 // user without the console being clobbered by logtree logs.
57 var readers []*logtree.LogReader
58 // Alternative channel that crash handling writes to, and which gets distributed
59 // to the consoles.
60 crash := make(chan string)
61
62 // Open up consoles and set up logging from logtree and crash channel.
Serge Bazanski5f8414d2022-06-24 13:02:11 +020063 for _, p := range consoles {
Serge Bazanskie803fc12022-01-25 14:58:24 +010064 f, err := os.OpenFile(p, os.O_WRONLY, 0)
65 if err != nil {
66 continue
Serge Bazanskic7359672020-10-30 16:38:57 +010067 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010068 reader, err := lt.Read("", logtree.WithChildren(), logtree.WithStream())
69 if err != nil {
70 panic(fmt.Errorf("could not set up root log reader: %v", err))
71 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010072 readers = append(readers, reader)
Serge Bazanskie803fc12022-01-25 14:58:24 +010073 go func(path string, f io.Writer) {
74 fmt.Fprintf(f, "\nMetropolis: this is %s. Verbose node logs follow.\n\n", path)
75 for {
Serge Bazanskif2f85f52023-03-16 11:51:19 +010076 select {
77 case p := <-reader.Stream:
78 fmt.Fprintf(f, "%s\n", p.String())
79 case s := <-crash:
80 fmt.Fprintf(f, "%s\n", s)
81 }
Serge Bazanskie803fc12022-01-25 14:58:24 +010082 }
83 }(p, f)
84 }
Serge Bazanskif2f85f52023-03-16 11:51:19 +010085
Lorenz Brun4025c9b2022-06-16 16:12:53 +000086 // Initialize persistent panic handler early
Serge Bazanski5f8414d2022-06-24 13:02:11 +020087 initPanicHandler(lt, consoles)
Serge Bazanskic7359672020-10-30 16:38:57 +010088
89 // Initial logger. Used until we get to a supervisor.
90 logger := lt.MustLeveledFor("init")
Serge Bazanski581b0bd2020-03-12 13:36:43 +010091
Serge Bazanski216fe7b2021-05-21 18:36:16 +020092 // Linux kernel default is 4096 which is far too low. Raise it to 1M which
93 // is what gVisor suggests.
Lorenz Brun878f5f92020-05-12 16:15:39 +020094 if err := unix.Setrlimit(unix.RLIMIT_NOFILE, &unix.Rlimit{Cur: 1048576, Max: 1048576}); err != nil {
Serge Bazanskic7359672020-10-30 16:38:57 +010095 logger.Fatalf("Failed to raise rlimits: %v", err)
Lorenz Brun878f5f92020-05-12 16:15:39 +020096 }
97
Serge Bazanski662b5b32020-12-21 13:49:00 +010098 logger.Info("Starting Metropolis node init")
Lorenz Brunae0d90d2019-09-05 17:53:56 +020099
Serge Bazanskic7359672020-10-30 16:38:57 +0100100 if err := tpm.Initialize(logger); err != nil {
Lorenz Brun8b786892022-01-13 14:21:16 +0100101 logger.Warningf("Failed to initialize TPM 2.0, attempting fallback to untrusted: %v", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200102 }
103
Serge Bazanskid8af5bf2021-03-16 13:38:29 +0100104 networkSvc := network.New()
Lorenz Brune306d782021-09-01 13:01:06 +0200105 timeSvc := timesvc.New()
Leopold Schabel68c58752019-11-14 21:00:59 +0100106
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200107 // This function initializes a headless Delve if this is a debug build or
108 // does nothing if it's not
Lorenz Brun70f65b22020-07-08 17:02:47 +0200109 initializeDebugger(networkSvc)
110
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200111 // Prepare local storage.
112 root := &localstorage.Root{}
113 if err := declarative.PlaceFS(root, "/"); err != nil {
114 panic(fmt.Errorf("when placing root FS: %w", err))
115 }
116
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200117 // Make context for supervisor. We cancel it when we reach the trapdoor.
118 ctxS, ctxC := context.WithCancel(context.Background())
119
Serge Bazanski58ddc092022-06-30 18:23:33 +0200120 // Make node-wide cluster resolver.
121 res := resolver.New(ctxS, resolver.WithLogger(func(f string, args ...interface{}) {
122 lt.MustLeveledFor("resolver").WithAddedStackDepth(1).Infof(f, args...)
123 }))
124
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100125 // Function which performs core, one-way initialization of the node. This means
126 // waiting for the network, starting the cluster manager, and then starting all
127 // services related to the node's roles.
128 init := func(ctx context.Context) error {
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200129 // Start storage and network - we need this to get anything else done.
130 if err := root.Start(ctx); err != nil {
131 return fmt.Errorf("cannot start root FS: %w", err)
132 }
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100133 if err := supervisor.Run(ctx, "network", networkSvc.Run); err != nil {
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200134 return fmt.Errorf("when starting network: %w", err)
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100135 }
Lorenz Brune306d782021-09-01 13:01:06 +0200136 if err := supervisor.Run(ctx, "time", timeSvc.Run); err != nil {
137 return fmt.Errorf("when starting time: %w", err)
138 }
Lorenz Brun1b2df232022-06-14 12:42:03 +0200139 if err := supervisor.Run(ctx, "pstore", dumpAndCleanPstore); err != nil {
140 return fmt.Errorf("when starting pstore: %w", err)
141 }
Lorenz Brunf95909d2019-09-11 19:48:26 +0200142
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100143 // Start the role service. The role service connects to the curator and runs
144 // all node-specific role code (eg. Kubernetes services).
145 // supervisor.Logger(ctx).Infof("Starting role service...")
146 rs := roleserve.New(roleserve.Config{
147 StorageRoot: root,
148 Network: networkSvc,
Serge Bazanski58ddc092022-06-30 18:23:33 +0200149 Resolver: res,
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100150 })
151 if err := supervisor.Run(ctx, "role", rs.Run); err != nil {
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100152 return fmt.Errorf("failed to start role service: %w", err)
153 }
154
155 // Start the hostsfile service.
156 hostsfileSvc := hostsfile.Service{
157 Config: hostsfile.Config{
158 Roleserver: rs,
159 Network: networkSvc,
160 Ephemeral: &root.Ephemeral,
Mateusz Zalegab30a41d2022-04-29 17:14:50 +0200161 ESP: &root.ESP,
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100162 },
163 }
164 if err := supervisor.Run(ctx, "hostsfile", hostsfileSvc.Run); err != nil {
Serge Bazanski6dff6d62022-01-28 18:15:14 +0100165 return fmt.Errorf("failed to start hostsfile service: %w", err)
166 }
167
Lorenz Brunac82c0d2022-03-01 13:32:45 +0100168 if err := runDebugService(ctx, rs, lt, root); err != nil {
169 return fmt.Errorf("when starting debug service: %w", err)
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100170 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200171
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100172 // Start cluster manager. This kicks off cluster membership machinery,
173 // which will either start a new cluster, enroll into one or join one.
174 m := cluster.NewManager(root, networkSvc, rs)
175 return m.Run(ctx)
176 }
177
178 // Start the init function in a one-shot runnable. Smuggle out any errors from
179 // the init function and stuff them into the fatal channel. This is where the
180 // system supervisor takes over as the main process management system.
181 fatal := make(chan error)
182 supervisor.New(ctxS, func(ctx context.Context) error {
183 err := init(ctx)
184 if err != nil {
185 fatal <- err
186 select {}
187 }
Serge Bazanski1ebd1e12020-07-13 19:17:16 +0200188 return nil
Serge Bazanskic7359672020-10-30 16:38:57 +0100189 }, supervisor.WithExistingLogtree(lt))
Serge Bazanskib1b742f2020-03-24 13:58:19 +0100190
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100191 // Meanwhile, wait for any fatal error from the init process, and handle it
192 // accordingly.
193 err := <-fatal
194 // Log error with primary logging mechanism still active.
195 logger.Infof("Node startup failed: %v", err)
196 // Start shutting down the supervision tree...
Serge Bazanskieac8f732021-10-05 23:30:37 +0200197 ctxC()
Serge Bazanskif2f85f52023-03-16 11:51:19 +0100198 time.Sleep(time.Second)
199 // After a bit, kill all console log readers.
200 for _, r := range readers {
201 r.Close()
202 r.Stream = nil
203 }
204 // Wait for final logs to flush to console...
205 time.Sleep(time.Second)
206 // Present final message to the console.
207 crash <- ""
208 crash <- ""
209 crash <- fmt.Sprintf("Fatal error: %v", err)
210 time.Sleep(time.Second)
211 // Return to minit, which will reboot this node.
212 os.Exit(1)
Serge Bazanski57b43752020-07-13 19:17:48 +0200213}