| 1 |
//go:build linux |
| 2 |
|
| 3 |
/* |
| 4 |
Copyright The containerd Authors. |
| 5 |
|
| 6 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 |
you may not use this file except in compliance with the License. |
| 8 |
You may obtain a copy of the License at |
| 9 |
|
| 10 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
|
| 12 |
Unless required by applicable law or agreed to in writing, software |
| 13 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 14 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 |
See the License for the specific language governing permissions and |
| 16 |
limitations under the License. |
| 17 |
*/ |
| 18 |
|
| 19 |
package task |
| 20 |
|
| 21 |
import ( |
| 22 |
"context" |
| 23 |
"fmt" |
| 24 |
"os" |
| 25 |
"sync" |
| 26 |
|
| 27 |
"github.com/moby/sys/userns" |
| 28 |
|
| 29 |
"github.com/containerd/cgroups/v3" |
| 30 |
"github.com/containerd/cgroups/v3/cgroup1" |
| 31 |
cgroupsv2 "github.com/containerd/cgroups/v3/cgroup2" |
| 32 |
eventstypes "github.com/containerd/containerd/api/events" |
| 33 |
taskAPI "github.com/containerd/containerd/api/runtime/task/v3" |
| 34 |
"github.com/containerd/containerd/api/types/runc/options" |
| 35 |
"github.com/containerd/containerd/api/types/task" |
| 36 |
"github.com/containerd/errdefs" |
| 37 |
"github.com/containerd/errdefs/pkg/errgrpc" |
| 38 |
runcC "github.com/containerd/go-runc" |
| 39 |
"github.com/containerd/log" |
| 40 |
"github.com/containerd/ttrpc" |
| 41 |
"github.com/containerd/typeurl/v2" |
| 42 |
|
| 43 |
"github.com/containerd/containerd/v2/cmd/containerd-shim-runc-v2/process" |
| 44 |
"github.com/containerd/containerd/v2/cmd/containerd-shim-runc-v2/runc" |
| 45 |
"github.com/containerd/containerd/v2/core/runtime" |
| 46 |
"github.com/containerd/containerd/v2/pkg/namespaces" |
| 47 |
"github.com/containerd/containerd/v2/pkg/oom" |
| 48 |
oomv1 "github.com/containerd/containerd/v2/pkg/oom/v1" |
| 49 |
oomv2 "github.com/containerd/containerd/v2/pkg/oom/v2" |
| 50 |
"github.com/containerd/containerd/v2/pkg/protobuf" |
| 51 |
ptypes "github.com/containerd/containerd/v2/pkg/protobuf/types" |
| 52 |
"github.com/containerd/containerd/v2/pkg/shim" |
| 53 |
"github.com/containerd/containerd/v2/pkg/shutdown" |
| 54 |
"github.com/containerd/containerd/v2/pkg/stdio" |
| 55 |
"github.com/containerd/containerd/v2/pkg/sys/reaper" |
| 56 |
) |
| 57 |
|
| 58 |
var ( |
| 59 |
_ = shim.TTRPCService(&service{}) |
| 60 |
empty = &ptypes.Empty{} |
| 61 |
) |
| 62 |
|
| 63 |
// NewTaskService creates a new instance of a task service |
| 64 |
func NewTaskService(ctx context.Context, publisher shim.Publisher, sd shutdown.Service) (taskAPI.TTRPCTaskService, error) { |
| 65 |
var ( |
| 66 |
ep oom.Watcher |
| 67 |
err error |
| 68 |
) |
| 69 |
if cgroups.Mode() == cgroups.Unified { |
| 70 |
ep, err = oomv2.New(publisher) |
| 71 |
} else { |
| 72 |
ep, err = oomv1.New(publisher) |
| 73 |
} |
| 74 |
if err != nil { |
| 75 |
return nil, err |
| 76 |
} |
| 77 |
go ep.Run(ctx) |
| 78 |
s := &service{ |
| 79 |
context: ctx, |
| 80 |
events: make(chan interface{}, 128), |
| 81 |
ec: reaper.Default.Subscribe(), |
| 82 |
ep: ep, |
| 83 |
shutdown: sd, |
| 84 |
containers: make(map[string]*runc.Container), |
| 85 |
running: make(map[int][]containerProcess), |
| 86 |
runningExecs: make(map[*runc.Container]int), |
| 87 |
execCountSubscribers: make(map[*runc.Container]chan<- int), |
| 88 |
containerInitExit: make(map[*runc.Container]runcC.Exit), |
| 89 |
exitSubscribers: make(map[*map[int][]runcC.Exit]struct{}), |
| 90 |
} |
| 91 |
go s.processExits() |
| 92 |
runcC.Monitor = reaper.Default |
| 93 |
if err := s.initPlatform(); err != nil { |
| 94 |
return nil, fmt.Errorf("failed to initialized platform behavior: %w", err) |
| 95 |
} |
| 96 |
go s.forward(ctx, publisher) |
| 97 |
sd.RegisterCallback(func(context.Context) error { |
| 98 |
close(s.events) |
| 99 |
return nil |
| 100 |
}) |
| 101 |
|
| 102 |
if address, err := shim.ReadAddress("address"); err == nil { |
| 103 |
sd.RegisterCallback(func(context.Context) error { |
| 104 |
return shim.RemoveSocket(address) |
| 105 |
}) |
| 106 |
} |
| 107 |
return s, nil |
| 108 |
} |
| 109 |
|
| 110 |
// service is the shim implementation of a remote shim over GRPC |
| 111 |
type service struct { |
| 112 |
mu sync.Mutex |
| 113 |
|
| 114 |
context context.Context |
| 115 |
events chan interface{} |
| 116 |
platform stdio.Platform |
| 117 |
ec chan runcC.Exit |
| 118 |
ep oom.Watcher |
| 119 |
|
| 120 |
containers map[string]*runc.Container |
| 121 |
|
| 122 |
lifecycleMu sync.Mutex |
| 123 |
running map[int][]containerProcess // pid -> running process, guarded by lifecycleMu |
| 124 |
runningExecs map[*runc.Container]int // container -> num running execs, guarded by lifecycleMu |
| 125 |
// container -> subscription to exec exits/changes to s.runningExecs[container], |
| 126 |
// guarded by lifecycleMu |
| 127 |
execCountSubscribers map[*runc.Container]chan<- int |
| 128 |
// container -> init exits, guarded by lifecycleMu |
| 129 |
// Used to stash container init process exits, so that we can hold them |
| 130 |
// until after we've made sure to publish all the container's exec exits. |
| 131 |
// Also used to prevent starting new execs from being started if the |
| 132 |
// container's init process (read: pid, not [process.Init]) has already been |
| 133 |
// reaped by the shim. |
| 134 |
// Note that this flag gets updated before the container's [process.Init.Status] |
| 135 |
// is transitioned to "stopped". |
| 136 |
containerInitExit map[*runc.Container]runcC.Exit |
| 137 |
// Subscriptions to exits for PIDs. Adding/deleting subscriptions and |
| 138 |
// dereferencing the subscription pointers must only be done while holding |
| 139 |
// lifecycleMu. |
| 140 |
exitSubscribers map[*map[int][]runcC.Exit]struct{} |
| 141 |
|
| 142 |
shutdown shutdown.Service |
| 143 |
} |
| 144 |
|
| 145 |
type containerProcess struct { |
| 146 |
Container *runc.Container |
| 147 |
Process process.Process |
| 148 |
} |
| 149 |
|
| 150 |
// preStart prepares for starting a container process and handling its exit. |
| 151 |
// The container being started should be passed in as c when starting the container |
| 152 |
// init process for an already-created container. c should be nil when creating a |
| 153 |
// container or when starting an exec. |
| 154 |
// |
| 155 |
// The returned handleStarted closure records that the process has started so |
| 156 |
// that its exit can be handled efficiently. If the process has already exited, |
| 157 |
// it handles the exit immediately. |
| 158 |
// handleStarted should be called after the event announcing the start of the |
| 159 |
// process has been published. Note that s.lifecycleMu must not be held when |
| 160 |
// calling handleStarted. |
| 161 |
// |
| 162 |
// The returned cleanup closure releases resources used to handle early exits. |
| 163 |
// It must be called before the caller of preStart returns, otherwise severe |
| 164 |
// memory leaks will occur. |
| 165 |
func (s *service) preStart(c *runc.Container) (handleStarted func(*runc.Container, process.Process), cleanup func()) { |
| 166 |
exits := make(map[int][]runcC.Exit) |
| 167 |
s.exitSubscribers[&exits] = struct{}{} |
| 168 |
|
| 169 |
if c != nil { |
| 170 |
// Remove container init process from s.running so it will once again be |
| 171 |
// treated as an early exit if it exits before handleStarted is called. |
| 172 |
pid := c.Pid() |
| 173 |
var newRunning []containerProcess |
| 174 |
for _, cp := range s.running[pid] { |
| 175 |
if cp.Container != c { |
| 176 |
newRunning = append(newRunning, cp) |
| 177 |
} |
| 178 |
} |
| 179 |
if len(newRunning) > 0 { |
| 180 |
s.running[pid] = newRunning |
| 181 |
} else { |
| 182 |
delete(s.running, pid) |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
handleStarted = func(c *runc.Container, p process.Process) { |
| 187 |
var pid int |
| 188 |
if p != nil { |
| 189 |
pid = p.Pid() |
| 190 |
} |
| 191 |
|
| 192 |
s.lifecycleMu.Lock() |
| 193 |
|
| 194 |
ees, exited := exits[pid] |
| 195 |
delete(s.exitSubscribers, &exits) |
| 196 |
exits = nil |
| 197 |
if pid == 0 || exited { |
| 198 |
s.lifecycleMu.Unlock() |
| 199 |
for _, ee := range ees { |
| 200 |
s.handleProcessExit(ee, c, p) |
| 201 |
} |
| 202 |
} else { |
| 203 |
// Process start was successful, add to `s.running`. |
| 204 |
s.running[pid] = append(s.running[pid], containerProcess{ |
| 205 |
Container: c, |
| 206 |
Process: p, |
| 207 |
}) |
| 208 |
s.lifecycleMu.Unlock() |
| 209 |
} |
| 210 |
} |
| 211 |
|
| 212 |
cleanup = func() { |
| 213 |
if exits != nil { |
| 214 |
s.lifecycleMu.Lock() |
| 215 |
defer s.lifecycleMu.Unlock() |
| 216 |
delete(s.exitSubscribers, &exits) |
| 217 |
} |
| 218 |
} |
| 219 |
|
| 220 |
return handleStarted, cleanup |
| 221 |
} |
| 222 |
|
| 223 |
// Create a new initial process and container with the underlying OCI runtime |
| 224 |
func (s *service) Create(ctx context.Context, r *taskAPI.CreateTaskRequest) (_ *taskAPI.CreateTaskResponse, err error) { |
| 225 |
s.mu.Lock() |
| 226 |
defer s.mu.Unlock() |
| 227 |
|
| 228 |
s.lifecycleMu.Lock() |
| 229 |
handleStarted, cleanup := s.preStart(nil) |
| 230 |
s.lifecycleMu.Unlock() |
| 231 |
defer cleanup() |
| 232 |
|
| 233 |
container, err := runc.NewContainer(ctx, s.platform, r) |
| 234 |
if err != nil { |
| 235 |
return nil, err |
| 236 |
} |
| 237 |
|
| 238 |
s.containers[r.ID] = container |
| 239 |
|
| 240 |
s.send(&eventstypes.TaskCreate{ |
| 241 |
ContainerID: r.ID, |
| 242 |
Bundle: r.Bundle, |
| 243 |
Rootfs: r.Rootfs, |
| 244 |
IO: &eventstypes.TaskIO{ |
| 245 |
Stdin: r.Stdin, |
| 246 |
Stdout: r.Stdout, |
| 247 |
Stderr: r.Stderr, |
| 248 |
Terminal: r.Terminal, |
| 249 |
}, |
| 250 |
Checkpoint: r.Checkpoint, |
| 251 |
Pid: uint32(container.Pid()), |
| 252 |
}) |
| 253 |
|
| 254 |
// The following line cannot return an error as the only state in which that |
| 255 |
// could happen would also cause the container.Pid() call above to |
| 256 |
// nil-deference panic. |
| 257 |
proc, _ := container.Process("") |
| 258 |
handleStarted(container, proc) |
| 259 |
|
| 260 |
return &taskAPI.CreateTaskResponse{ |
| 261 |
Pid: uint32(container.Pid()), |
| 262 |
}, nil |
| 263 |
} |
| 264 |
|
| 265 |
func (s *service) RegisterTTRPC(server *ttrpc.Server) error { |
| 266 |
taskAPI.RegisterTTRPCTaskService(server, s) |
| 267 |
return nil |
| 268 |
} |
| 269 |
|
| 270 |
// Start a process |
| 271 |
func (s *service) Start(ctx context.Context, r *taskAPI.StartRequest) (*taskAPI.StartResponse, error) { |
| 272 |
container, err := s.getContainer(r.ID) |
| 273 |
if err != nil { |
| 274 |
return nil, err |
| 275 |
} |
| 276 |
|
| 277 |
var cinit *runc.Container |
| 278 |
s.lifecycleMu.Lock() |
| 279 |
if r.ExecID == "" { |
| 280 |
cinit = container |
| 281 |
} else { |
| 282 |
if _, initExited := s.containerInitExit[container]; initExited { |
| 283 |
s.lifecycleMu.Unlock() |
| 284 |
return nil, errgrpc.ToGRPCf(errdefs.ErrFailedPrecondition, "container %s init process is not running", container.ID) |
| 285 |
} |
| 286 |
s.runningExecs[container]++ |
| 287 |
} |
| 288 |
handleStarted, cleanup := s.preStart(cinit) |
| 289 |
s.lifecycleMu.Unlock() |
| 290 |
defer cleanup() |
| 291 |
|
| 292 |
p, err := container.Start(ctx, r) |
| 293 |
if err != nil { |
| 294 |
// If we failed to even start the process, s.runningExecs |
| 295 |
// won't get decremented in s.handleProcessExit. We still need |
| 296 |
// to update it. |
| 297 |
if r.ExecID != "" { |
| 298 |
s.lifecycleMu.Lock() |
| 299 |
s.runningExecs[container]-- |
| 300 |
if ch, ok := s.execCountSubscribers[container]; ok { |
| 301 |
ch <- s.runningExecs[container] |
| 302 |
} |
| 303 |
s.lifecycleMu.Unlock() |
| 304 |
} |
| 305 |
handleStarted(container, p) |
| 306 |
return nil, errgrpc.ToGRPC(err) |
| 307 |
} |
| 308 |
|
| 309 |
switch r.ExecID { |
| 310 |
case "": |
| 311 |
switch cg := container.Cgroup().(type) { |
| 312 |
case cgroup1.Cgroup: |
| 313 |
if err := s.ep.Add(container.ID, cg); err != nil { |
| 314 |
log.G(ctx).WithError(err).Error("add cg to OOM monitor") |
| 315 |
} |
| 316 |
case *cgroupsv2.Manager: |
| 317 |
allControllers, err := cg.RootControllers() |
| 318 |
if err != nil { |
| 319 |
log.G(ctx).WithError(err).Error("failed to get root controllers") |
| 320 |
} else { |
| 321 |
if err := cg.ToggleControllers(allControllers, cgroupsv2.Enable); err != nil { |
| 322 |
if userns.RunningInUserNS() { |
| 323 |
log.G(ctx).WithError(err).Debugf("failed to enable controllers (%v)", allControllers) |
| 324 |
} else { |
| 325 |
log.G(ctx).WithError(err).Errorf("failed to enable controllers (%v)", allControllers) |
| 326 |
} |
| 327 |
} |
| 328 |
} |
| 329 |
if err := s.ep.Add(container.ID, cg); err != nil { |
| 330 |
log.G(ctx).WithError(err).Error("add cg to OOM monitor") |
| 331 |
} |
| 332 |
} |
| 333 |
|
| 334 |
s.send(&eventstypes.TaskStart{ |
| 335 |
ContainerID: container.ID, |
| 336 |
Pid: uint32(p.Pid()), |
| 337 |
}) |
| 338 |
default: |
| 339 |
s.send(&eventstypes.TaskExecStarted{ |
| 340 |
ContainerID: container.ID, |
| 341 |
ExecID: r.ExecID, |
| 342 |
Pid: uint32(p.Pid()), |
| 343 |
}) |
| 344 |
} |
| 345 |
handleStarted(container, p) |
| 346 |
return &taskAPI.StartResponse{ |
| 347 |
Pid: uint32(p.Pid()), |
| 348 |
}, nil |
| 349 |
} |
| 350 |
|
| 351 |
// Delete the initial process and container |
| 352 |
func (s *service) Delete(ctx context.Context, r *taskAPI.DeleteRequest) (*taskAPI.DeleteResponse, error) { |
| 353 |
container, err := s.getContainer(r.ID) |
| 354 |
if err != nil { |
| 355 |
return nil, err |
| 356 |
} |
| 357 |
p, err := container.Delete(ctx, r) |
| 358 |
if err != nil { |
| 359 |
return nil, errgrpc.ToGRPC(err) |
| 360 |
} |
| 361 |
// if we deleted an init task, send the task delete event |
| 362 |
if r.ExecID == "" { |
| 363 |
s.mu.Lock() |
| 364 |
delete(s.containers, r.ID) |
| 365 |
s.mu.Unlock() |
| 366 |
s.send(&eventstypes.TaskDelete{ |
| 367 |
ContainerID: container.ID, |
| 368 |
Pid: uint32(p.Pid()), |
| 369 |
ExitStatus: uint32(p.ExitStatus()), |
| 370 |
ExitedAt: protobuf.ToTimestamp(p.ExitedAt()), |
| 371 |
}) |
| 372 |
s.lifecycleMu.Lock() |
| 373 |
delete(s.containerInitExit, container) |
| 374 |
s.lifecycleMu.Unlock() |
| 375 |
} |
| 376 |
return &taskAPI.DeleteResponse{ |
| 377 |
ExitStatus: uint32(p.ExitStatus()), |
| 378 |
ExitedAt: protobuf.ToTimestamp(p.ExitedAt()), |
| 379 |
Pid: uint32(p.Pid()), |
| 380 |
}, nil |
| 381 |
} |
| 382 |
|
| 383 |
// Exec an additional process inside the container |
| 384 |
func (s *service) Exec(ctx context.Context, r *taskAPI.ExecProcessRequest) (*ptypes.Empty, error) { |
| 385 |
container, err := s.getContainer(r.ID) |
| 386 |
if err != nil { |
| 387 |
return nil, err |
| 388 |
} |
| 389 |
ok, cancel := container.ReserveProcess(r.ExecID) |
| 390 |
if !ok { |
| 391 |
return nil, errgrpc.ToGRPCf(errdefs.ErrAlreadyExists, "id %s", r.ExecID) |
| 392 |
} |
| 393 |
process, err := container.Exec(ctx, r) |
| 394 |
if err != nil { |
| 395 |
cancel() |
| 396 |
return nil, errgrpc.ToGRPC(err) |
| 397 |
} |
| 398 |
|
| 399 |
s.send(&eventstypes.TaskExecAdded{ |
| 400 |
ContainerID: container.ID, |
| 401 |
ExecID: process.ID(), |
| 402 |
}) |
| 403 |
return empty, nil |
| 404 |
} |
| 405 |
|
| 406 |
// ResizePty of a process |
| 407 |
func (s *service) ResizePty(ctx context.Context, r *taskAPI.ResizePtyRequest) (*ptypes.Empty, error) { |
| 408 |
container, err := s.getContainer(r.ID) |
| 409 |
if err != nil { |
| 410 |
return nil, err |
| 411 |
} |
| 412 |
if err := container.ResizePty(ctx, r); err != nil { |
| 413 |
return nil, errgrpc.ToGRPC(err) |
| 414 |
} |
| 415 |
return empty, nil |
| 416 |
} |
| 417 |
|
| 418 |
// State returns runtime state information for a process |
| 419 |
func (s *service) State(ctx context.Context, r *taskAPI.StateRequest) (*taskAPI.StateResponse, error) { |
| 420 |
container, err := s.getContainer(r.ID) |
| 421 |
if err != nil { |
| 422 |
return nil, err |
| 423 |
} |
| 424 |
p, err := container.Process(r.ExecID) |
| 425 |
if err != nil { |
| 426 |
return nil, errgrpc.ToGRPC(err) |
| 427 |
} |
| 428 |
st, err := p.Status(ctx) |
| 429 |
if err != nil { |
| 430 |
return nil, err |
| 431 |
} |
| 432 |
status := task.Status_UNKNOWN |
| 433 |
switch st { |
| 434 |
case "created": |
| 435 |
status = task.Status_CREATED |
| 436 |
case "running": |
| 437 |
status = task.Status_RUNNING |
| 438 |
case "stopped": |
| 439 |
status = task.Status_STOPPED |
| 440 |
case "paused": |
| 441 |
status = task.Status_PAUSED |
| 442 |
case "pausing": |
| 443 |
status = task.Status_PAUSING |
| 444 |
} |
| 445 |
sio := p.Stdio() |
| 446 |
return &taskAPI.StateResponse{ |
| 447 |
ID: p.ID(), |
| 448 |
Bundle: container.Bundle, |
| 449 |
Pid: uint32(p.Pid()), |
| 450 |
Status: status, |
| 451 |
Stdin: sio.Stdin, |
| 452 |
Stdout: sio.Stdout, |
| 453 |
Stderr: sio.Stderr, |
| 454 |
Terminal: sio.Terminal, |
| 455 |
ExitStatus: uint32(p.ExitStatus()), |
| 456 |
ExitedAt: protobuf.ToTimestamp(p.ExitedAt()), |
| 457 |
}, nil |
| 458 |
} |
| 459 |
|
| 460 |
// Pause the container |
| 461 |
func (s *service) Pause(ctx context.Context, r *taskAPI.PauseRequest) (*ptypes.Empty, error) { |
| 462 |
container, err := s.getContainer(r.ID) |
| 463 |
if err != nil { |
| 464 |
return nil, err |
| 465 |
} |
| 466 |
if err := container.Pause(ctx); err != nil { |
| 467 |
return nil, errgrpc.ToGRPC(err) |
| 468 |
} |
| 469 |
s.send(&eventstypes.TaskPaused{ |
| 470 |
ContainerID: container.ID, |
| 471 |
}) |
| 472 |
return empty, nil |
| 473 |
} |
| 474 |
|
| 475 |
// Resume the container |
| 476 |
func (s *service) Resume(ctx context.Context, r *taskAPI.ResumeRequest) (*ptypes.Empty, error) { |
| 477 |
container, err := s.getContainer(r.ID) |
| 478 |
if err != nil { |
| 479 |
return nil, err |
| 480 |
} |
| 481 |
if err := container.Resume(ctx); err != nil { |
| 482 |
return nil, errgrpc.ToGRPC(err) |
| 483 |
} |
| 484 |
s.send(&eventstypes.TaskResumed{ |
| 485 |
ContainerID: container.ID, |
| 486 |
}) |
| 487 |
return empty, nil |
| 488 |
} |
| 489 |
|
| 490 |
// Kill a process with the provided signal |
| 491 |
func (s *service) Kill(ctx context.Context, r *taskAPI.KillRequest) (*ptypes.Empty, error) { |
| 492 |
container, err := s.getContainer(r.ID) |
| 493 |
if err != nil { |
| 494 |
return nil, err |
| 495 |
} |
| 496 |
if err := container.Kill(ctx, r); err != nil { |
| 497 |
return nil, errgrpc.ToGRPC(err) |
| 498 |
} |
| 499 |
return empty, nil |
| 500 |
} |
| 501 |
|
| 502 |
// Pids returns all pids inside the container |
| 503 |
func (s *service) Pids(ctx context.Context, r *taskAPI.PidsRequest) (*taskAPI.PidsResponse, error) { |
| 504 |
container, err := s.getContainer(r.ID) |
| 505 |
if err != nil { |
| 506 |
return nil, err |
| 507 |
} |
| 508 |
pids, err := s.getContainerPids(ctx, container) |
| 509 |
if err != nil { |
| 510 |
return nil, errgrpc.ToGRPC(err) |
| 511 |
} |
| 512 |
var processes []*task.ProcessInfo |
| 513 |
for _, pid := range pids { |
| 514 |
pInfo := task.ProcessInfo{ |
| 515 |
Pid: pid, |
| 516 |
} |
| 517 |
for _, p := range container.ExecdProcesses() { |
| 518 |
if p.Pid() == int(pid) { |
| 519 |
d := &options.ProcessDetails{ |
| 520 |
ExecID: p.ID(), |
| 521 |
} |
| 522 |
a, err := typeurl.MarshalAnyToProto(d) |
| 523 |
if err != nil { |
| 524 |
return nil, fmt.Errorf("failed to marshal process %d info: %w", pid, err) |
| 525 |
} |
| 526 |
pInfo.Info = a |
| 527 |
break |
| 528 |
} |
| 529 |
} |
| 530 |
processes = append(processes, &pInfo) |
| 531 |
} |
| 532 |
return &taskAPI.PidsResponse{ |
| 533 |
Processes: processes, |
| 534 |
}, nil |
| 535 |
} |
| 536 |
|
| 537 |
// CloseIO of a process |
| 538 |
func (s *service) CloseIO(ctx context.Context, r *taskAPI.CloseIORequest) (*ptypes.Empty, error) { |
| 539 |
container, err := s.getContainer(r.ID) |
| 540 |
if err != nil { |
| 541 |
return nil, err |
| 542 |
} |
| 543 |
if err := container.CloseIO(ctx, r); err != nil { |
| 544 |
return nil, err |
| 545 |
} |
| 546 |
return empty, nil |
| 547 |
} |
| 548 |
|
| 549 |
// Checkpoint the container |
| 550 |
func (s *service) Checkpoint(ctx context.Context, r *taskAPI.CheckpointTaskRequest) (*ptypes.Empty, error) { |
| 551 |
container, err := s.getContainer(r.ID) |
| 552 |
if err != nil { |
| 553 |
return nil, err |
| 554 |
} |
| 555 |
if err := container.Checkpoint(ctx, r); err != nil { |
| 556 |
return nil, errgrpc.ToGRPC(err) |
| 557 |
} |
| 558 |
return empty, nil |
| 559 |
} |
| 560 |
|
| 561 |
// Update a running container |
| 562 |
func (s *service) Update(ctx context.Context, r *taskAPI.UpdateTaskRequest) (*ptypes.Empty, error) { |
| 563 |
container, err := s.getContainer(r.ID) |
| 564 |
if err != nil { |
| 565 |
return nil, err |
| 566 |
} |
| 567 |
if err := container.Update(ctx, r); err != nil { |
| 568 |
return nil, errgrpc.ToGRPC(err) |
| 569 |
} |
| 570 |
return empty, nil |
| 571 |
} |
| 572 |
|
| 573 |
// Wait for a process to exit |
| 574 |
func (s *service) Wait(ctx context.Context, r *taskAPI.WaitRequest) (*taskAPI.WaitResponse, error) { |
| 575 |
container, err := s.getContainer(r.ID) |
| 576 |
if err != nil { |
| 577 |
return nil, err |
| 578 |
} |
| 579 |
p, err := container.Process(r.ExecID) |
| 580 |
if err != nil { |
| 581 |
return nil, errgrpc.ToGRPC(err) |
| 582 |
} |
| 583 |
p.Wait() |
| 584 |
|
| 585 |
return &taskAPI.WaitResponse{ |
| 586 |
ExitStatus: uint32(p.ExitStatus()), |
| 587 |
ExitedAt: protobuf.ToTimestamp(p.ExitedAt()), |
| 588 |
}, nil |
| 589 |
} |
| 590 |
|
| 591 |
// Connect returns shim information such as the shim's pid |
| 592 |
func (s *service) Connect(ctx context.Context, r *taskAPI.ConnectRequest) (*taskAPI.ConnectResponse, error) { |
| 593 |
var pid int |
| 594 |
if container, err := s.getContainer(r.ID); err == nil { |
| 595 |
pid = container.Pid() |
| 596 |
} |
| 597 |
return &taskAPI.ConnectResponse{ |
| 598 |
ShimPid: uint32(os.Getpid()), |
| 599 |
TaskPid: uint32(pid), |
| 600 |
}, nil |
| 601 |
} |
| 602 |
|
| 603 |
func (s *service) Shutdown(ctx context.Context, r *taskAPI.ShutdownRequest) (*ptypes.Empty, error) { |
| 604 |
s.mu.Lock() |
| 605 |
defer s.mu.Unlock() |
| 606 |
|
| 607 |
// return out if the shim is still servicing containers |
| 608 |
if len(s.containers) > 0 { |
| 609 |
return empty, nil |
| 610 |
} |
| 611 |
|
| 612 |
// please make sure that temporary resource has been cleanup or registered |
| 613 |
// for cleanup before calling shutdown |
| 614 |
s.shutdown.Shutdown() |
| 615 |
|
| 616 |
return empty, nil |
| 617 |
} |
| 618 |
|
| 619 |
func (s *service) Stats(ctx context.Context, r *taskAPI.StatsRequest) (*taskAPI.StatsResponse, error) { |
| 620 |
container, err := s.getContainer(r.ID) |
| 621 |
if err != nil { |
| 622 |
return nil, err |
| 623 |
} |
| 624 |
cgx := container.Cgroup() |
| 625 |
if cgx == nil { |
| 626 |
return nil, errgrpc.ToGRPCf(errdefs.ErrNotFound, "cgroup does not exist") |
| 627 |
} |
| 628 |
var statsx interface{} |
| 629 |
switch cg := cgx.(type) { |
| 630 |
case cgroup1.Cgroup: |
| 631 |
stats, err := cg.Stat(cgroup1.IgnoreNotExist) |
| 632 |
if err != nil { |
| 633 |
return nil, err |
| 634 |
} |
| 635 |
statsx = stats |
| 636 |
case *cgroupsv2.Manager: |
| 637 |
stats, err := cg.Stat() |
| 638 |
if err != nil { |
| 639 |
return nil, err |
| 640 |
} |
| 641 |
statsx = stats |
| 642 |
default: |
| 643 |
return nil, errgrpc.ToGRPCf(errdefs.ErrNotImplemented, "unsupported cgroup type %T", cg) |
| 644 |
} |
| 645 |
data, err := typeurl.MarshalAny(statsx) |
| 646 |
if err != nil { |
| 647 |
return nil, err |
| 648 |
} |
| 649 |
return &taskAPI.StatsResponse{ |
| 650 |
Stats: typeurl.MarshalProto(data), |
| 651 |
}, nil |
| 652 |
} |
| 653 |
|
| 654 |
func (s *service) processExits() { |
| 655 |
for e := range s.ec { |
| 656 |
// While unlikely, it is not impossible for a container process to exit |
| 657 |
// and have its PID be recycled for a new container process before we |
| 658 |
// have a chance to process the first exit. As we have no way to tell |
| 659 |
// for sure which of the processes the exit event corresponds to (until |
| 660 |
// pidfd support is implemented) there is no way for us to handle the |
| 661 |
// exit correctly in that case. |
| 662 |
|
| 663 |
s.lifecycleMu.Lock() |
| 664 |
// Inform any concurrent s.Start() calls so they can handle the exit |
| 665 |
// if the PID belongs to them. |
| 666 |
for subscriber := range s.exitSubscribers { |
| 667 |
(*subscriber)[e.Pid] = append((*subscriber)[e.Pid], e) |
| 668 |
} |
| 669 |
// Handle the exit for a created/started process. If there's more than |
| 670 |
// one, assume they've all exited. One of them will be the correct |
| 671 |
// process. |
| 672 |
var cps []containerProcess |
| 673 |
for _, cp := range s.running[e.Pid] { |
| 674 |
_, init := cp.Process.(*process.Init) |
| 675 |
if init { |
| 676 |
s.containerInitExit[cp.Container] = e |
| 677 |
} |
| 678 |
cps = append(cps, cp) |
| 679 |
} |
| 680 |
delete(s.running, e.Pid) |
| 681 |
s.lifecycleMu.Unlock() |
| 682 |
|
| 683 |
for _, cp := range cps { |
| 684 |
if ip, ok := cp.Process.(*process.Init); ok { |
| 685 |
s.handleInitExit(e, cp.Container, ip) |
| 686 |
} else { |
| 687 |
s.handleProcessExit(e, cp.Container, cp.Process) |
| 688 |
} |
| 689 |
} |
| 690 |
} |
| 691 |
} |
| 692 |
|
| 693 |
func (s *service) send(evt interface{}) { |
| 694 |
s.events <- evt |
| 695 |
} |
| 696 |
|
| 697 |
// handleInitExit processes container init process exits. |
| 698 |
// This is handled separately from non-init exits, because there |
| 699 |
// are some extra invariants we want to ensure in this case, namely: |
| 700 |
// - for a given container, the init process exit MUST be the last exit published |
| 701 |
// This is achieved by: |
| 702 |
// - killing all running container processes (if the container has a shared pid |
| 703 |
// namespace, otherwise all other processes have been reaped already). |
| 704 |
// - waiting for the container's running exec counter to reach 0. |
| 705 |
// - finally, publishing the init exit. |
| 706 |
func (s *service) handleInitExit(e runcC.Exit, c *runc.Container, p *process.Init) { |
| 707 |
// kill all running container processes |
| 708 |
if runc.ShouldKillAllOnExit(s.context, c.Bundle) { |
| 709 |
if err := p.KillAll(s.context); err != nil { |
| 710 |
log.G(s.context).WithError(err).WithField("id", p.ID()). |
| 711 |
Error("failed to kill init's children") |
| 712 |
} |
| 713 |
} |
| 714 |
|
| 715 |
s.lifecycleMu.Lock() |
| 716 |
numRunningExecs := s.runningExecs[c] |
| 717 |
if numRunningExecs == 0 { |
| 718 |
delete(s.runningExecs, c) |
| 719 |
s.lifecycleMu.Unlock() |
| 720 |
s.handleProcessExit(e, c, p) |
| 721 |
return |
| 722 |
} |
| 723 |
|
| 724 |
events := make(chan int, numRunningExecs) |
| 725 |
s.execCountSubscribers[c] = events |
| 726 |
|
| 727 |
s.lifecycleMu.Unlock() |
| 728 |
|
| 729 |
go func() { |
| 730 |
defer func() { |
| 731 |
s.lifecycleMu.Lock() |
| 732 |
defer s.lifecycleMu.Unlock() |
| 733 |
delete(s.execCountSubscribers, c) |
| 734 |
delete(s.runningExecs, c) |
| 735 |
}() |
| 736 |
|
| 737 |
// wait for running processes to exit |
| 738 |
for { |
| 739 |
if runningExecs := <-events; runningExecs == 0 { |
| 740 |
break |
| 741 |
} |
| 742 |
} |
| 743 |
|
| 744 |
// all running processes have exited now, and no new |
| 745 |
// ones can start, so we can publish the init exit |
| 746 |
s.handleProcessExit(e, c, p) |
| 747 |
}() |
| 748 |
} |
| 749 |
|
| 750 |
func (s *service) handleProcessExit(e runcC.Exit, c *runc.Container, p process.Process) { |
| 751 |
p.SetExited(e.Status) |
| 752 |
s.send(&eventstypes.TaskExit{ |
| 753 |
ContainerID: c.ID, |
| 754 |
ID: p.ID(), |
| 755 |
Pid: uint32(e.Pid), |
| 756 |
ExitStatus: uint32(e.Status), |
| 757 |
ExitedAt: protobuf.ToTimestamp(p.ExitedAt()), |
| 758 |
}) |
| 759 |
if _, init := p.(*process.Init); !init { |
| 760 |
s.lifecycleMu.Lock() |
| 761 |
s.runningExecs[c]-- |
| 762 |
if ch, ok := s.execCountSubscribers[c]; ok { |
| 763 |
ch <- s.runningExecs[c] |
| 764 |
} |
| 765 |
s.lifecycleMu.Unlock() |
| 766 |
} |
| 767 |
} |
| 768 |
|
| 769 |
func (s *service) getContainerPids(ctx context.Context, container *runc.Container) ([]uint32, error) { |
| 770 |
p, err := container.Process("") |
| 771 |
if err != nil { |
| 772 |
return nil, errgrpc.ToGRPC(err) |
| 773 |
} |
| 774 |
ps, err := p.(*process.Init).Runtime().Ps(ctx, container.ID) |
| 775 |
if err != nil { |
| 776 |
return nil, err |
| 777 |
} |
| 778 |
pids := make([]uint32, 0, len(ps)) |
| 779 |
for _, pid := range ps { |
| 780 |
pids = append(pids, uint32(pid)) |
| 781 |
} |
| 782 |
return pids, nil |
| 783 |
} |
| 784 |
|
| 785 |
func (s *service) forward(ctx context.Context, publisher shim.Publisher) { |
| 786 |
ns, _ := namespaces.Namespace(ctx) |
| 787 |
ctx = namespaces.WithNamespace(context.Background(), ns) |
| 788 |
for e := range s.events { |
| 789 |
err := publisher.Publish(ctx, runtime.GetTopic(e), e) |
| 790 |
if err != nil { |
| 791 |
log.G(ctx).WithError(err).Error("post event") |
| 792 |
} |
| 793 |
} |
| 794 |
publisher.Close() |
| 795 |
} |
| 796 |
|
| 797 |
func (s *service) getContainer(id string) (*runc.Container, error) { |
| 798 |
s.mu.Lock() |
| 799 |
container := s.containers[id] |
| 800 |
s.mu.Unlock() |
| 801 |
if container == nil { |
| 802 |
return nil, errgrpc.ToGRPCf(errdefs.ErrNotFound, "container not created") |
| 803 |
} |
| 804 |
return container, nil |
| 805 |
} |
| 806 |
|
| 807 |
// initialize a single epoll fd to manage our consoles. `initPlatform` should |
| 808 |
// only be called once. |
| 809 |
func (s *service) initPlatform() error { |
| 810 |
if s.platform != nil { |
| 811 |
return nil |
| 812 |
} |
| 813 |
p, err := runc.NewPlatform() |
| 814 |
if err != nil { |
| 815 |
return err |
| 816 |
} |
| 817 |
s.platform = p |
| 818 |
s.shutdown.RegisterCallback(func(context.Context) error { return s.platform.Close() }) |
| 819 |
return nil |
| 820 |
} |