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 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
|
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"expvar"
"fmt"
"io"
"net"
"net/http"
"net/http/pprof"
"os"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/containerd/ttrpc"
"github.com/docker/go-metrics"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
csapi "github.com/containerd/containerd/api/services/content/v1"
diffapi "github.com/containerd/containerd/api/services/diff/v1"
ssapi "github.com/containerd/containerd/api/services/snapshots/v1"
"github.com/containerd/containerd/content/local"
csproxy "github.com/containerd/containerd/content/proxy"
"github.com/containerd/containerd/defaults"
"github.com/containerd/containerd/diff"
diffproxy "github.com/containerd/containerd/diff/proxy"
"github.com/containerd/containerd/events/exchange"
"github.com/containerd/containerd/pkg/deprecation"
"github.com/containerd/containerd/pkg/dialer"
"github.com/containerd/containerd/pkg/timeout"
"github.com/containerd/containerd/plugin"
srvconfig "github.com/containerd/containerd/services/server/config"
"github.com/containerd/containerd/services/warning"
ssproxy "github.com/containerd/containerd/snapshots/proxy"
"github.com/containerd/containerd/sys"
"github.com/containerd/log"
"github.com/containerd/platforms"
)
// CreateTopLevelDirectories creates the top-level root and state directories.
func CreateTopLevelDirectories(config *srvconfig.Config) error {
switch {
case config.Root == "":
return errors.New("root must be specified")
case config.State == "":
return errors.New("state must be specified")
case config.Root == config.State:
return errors.New("root and state must be different paths")
}
if err := sys.MkdirAllWithACL(config.Root, 0711); err != nil {
return err
}
if err := sys.MkdirAllWithACL(config.State, 0711); err != nil {
return err
}
if config.State != defaults.DefaultStateDir {
// XXX: socketRoot in pkg/shim is hard-coded to the default state directory.
// See https://github.com/containerd/containerd/issues/10502#issuecomment-2249268582 for why it's set up that way.
// The default fifo directory in pkg/cio is also configured separately and defaults to the default state directory instead of the configured state directory.
// Make sure the default state directory is created with the correct permissions.
if err := sys.MkdirAllWithACL(defaults.DefaultStateDir, 0o711); err != nil {
return err
}
}
if config.TempDir != "" {
if err := sys.MkdirAllWithACL(config.TempDir, 0711); err != nil {
return err
}
if runtime.GOOS == "windows" {
// On Windows, the Host Compute Service (vmcompute) will read the
// TEMP/TMP setting from the calling process when creating the
// tempdir to extract an image layer to. This allows the
// administrator to align the tempdir location with the same volume
// as the snapshot dir to avoid a copy operation when moving the
// extracted layer to the snapshot dir location.
os.Setenv("TEMP", config.TempDir)
os.Setenv("TMP", config.TempDir)
} else {
os.Setenv("TMPDIR", config.TempDir)
}
}
return nil
}
// New creates and initializes a new containerd server
func New(ctx context.Context, config *srvconfig.Config) (*Server, error) {
if err := apply(ctx, config); err != nil {
return nil, err
}
for key, sec := range config.Timeouts {
d, err := time.ParseDuration(sec)
if err != nil {
return nil, fmt.Errorf("unable to parse %s into a time duration", sec)
}
timeout.Set(key, d)
}
plugins, err := LoadPlugins(ctx, config)
if err != nil {
return nil, err
}
for id, p := range config.StreamProcessors {
diff.RegisterProcessor(diff.BinaryHandler(id, p.Returns, p.Accepts, p.Path, p.Args, p.Env))
}
serverOpts := []grpc.ServerOption{
grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
}
if config.GRPC.MaxRecvMsgSize > 0 {
serverOpts = append(serverOpts, grpc.MaxRecvMsgSize(config.GRPC.MaxRecvMsgSize))
}
if config.GRPC.MaxSendMsgSize > 0 {
serverOpts = append(serverOpts, grpc.MaxSendMsgSize(config.GRPC.MaxSendMsgSize))
}
ttrpcServer, err := newTTRPCServer()
if err != nil {
return nil, err
}
tcpServerOpts := serverOpts
if config.GRPC.TCPTLSCert != "" {
log.G(ctx).Info("setting up tls on tcp GRPC services...")
tlsCert, err := tls.LoadX509KeyPair(config.GRPC.TCPTLSCert, config.GRPC.TCPTLSKey)
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
if config.GRPC.TCPTLSCA != "" {
caCertPool := x509.NewCertPool()
caCert, err := os.ReadFile(config.GRPC.TCPTLSCA)
if err != nil {
return nil, fmt.Errorf("failed to load CA file: %w", err)
}
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.ClientCAs = caCertPool
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
tcpServerOpts = append(tcpServerOpts, grpc.Creds(credentials.NewTLS(tlsConfig)))
}
// grpcService allows GRPC services to be registered with the underlying server
type grpcService interface {
Register(*grpc.Server) error
}
// tcpService allows GRPC services to be registered with the underlying tcp server
type tcpService interface {
RegisterTCP(*grpc.Server) error
}
// ttrpcService allows TTRPC services to be registered with the underlying server
type ttrpcService interface {
RegisterTTRPC(*ttrpc.Server) error
}
var (
grpcServer = grpc.NewServer(serverOpts...)
tcpServer = grpc.NewServer(tcpServerOpts...)
grpcServices []grpcService
tcpServices []tcpService
ttrpcServices []ttrpcService
s = &Server{
grpcServer: grpcServer,
tcpServer: tcpServer,
ttrpcServer: ttrpcServer,
config: config,
}
// TODO: Remove this in 2.0 and let event plugin crease it
events = exchange.NewExchange()
initialized = plugin.NewPluginSet()
required = make(map[string]struct{})
)
for _, r := range config.RequiredPlugins {
required[r] = struct{}{}
}
for _, p := range plugins {
id := p.URI()
reqID := id
if config.GetVersion() == 1 {
reqID = p.ID
}
log.G(ctx).WithField("type", p.Type).Infof("loading plugin %q...", id)
var mustSucceed int32
initContext := plugin.NewContext(
ctx,
p,
initialized,
config.Root,
config.State,
)
initContext.Events = events
initContext.Address = config.GRPC.Address
initContext.TTRPCAddress = config.TTRPC.Address
initContext.RegisterReadiness = func() func() {
atomic.StoreInt32(&mustSucceed, 1)
return s.RegisterReadiness()
}
// load the plugin specific configuration if it is provided
if p.Config != nil {
pc, err := config.Decode(p)
if err != nil {
return nil, err
}
initContext.Config = pc
}
result := p.Init(initContext)
if err := initialized.Add(result); err != nil {
return nil, fmt.Errorf("could not add plugin result to plugin set: %w", err)
}
instance, err := result.Instance()
if err != nil {
if plugin.IsSkipPlugin(err) {
log.G(ctx).WithError(err).WithField("type", p.Type).Infof("skip loading plugin %q...", id)
} else {
log.G(ctx).WithError(err).Warnf("failed to load plugin %s", id)
}
if _, ok := required[reqID]; ok {
return nil, fmt.Errorf("load required plugin %s: %w", id, err)
}
// If readiness was registered during initialization, the plugin cannot fail
if atomic.LoadInt32(&mustSucceed) != 0 {
return nil, fmt.Errorf("plugin failed after registering readiness %s: %w", id, err)
}
continue
}
delete(required, reqID)
// check for grpc services that should be registered with the server
if src, ok := instance.(grpcService); ok {
grpcServices = append(grpcServices, src)
}
if src, ok := instance.(ttrpcService); ok {
ttrpcServices = append(ttrpcServices, src)
}
if service, ok := instance.(tcpService); ok {
tcpServices = append(tcpServices, service)
}
s.plugins = append(s.plugins, result)
}
if len(required) != 0 {
var missing []string
for id := range required {
missing = append(missing, id)
}
return nil, fmt.Errorf("required plugin %s not included", missing)
}
// register services after all plugins have been initialized
for _, service := range grpcServices {
if err := service.Register(grpcServer); err != nil {
return nil, err
}
}
for _, service := range ttrpcServices {
if err := service.RegisterTTRPC(ttrpcServer); err != nil {
return nil, err
}
}
for _, service := range tcpServices {
if err := service.RegisterTCP(tcpServer); err != nil {
return nil, err
}
}
recordConfigDeprecations(ctx, config, initialized)
return s, nil
}
// recordConfigDeprecations attempts to record use of any deprecated config field. Failures are logged and ignored.
func recordConfigDeprecations(ctx context.Context, config *srvconfig.Config, set *plugin.Set) {
// record any detected deprecations without blocking server startup
plugin, err := set.GetByID(plugin.WarningPlugin, plugin.DeprecationsPlugin)
if err != nil {
log.G(ctx).WithError(err).Warn("failed to load warning service to record deprecations")
return
}
instance, err := plugin.Instance()
if err != nil {
log.G(ctx).WithError(err).Warn("failed to load warning service to record deprecations")
return
}
warn, ok := instance.(warning.Service)
if !ok {
log.G(ctx).WithError(err).Warn("failed to load warning service to record deprecations, unexpected plugin type")
return
}
if config.PluginDir != "" {
warn.Emit(ctx, deprecation.GoPluginLibrary)
}
}
// Server is the containerd main daemon
type Server struct {
grpcServer *grpc.Server
ttrpcServer *ttrpc.Server
tcpServer *grpc.Server
config *srvconfig.Config
plugins []*plugin.Plugin
ready sync.WaitGroup
}
// ServeGRPC provides the containerd grpc APIs on the provided listener
func (s *Server) ServeGRPC(l net.Listener) error {
if s.config.Metrics.GRPCHistogram {
// enable grpc time histograms to measure rpc latencies
grpc_prometheus.EnableHandlingTimeHistogram()
}
// before we start serving the grpc API register the grpc_prometheus metrics
// handler. This needs to be the last service registered so that it can collect
// metrics for every other service
grpc_prometheus.Register(s.grpcServer)
return trapClosedConnErr(s.grpcServer.Serve(l))
}
// ServeTTRPC provides the containerd ttrpc APIs on the provided listener
func (s *Server) ServeTTRPC(l net.Listener) error {
return trapClosedConnErr(s.ttrpcServer.Serve(context.Background(), l))
}
// ServeMetrics provides a prometheus endpoint for exposing metrics
func (s *Server) ServeMetrics(l net.Listener) error {
m := http.NewServeMux()
m.Handle("/v1/metrics", metrics.Handler())
srv := &http.Server{
Handler: m,
ReadHeaderTimeout: 5 * time.Minute, // "G112: Potential Slowloris Attack (gosec)"; not a real concern for our use, so setting a long timeout.
}
return trapClosedConnErr(srv.Serve(l))
}
// ServeTCP allows services to serve over tcp
func (s *Server) ServeTCP(l net.Listener) error {
grpc_prometheus.Register(s.tcpServer)
return trapClosedConnErr(s.tcpServer.Serve(l))
}
// ServeDebug provides a debug endpoint
func (s *Server) ServeDebug(l net.Listener) error {
// don't use the default http server mux to make sure nothing gets registered
// that we don't want to expose via containerd
m := http.NewServeMux()
m.Handle("/debug/vars", expvar.Handler())
m.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
m.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
m.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
m.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
m.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
srv := &http.Server{
Handler: m,
ReadHeaderTimeout: 5 * time.Minute, // "G112: Potential Slowloris Attack (gosec)"; not a real concern for our use, so setting a long timeout.
}
return trapClosedConnErr(srv.Serve(l))
}
// Stop the containerd server canceling any open connections
func (s *Server) Stop() {
s.grpcServer.Stop()
for i := len(s.plugins) - 1; i >= 0; i-- {
p := s.plugins[i]
instance, err := p.Instance()
if err != nil {
log.L.WithError(err).WithField("id", p.Registration.URI()).
Error("could not get plugin instance")
continue
}
closer, ok := instance.(io.Closer)
if !ok {
continue
}
if err := closer.Close(); err != nil {
log.L.WithError(err).WithField("id", p.Registration.URI()).
Error("failed to close plugin")
}
}
}
func (s *Server) RegisterReadiness() func() {
s.ready.Add(1)
return func() {
s.ready.Done()
}
}
func (s *Server) Wait() {
s.ready.Wait()
}
// LoadPlugins loads all plugins into containerd and generates an ordered graph
// of all plugins.
func LoadPlugins(ctx context.Context, config *srvconfig.Config) ([]*plugin.Registration, error) {
// load all plugins into containerd
path := config.PluginDir
if path == "" {
path = filepath.Join(config.Root, "plugins")
}
if count, err := plugin.Load(path); err != nil {
return nil, err
} else if count > 0 || config.PluginDir != "" {
config.PluginDir = path
log.G(ctx).Warningf("loaded %d dynamic plugins. `go_plugin` is deprecated, please use `external plugins` instead", count)
}
// load additional plugins that don't automatically register themselves
plugin.Register(&plugin.Registration{
Type: plugin.ContentPlugin,
ID: "content",
InitFn: func(ic *plugin.InitContext) (interface{}, error) {
ic.Meta.Exports["root"] = ic.Root
return local.NewStore(ic.Root)
},
})
clients := &proxyClients{}
for name, pp := range config.ProxyPlugins {
var (
t plugin.Type
f func(*grpc.ClientConn) interface{}
address = pp.Address
p v1.Platform
err error
)
switch pp.Type {
case string(plugin.SnapshotPlugin), "snapshot":
t = plugin.SnapshotPlugin
ssname := name
f = func(conn *grpc.ClientConn) interface{} {
return ssproxy.NewSnapshotter(ssapi.NewSnapshotsClient(conn), ssname)
}
case string(plugin.ContentPlugin), "content":
t = plugin.ContentPlugin
f = func(conn *grpc.ClientConn) interface{} {
return csproxy.NewContentStore(csapi.NewContentClient(conn))
}
case string(plugin.DiffPlugin), "diff":
t = plugin.DiffPlugin
f = func(conn *grpc.ClientConn) interface{} {
return diffproxy.NewDiffApplier(diffapi.NewDiffClient(conn))
}
default:
log.G(ctx).WithField("type", pp.Type).Warn("unknown proxy plugin type")
}
if pp.Platform != "" {
p, err = platforms.Parse(pp.Platform)
if err != nil {
log.G(ctx).WithError(err).WithField("plugin", name).Warn("skipping proxy platform with bad platform")
}
} else {
p = platforms.DefaultSpec()
}
exports := pp.Exports
if exports == nil {
exports = map[string]string{}
}
exports["address"] = address
plugin.Register(&plugin.Registration{
Type: t,
ID: name,
InitFn: func(ic *plugin.InitContext) (interface{}, error) {
ic.Meta.Exports = exports
ic.Meta.Platforms = append(ic.Meta.Platforms, p)
ic.Meta.Capabilities = pp.Capabilities
conn, err := clients.getClient(address)
if err != nil {
return nil, err
}
return f(conn), nil
},
})
}
filter := srvconfig.V2DisabledFilter
if config.GetVersion() == 1 {
filter = srvconfig.V1DisabledFilter
}
// return the ordered graph for plugins
return plugin.Graph(filter(config.DisabledPlugins)), nil
}
type proxyClients struct {
m sync.Mutex
clients map[string]*grpc.ClientConn
}
func (pc *proxyClients) getClient(address string) (*grpc.ClientConn, error) {
pc.m.Lock()
defer pc.m.Unlock()
if pc.clients == nil {
pc.clients = map[string]*grpc.ClientConn{}
} else if c, ok := pc.clients[address]; ok {
return c, nil
}
backoffConfig := backoff.DefaultConfig
backoffConfig.MaxDelay = 3 * time.Second
connParams := grpc.ConnectParams{
Backoff: backoffConfig,
}
gopts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithConnectParams(connParams),
grpc.WithContextDialer(dialer.ContextDialer),
// TODO(stevvooe): We may need to allow configuration of this on the client.
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(defaults.DefaultMaxRecvMsgSize)),
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(defaults.DefaultMaxSendMsgSize)),
}
conn, err := grpc.Dial(dialer.DialAddress(address), gopts...)
if err != nil {
return nil, fmt.Errorf("failed to dial %q: %w", address, err)
}
pc.clients[address] = conn
return conn, nil
}
func trapClosedConnErr(err error) error {
if err == nil || errors.Is(err, net.ErrClosed) {
return nil
}
return err
}
|