-
Notifications
You must be signed in to change notification settings - Fork 1k
/
main.go
461 lines (402 loc) · 13 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package main
import (
"context"
"errors"
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"path/filepath"
"runtime"
"runtime/pprof"
"sort"
"strings"
"time"
"github.com/containers/kubensmnt"
"github.com/containers/storage/pkg/reexec"
"github.com/cri-o/cri-o/internal/criocli"
"github.com/cri-o/cri-o/internal/log"
"github.com/cri-o/cri-o/internal/opentelemetry"
"github.com/cri-o/cri-o/internal/signals"
"github.com/cri-o/cri-o/internal/version"
libconfig "github.com/cri-o/cri-o/pkg/config"
"github.com/cri-o/cri-o/server"
otel_collector "github.com/cri-o/cri-o/server/otel-collector"
"github.com/cri-o/cri-o/utils"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/sirupsen/logrus"
"github.com/soheilhy/cmux"
"github.com/uptrace/opentelemetry-go-extra/otellogrus"
"github.com/urfave/cli/v2"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"golang.org/x/sys/unix"
"google.golang.org/grpc"
v1 "k8s.io/cri-api/pkg/apis/runtime/v1"
)
func writeCrioGoroutineStacks() {
path := filepath.Join("/tmp", fmt.Sprintf(
"crio-goroutine-stacks-%s.log",
strings.ReplaceAll(time.Now().Format(time.RFC3339), ":", ""),
))
if err := utils.WriteGoroutineStacksToFile(path); err != nil {
logrus.Warnf("Failed to write goroutine stacks: %s", err)
}
}
func catchShutdown(ctx context.Context, cancel context.CancelFunc, gserver *grpc.Server, tp *sdktrace.TracerProvider, sserver *server.Server, hserver *http.Server, signalled *bool) {
sig := make(chan os.Signal, 2048)
signal.Notify(sig, signals.Interrupt, signals.Term, unix.SIGUSR1, unix.SIGUSR2, unix.SIGPIPE, signals.Hup)
go func() {
for s := range sig {
log.WithFields(ctx, logrus.Fields{
"signal": s,
}).Debug("received signal")
switch s {
case unix.SIGUSR1:
writeCrioGoroutineStacks()
continue
case unix.SIGUSR2:
runtime.GC()
continue
case unix.SIGPIPE:
continue
case signals.Interrupt:
log.Debugf(ctx, "Caught SIGINT")
case signals.Term:
log.Debugf(ctx, "Caught SIGTERM")
default:
continue
}
*signalled = true
if tp != nil {
if err := tp.Shutdown(ctx); err != nil {
log.Warnf(ctx, "Error shutting down opentelemetry tracer provider: %v", err)
}
}
gserver.GracefulStop()
hserver.Shutdown(ctx) // nolint: errcheck
if err := sserver.StopStreamServer(); err != nil {
log.Warnf(ctx, "Error shutting down streaming server: %v", err)
}
sserver.StopMonitors()
cancel()
if err := sserver.Shutdown(ctx); err != nil {
log.Warnf(ctx, "Error shutting down main service %v", err)
}
return
}
}()
}
const usage = `OCI-based implementation of Kubernetes Container Runtime Interface Daemon
crio is meant to provide an integration path between OCI conformant runtimes
and the kubelet. Specifically, it implements the Kubelet Container Runtime
Interface (CRI) using OCI conformant runtimes. The scope of crio is tied to the
scope of the CRI.
1. Support multiple image formats including the existing Docker and OCI image formats.
2. Support for multiple means to download images including trust & image verification.
3. Container image management (managing image layers, overlay filesystems, etc).
4. Container process lifecycle management.
5. Monitoring and logging required to satisfy the CRI.
6. Resource isolation as required by the CRI.`
const kubensmntHelp = `Path to a bind-mounted mount namespace that CRI-O
should join before launching any containers. If the path does not exist,
or does not point to a mount namespace bindmount, CRI-O will run in its
parent's mount namespace and log a warning that the requested namespace
was not joined.`
func main() {
log.InitKlogShim()
if reexec.Init() {
return
}
app := cli.NewApp()
app.Name = "crio"
app.Usage = "OCI-based implementation of Kubernetes Container Runtime Interface"
app.Authors = []*cli.Author{{Name: "The CRI-O Maintainers"}}
app.UsageText = usage
app.Description = app.Usage
info, err := version.Get(false)
if err != nil {
logrus.Fatal(err)
}
app.Version = version.Version + "\n" + info.String()
app.Flags, app.Metadata, err = criocli.GetFlagsAndMetadata()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
sort.Sort(cli.FlagsByName(app.Flags))
sort.Sort(cli.FlagsByName(criocli.ConfigCommand.Flags))
app.Metadata["Env"] = map[string]string{
kubensmnt.EnvName: kubensmntHelp,
}
app.Commands = criocli.DefaultCommands
app.Commands = append(app.Commands, []*cli.Command{
criocli.ConfigCommand,
criocli.PublishCommand,
criocli.VersionCommand,
criocli.WipeCommand,
criocli.StatusCommand,
}...)
app.Before = func(c *cli.Context) (err error) {
config, err := criocli.GetAndMergeConfigFromContext(c)
if err != nil {
return err
}
logrus.SetFormatter(&logrus.TextFormatter{
TimestampFormat: "2006-01-02 15:04:05.000000000Z07:00",
FullTimestamp: true,
})
info.LogVersion()
level, err := logrus.ParseLevel(config.LogLevel)
if err != nil {
return err
}
logrus.SetLevel(level)
logrus.AddHook(log.NewFilenameHook())
logrus.AddHook(otellogrus.NewHook(otellogrus.WithLevels(
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
logrus.DebugLevel,
logrus.TraceLevel,
)))
filterHook, err := log.NewFilterHook(config.LogFilter)
if err != nil {
return err
}
logrus.AddHook(filterHook)
if path := c.String("log"); path != "" {
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_SYNC, 0o666)
if err != nil {
return err
}
logrus.SetOutput(f)
}
switch c.String("log-format") {
case "text":
// retain logrus's default.
case "json":
logrus.SetFormatter(new(logrus.JSONFormatter))
default:
return fmt.Errorf("unknown log-format %q", c.String("log-format"))
}
return nil
}
app.Action = func(c *cli.Context) error {
ctx, cancel := context.WithCancel(context.Background())
cpuProfilePath := c.String("profile-cpu")
if cpuProfilePath != "" {
logrus.Infof("Creating CPU profile in: %v", cpuProfilePath)
file, err := os.Create(cpuProfilePath)
if err != nil {
cancel()
return fmt.Errorf("could not create CPU profile: %w", err)
}
defer file.Close()
if err := pprof.StartCPUProfile(file); err != nil {
cancel()
return fmt.Errorf("could not start CPU profiling: %w", err)
}
defer pprof.StopCPUProfile()
}
if c.Bool("profile") {
profilePort := c.Int("profile-port")
profileEndpoint := fmt.Sprintf("localhost:%v", profilePort)
go func() {
logrus.Debugf("Starting profiling server on %v", profileEndpoint)
if err := http.ListenAndServe(profileEndpoint, nil); err != nil {
logrus.Fatalf("Unable to run profiling server: %v", err)
}
}()
}
if c.Args().Len() > 0 {
cancel()
return fmt.Errorf("command %q not supported", c.Args().Get(0))
}
// Check if we joined a mount namespace
nsname, err := kubensmnt.Status()
if nsname != "" {
if err != nil {
logrus.Warn(err)
} else {
logrus.Infof("Joined mount namespace %q", nsname)
}
}
config, ok := c.App.Metadata["config"].(*libconfig.Config)
if !ok {
cancel()
return errors.New("type assertion error when accessing server config")
}
// Validate the configuration during runtime
if err := config.Validate(true); err != nil {
cancel()
return err
}
lis, err := server.Listen("unix", config.Listen)
if err != nil {
logrus.Fatalf("Failed to listen: %v", err)
}
if err := os.Chmod(config.Listen, 0o660); err != nil {
logrus.Fatalf("Failed to chmod listen socket %s: %v", config.Listen, err)
}
var (
tracerProvider *sdktrace.TracerProvider
opts []otelgrpc.Option
)
if config.EnableTracing {
tracerProvider, opts, err = opentelemetry.InitTracing(
ctx,
config.TracingEndpoint,
config.TracingSamplingRatePerMillion,
)
if err != nil {
logrus.Fatalf("Failed to initialize tracer provider: %v", err)
}
}
grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
otel_collector.UnaryInterceptor(),
)),
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
otel_collector.StreamInterceptor(),
)),
grpc.StatsHandler(otelgrpc.NewServerHandler(opts...)),
grpc.MaxSendMsgSize(config.GRPCMaxSendMsgSize),
grpc.MaxRecvMsgSize(config.GRPCMaxRecvMsgSize),
)
crioServer, err := server.New(ctx, config)
if err != nil {
logrus.Fatal(err)
}
// Immediately upon start up, write our new version files
// we write one to a tmpfs, so we can detect when a node rebooted.
if err := info.WriteVersionFile(config.VersionFile); err != nil {
logrus.Fatal(err)
}
// we then write to a persistent directory. This is to check if crio has upgraded
// if it has, we should wipe images
if err := info.WriteVersionFile(config.VersionFilePersist); err != nil {
logrus.Fatal(err)
}
if config.CleanShutdownFile != "" {
// clear out the shutdown file
if err := os.Remove(config.CleanShutdownFile); err != nil && !os.IsNotExist(err) {
logrus.Error(err)
}
if err := os.MkdirAll(filepath.Dir(config.CleanShutdownSupportedFileName()), 0o755); err != nil {
logrus.Errorf("Creating clean shutdown supported parent directory: %v", err)
}
// Write "$CleanShutdownFile".supported to show crio-wipe that
// we should be wiping if the CleanShutdownFile wasn't found.
// This protects us from wiping after an upgrade from a version that doesn't support
// CleanShutdownFile.
f, err := os.Create(config.CleanShutdownSupportedFileName())
if err != nil {
logrus.Errorf("Writing clean shutdown supported file: %v", err)
}
f.Close()
// and sync the changes to disk
if err := utils.SyncParent(config.CleanShutdownFile); err != nil {
logrus.Errorf("Failed to sync parent directory of clean shutdown file: %v", err)
}
}
// We always use 'Volatile: true' when creating containers, which means that in
// the event of an unclean shutdown, we might lose track of containers and layers.
// We need to call the garbage collection function to clean up the redundant files.
if err := crioServer.Store().GarbageCollect(); err != nil {
logrus.Errorf("Attempts to clean up unreferenced old container leftovers failed: %v", err)
}
v1.RegisterRuntimeServiceServer(grpcServer, crioServer)
v1.RegisterImageServiceServer(grpcServer, crioServer)
// after the daemon is done setting up we can notify systemd api
notifySystem()
go func() {
crioServer.StartExitMonitor(ctx)
}()
hookSync := make(chan error, 2)
if crioServer.ContainerServer.Hooks == nil {
hookSync <- err // so we don't block during cleanup
} else {
go crioServer.ContainerServer.Hooks.Monitor(ctx, hookSync)
err = <-hookSync
if err != nil {
cancel()
logrus.Fatal(err)
}
}
m := cmux.New(lis)
grpcL := m.MatchWithWriters(cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc"))
httpL := m.Match(cmux.HTTP1Fast())
infoMux := crioServer.GetExtendInterfaceMux(c.Bool("enable-profile-unix-socket"))
httpServer := &http.Server{
Handler: infoMux,
ReadTimeout: 5 * time.Second,
}
graceful := false
catchShutdown(ctx, cancel, grpcServer, tracerProvider, crioServer, httpServer, &graceful)
go func() {
if err := grpcServer.Serve(grpcL); err != nil {
logrus.Errorf("Unable to run GRPC server: %v", err)
}
}()
go func() {
if err := httpServer.Serve(httpL); err != nil {
logrus.Debugf("Closed http server")
}
}()
serverCloseCh := make(chan struct{})
go func() {
defer close(serverCloseCh)
if err := m.Serve(); err != nil {
if graceful && strings.Contains(strings.ToLower(err.Error()), "use of closed network connection") {
err = nil
} else {
logrus.Errorf("Failed to serve grpc request: %v", err)
}
}
}()
streamServerCloseCh := crioServer.StreamingServerCloseChan()
serverMonitorsCh := crioServer.MonitorsCloseChan()
select {
case <-streamServerCloseCh:
case <-serverMonitorsCh:
case <-serverCloseCh:
}
if err := crioServer.Shutdown(ctx); err != nil {
logrus.Warnf("Error shutting down service: %v", err)
}
cancel()
<-streamServerCloseCh
logrus.Debugf("Closed stream server")
<-serverMonitorsCh
logrus.Debugf("Closed monitors")
err = <-hookSync
if err == nil || errors.Is(err, context.Canceled) {
logrus.Debugf("Closed hook monitor")
} else {
logrus.Errorf("Hook monitor failed: %v", err)
}
<-serverCloseCh
logrus.Debugf("Closed main server")
memProfilePath := c.String("profile-mem")
if memProfilePath != "" {
logrus.Infof("Creating memory profile in: %v", memProfilePath)
file, err := os.Create(memProfilePath)
if err != nil {
return fmt.Errorf("could not create memory profile: %w", err)
}
defer file.Close()
runtime.GC()
if err := pprof.WriteHeapProfile(file); err != nil {
return fmt.Errorf("could not write memory profile: %w", err)
}
}
return nil
}
if err := app.Run(os.Args); err != nil {
logrus.Fatal(err)
}
}