/
main.go
290 lines (235 loc) · 6.61 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"os/signal"
goruntime "runtime"
"syscall"
"time"
"github.com/talos-systems/go-cmd/pkg/cmd/proc"
"github.com/talos-systems/go-cmd/pkg/cmd/proc/reaper"
"github.com/talos-systems/go-procfs/procfs"
"golang.org/x/net/http/httpproxy"
"golang.org/x/sys/unix"
"github.com/talos-systems/talos/internal/app/apid"
"github.com/talos-systems/talos/internal/app/machined/pkg/runtime"
v1alpha1runtime "github.com/talos-systems/talos/internal/app/machined/pkg/runtime/v1alpha1"
"github.com/talos-systems/talos/internal/app/machined/pkg/runtime/v1alpha1/bootloader"
"github.com/talos-systems/talos/internal/app/machined/pkg/system"
"github.com/talos-systems/talos/internal/app/machined/pkg/system/services"
"github.com/talos-systems/talos/internal/app/timed"
"github.com/talos-systems/talos/internal/app/trustd"
"github.com/talos-systems/talos/internal/pkg/mount"
"github.com/talos-systems/talos/pkg/machinery/api/common"
"github.com/talos-systems/talos/pkg/machinery/api/machine"
"github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/startup"
)
func init() {
// Explicitly disable memory profiling to save around 1.4MiB of memory.
goruntime.MemProfileRate = 0
// Explicitly set the default http client transport to work around proxy.Do
// once. This is the http.DefaultTransport with the Proxy func overridden so
// that the environment variables with be reread/initialized each time the
// http call is made.
http.DefaultClient.Transport = &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return httpproxy.FromEnvironment().ProxyFunc()(req.URL)
},
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
}
func recovery() {
if r := recover(); r != nil {
var (
err error
ok bool
)
err, ok = r.(error)
if ok {
handle(err)
}
}
}
func revertBootloader() {
if meta, err := bootloader.NewMeta(); err == nil {
if err = meta.Revert(); err != nil {
log.Printf("failed to revert upgrade: %v", err)
}
//nolint:errcheck
meta.Close()
} else {
log.Printf("failed to open meta: %v", err)
}
}
// syncNonVolatileStorageBuffers invokes unix.Sync and waits up to 30 seconds
// for it to finish.
//
// See http://man7.org/linux/man-pages/man2/reboot.2.html.
func syncNonVolatileStorageBuffers() {
syncdone := make(chan struct{})
go func() {
defer close(syncdone)
unix.Sync()
}()
log.Printf("waiting for sync...")
for i := 29; i >= 0; i-- {
select {
case <-syncdone:
log.Printf("sync done")
return
case <-time.After(time.Second):
}
if i != 0 {
log.Printf("waiting %d more seconds for sync to finish", i)
}
}
log.Printf("sync hasn't completed in time, aborting...")
}
//nolint:gocyclo
func handle(err error) {
rebootCmd := unix.LINUX_REBOOT_CMD_RESTART
var rebootErr runtime.RebootError
if errors.As(err, &rebootErr) {
// not a failure, but wrapped reboot command
rebootCmd = rebootErr.Cmd
err = nil
}
if err != nil {
log.Print(err)
revertBootloader()
if p := procfs.ProcCmdline().Get(constants.KernelParamPanic).First(); p != nil {
if *p == "0" {
log.Printf("panic=0 kernel flag found, sleeping forever")
rebootCmd = 0
}
}
}
if rebootCmd == unix.LINUX_REBOOT_CMD_RESTART {
for i := 10; i >= 0; i-- {
log.Printf("rebooting in %d seconds\n", i)
time.Sleep(1 * time.Second)
}
}
if err = proc.KillAll(); err != nil {
log.Printf("error killing all procs: %s", err)
}
if err = mount.UnmountAll(); err != nil {
log.Printf("error unmounting: %s", err)
}
syncNonVolatileStorageBuffers()
if rebootCmd == 0 {
exitSignal := make(chan os.Signal, 1)
signal.Notify(exitSignal, syscall.SIGINT, syscall.SIGTERM)
<-exitSignal
} else if unix.Reboot(rebootCmd) == nil {
// Wait forever.
select {}
}
}
//nolint:gocyclo
func run() error {
errCh := make(chan error)
// Ensure RNG is seeded.
if err := startup.RandSeed(); err != nil {
return err
}
// Set the PATH env var.
if err := os.Setenv("PATH", constants.PATH); err != nil {
return errors.New("error setting PATH")
}
// Initialize the controller without a config.
c, err := v1alpha1runtime.NewController(nil)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Schedule service shutdown on any return.
defer system.Services(c.Runtime()).Shutdown(ctx)
// Start signal and ACPI listeners.
go func() {
if e := c.ListenForEvents(ctx); e != nil {
log.Printf("WARNING: signals and ACPI events will be ignored: %s", e)
}
}()
// Start v2 controller runtime.
go func() {
if e := c.V1Alpha2().Run(ctx); e != nil {
errCh <- fmt.Errorf("fatal controller runtime error: %s", e)
}
log.Printf("controller runtime finished")
}()
// Initialize the machine.
if err = c.Run(ctx, runtime.SequenceInitialize, nil); err != nil {
return err
}
// Perform an installation if required.
if err = c.Run(ctx, runtime.SequenceInstall, nil); err != nil {
return err
}
// Start the machine API.
system.Services(c.Runtime()).LoadAndStart(&services.Machined{Controller: c})
// Boot the machine.
if err = c.Run(ctx, runtime.SequenceBoot, nil); err != nil && !errors.Is(err, context.Canceled) {
return err
}
// Watch and handle runtime events.
_ = c.Runtime().Events().Watch(func(events <-chan runtime.Event) { //nolint:errcheck
for {
for event := range events {
switch msg := event.Payload.(type) {
case *machine.SequenceEvent:
if msg.Error != nil {
if msg.Error.GetCode() == common.Code_LOCKED {
// ignore sequence lock errors, they're not fatal
continue
}
errCh <- fmt.Errorf("fatal sequencer error in %q sequence: %v", msg.GetSequence(), msg.GetError().String())
}
case *machine.RestartEvent:
errCh <- runtime.RebootError{Cmd: int(msg.Cmd)}
}
}
}
})
return <-errCh
}
func main() {
switch os.Args[0] {
case "/apid":
apid.Main()
return
case "/timed":
timed.Main()
return
case "/trustd":
trustd.Main()
return
default:
}
// Setup panic handler.
defer recovery()
// Initialize the process reaper.
reaper.Run()
defer reaper.Shutdown()
handle(run())
}