Skip to content

Commit

Permalink
add update resource
Browse files Browse the repository at this point in the history
Signed-off-by: ningmingxiao <ning.mingxiao@zte.com.cn>
  • Loading branch information
ningmingxiao committed Jan 14, 2022
1 parent 0ddaffd commit e1d9fd0
Show file tree
Hide file tree
Showing 5 changed files with 289 additions and 1 deletion.
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

✅ Same UI/UX as `docker`

✅ Supports Docker Compose (`nerdctl compose up`)
✅ Supports Docker Compose (`nerdctl compose up`)docker update [

✅ Supports [rootless mode](./docs/rootless.md)

Expand Down Expand Up @@ -234,6 +234,7 @@ It does not necessarily mean that the corresponding features are missing in cont
- [:whale: nerdctl stop](#whale-nerdctl-stop)
- [:whale: nerdctl start](#whale-nerdctl-start)
- [:whale: nerdctl restart](#whale-nerdctl-restart)
- [:whale: nerdctl update](#whale-nerdctl-update)
- [:whale: nerdctl wait](#whale-nerdctl-wait)
- [:whale: nerdctl kill](#whale-nerdctl-kill)
- [:whale: nerdctl pause](#whale-nerdctl-pause)
Expand Down Expand Up @@ -644,6 +645,20 @@ Usage: `nerdctl restart [OPTIONS] CONTAINER [CONTAINER...]`
Flags:
- :whale: `-t, --time=SECONDS`: Seconds to wait for stop before killing it (default "10")

### :whale: nerdctl update
Update configuration of one or more containers.

Usage: `nerctl update [OPTIONS] CONTAINER [CONTAINER...]`

- :whale: `--cpus`: Number of CPUs
- :whale: `--cpu-quota`: Limit the CPU CFS (Completely Fair Scheduler) quota
- :whale: `--cpu-period`: Limit the CPU CFS (Completely Fair Scheduler) period
- :whale: `--cpu-shares`: CPU shares (relative weight)
- :whale: `--cpuset-cpus`: CPUs in which to allow execution (0-3, 0,1)
- :whale: `--cpuset-mems`: Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems
- :whale: `--memory`: Memory limit
- :whale: `--pids-limit`: Tune container pids limit

### :whale: nerdctl wait
Block until one or more containers stop, then print their exit codes.

Expand Down
1 change: 1 addition & 0 deletions cmd/nerdctl/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func newContainerCommand() *cobra.Command {
containerCommand.AddCommand(
newCreateCommand(),
newRunCommand(),
newUpdateCommand(),
newExecCommand(),
containerLsCommand(),
newContainerInspectCommand(),
Expand Down
1 change: 1 addition & 0 deletions cmd/nerdctl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ Config file ($NERDCTL_TOML): %s
newCreateCommand(),
// #region Run & Exec
newRunCommand(),
newUpdateCommand(),
newExecCommand(),
// #endregion

Expand Down
5 changes: 5 additions & 0 deletions cmd/nerdctl/run_cgroup_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ func TestRunCgroupV2(t *testing.T) {
"cat", "cpu.max", "memory.max", "pids.max", "cpu.weight", "cpuset.cpus", "cpuset.mems").AssertOutExactly(expected)
base.Cmd("run", "--rm", "--cpu-quota", "42000", "--cpuset-mems", "0", "--cpu-period", "100000", "--memory", "42m", "--pids-limit", "42", "--cpu-shares", "2000", "--cpuset-cpus", "0-1", "-w", "/sys/fs/cgroup", testutil.AlpineImage,
"cat", "cpu.max", "memory.max", "pids.max", "cpu.weight", "cpuset.cpus", "cpuset.mems").AssertOutExactly(expected)

base.Cmd("run", "--name", testutil.Identifier(t)+"-testUpdate", "-w", "/sys/fs/cgroup", "-d", testutil.AlpineImage, "sleep", "infinity").AssertOK()
base.Cmd("update", "--cpu-quota", "42000", "--cpuset-mems", "0", "--cpu-period", "100000", "--memory", "42m", "--pids-limit", "42", "--cpu-shares", "2000", "--cpuset-cpus", "0-1", "testUpdate").AssertOK()
base.Cmd("exec", "testUpdate", "cat", "cpu.max", "memory.max", "pids.max", "cpu.weight", "cpuset.cpus", "cpuset.mems").AssertOutExactly(expected)
base.Cmd("rm", "-f", testutil.Identifier(t)+"-testUpdate").AssertOK()
}

func TestRunDevice(t *testing.T) {
Expand Down
266 changes: 266 additions & 0 deletions cmd/nerdctl/update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
/*
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 main

import (
"context"
"errors"
"fmt"
"runtime"

"github.com/containerd/containerd"
"github.com/containerd/containerd/containers"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/nerdctl/pkg/formatter"
"github.com/containerd/nerdctl/pkg/idutil/containerwalker"
"github.com/containerd/typeurl"
"github.com/docker/go-units"
runtimespec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/spf13/cobra"
)

type updateRsourceOptions struct {
CpuPeriod uint64
CpuQuota int64
CpuShares uint64
MemoryLimitInBytes int64
CpusetCpus string
CpusetMems string
PidsLimit int64
}

func newUpdateCommand() *cobra.Command {
var updateCommand = &cobra.Command{
Use: "update [flags] CONTAINER [CONTAINER, ...]",
Args: cobra.MinimumNArgs(1),
Short: "Update one or more running containers",
RunE: updateAction,
ValidArgsFunction: updateShellComplete,
SilenceUsage: true,
SilenceErrors: true,
}
updateCommand.Flags().SetInterspersed(false)
setUpdateFlags(updateCommand)
return updateCommand
}

func setUpdateFlags(cmd *cobra.Command) {
cmd.Flags().Float64("cpus", 0.0, "Number of CPUs")
cmd.Flags().Uint64("cpu-period", 0, "Limit CPU CFS (Completely Fair Scheduler) period")
cmd.Flags().Int64("cpu-quota", -1, "Limit CPU CFS (Completely Fair Scheduler) quota")
cmd.Flags().Uint64("cpu-shares", 0, "CPU shares (relative weight)")
cmd.Flags().StringP("memory", "m", "", "Memory limit")
cmd.Flags().String("cpuset-cpus", "", "CPUs in which to allow execution (0-3, 0,1)")
cmd.Flags().String("cpuset-mems", "", "MEMs in which to allow execution (0-3, 0,1)")
cmd.Flags().Int64("pids-limit", -1, "Tune container pids limit (set -1 for unlimited)")
}

func updateAction(cmd *cobra.Command, args []string) error {
client, ctx, cancel, err := newClient(cmd)
if err != nil {
return err
}
defer cancel()
options, err := getUpdateOption(cmd)
if err != nil {
return err
}
walker := &containerwalker.ContainerWalker{
Client: client,
OnFound: func(ctx context.Context, found containerwalker.Found) error {
err = updateContainer(ctx, client, found.Container.ID(), options, cmd)
return err
},
}
for _, req := range args {
n, err := walker.Walk(ctx, req)
if err != nil {
return err
} else if n == 0 {
return fmt.Errorf("no such container %s", req)
} else if n > 1 {
return fmt.Errorf("multiple IDs found with provided prefix: %s", req)
}
}
return nil
}

func getUpdateOption(cmd *cobra.Command) (updateRsourceOptions, error) {
var options updateRsourceOptions
cpus, err := cmd.Flags().GetFloat64("cpus")
if err != nil {
return options, err
}
cpuPeriod, err := cmd.Flags().GetUint64("cpu-period")
if err != nil {
return options, err
}
cpuQuota, err := cmd.Flags().GetInt64("cpu-quota")
if err != nil {
return options, err
}
if cpuQuota != -1 || cpuPeriod != 0 {
if cpus > 0.0 {
return options, errors.New("cpus and quota/period should be used separately")
}
}
if cpus > 0.0 {
cpuPeriod = uint64(100000)
cpuQuota = int64(cpus * 100000.0)
}
shares, err := cmd.Flags().GetUint64("cpu-shares")
if err != nil {
return options, err
}
memStr, err := cmd.Flags().GetString("memory")
if err != nil {
return options, err
}
var mem64 int64
if memStr != "" {
mem64, err = units.RAMInBytes(memStr)
if err != nil {
return options, fmt.Errorf("failed to parse memory bytes %q: %w", memStr, err)
}
}
cpuset, err := cmd.Flags().GetString("cpuset-cpus")
if err != nil {
return options, err
}
cpusetMems, err := cmd.Flags().GetString("cpuset-mems")
if err != nil {
return options, err
}
pidsLimit, err := cmd.Flags().GetInt64("pids-limit")
if err != nil {
return options, err
}
if runtime.GOOS == "linux" {
options = updateRsourceOptions{
CpuPeriod: cpuPeriod,
CpuQuota: cpuQuota,
CpuShares: shares,
CpusetCpus: cpuset,
CpusetMems: cpusetMems,
MemoryLimitInBytes: mem64,
PidsLimit: pidsLimit,
}
}
return options, nil
}

func updateContainer(ctx context.Context, client *containerd.Client, id string, opts updateRsourceOptions, cmd *cobra.Command) error {
container, err := client.LoadContainer(ctx, id)
if err != nil {
return err
}
cStatus := formatter.ContainerStatus(ctx, container)
if cStatus == "pausing" {
return fmt.Errorf("container %q is in pausing state", id)
}
spec, err := container.Spec(ctx)
if err != nil {
return err
}

if runtime.GOOS == "linux" {
if spec.Linux == nil {
spec.Linux = &runtimespec.Linux{}
}
if spec.Linux.Resources == nil {
spec.Linux.Resources = &runtimespec.LinuxResources{}
}
if spec.Linux.Resources.CPU == nil {
spec.Linux.Resources.CPU = &runtimespec.LinuxCPU{}
}
if cmd.Flags().Changed("cpu-shares") {
if spec.Linux.Resources.CPU.Shares != &opts.CpuShares {
spec.Linux.Resources.CPU.Shares = &opts.CpuShares
}
}
if cmd.Flags().Changed("cpu-quota") {
if spec.Linux.Resources.CPU.Quota != &opts.CpuQuota {
spec.Linux.Resources.CPU.Quota = &opts.CpuQuota
}
}
if cmd.Flags().Changed("cpu-period") {
if spec.Linux.Resources.CPU.Period != &opts.CpuPeriod {
spec.Linux.Resources.CPU.Period = &opts.CpuPeriod
}
}
if cmd.Flags().Changed("cpus") {
if spec.Linux.Resources.CPU.Cpus != opts.CpusetCpus {
spec.Linux.Resources.CPU.Cpus = opts.CpusetCpus
}
}
if cmd.Flags().Changed("cpuset-mems") {
if spec.Linux.Resources.CPU.Mems != opts.CpusetMems {
spec.Linux.Resources.CPU.Mems = opts.CpusetMems
}
}

if spec.Linux.Resources.Memory == nil {
spec.Linux.Resources.Memory = &runtimespec.LinuxMemory{}
}
if cmd.Flags().Changed("memory") {
if spec.Linux.Resources.Memory.Limit != &opts.MemoryLimitInBytes {
spec.Linux.Resources.Memory.Limit = &opts.MemoryLimitInBytes
}
}
if spec.Linux.Resources.Pids == nil {
spec.Linux.Resources.Pids = &runtimespec.LinuxPids{}
}
if cmd.Flags().Changed("pids-limit") {
if spec.Linux.Resources.Pids.Limit != opts.PidsLimit {
spec.Linux.Resources.Pids.Limit = opts.PidsLimit
}
}
}

if err := container.Update(ctx, func(ctx context.Context, client *containerd.Client, c *containers.Container) error {
any, err := typeurl.MarshalAny(spec)
if err != nil {
return err
}
c.Spec = any
return nil
}); err != nil {
return err
}

// If container is not running, only update spec is enough, new resource
// limit will be applied when container start.
if cStatus != "up" {
return nil
}
task, err := container.Task(ctx, nil)
if err != nil {
if errdefs.IsNotFound(err) {
// Task exited already.
return nil
}
return fmt.Errorf("failed to get task:%w", err)
}
if err := task.Update(ctx, containerd.WithResources(spec.Linux.Resources)); err != nil {
return err
}
return nil
}

func updateShellComplete(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return shellCompleteContainerNames(cmd, nil)
}

0 comments on commit e1d9fd0

Please sign in to comment.