From bca62476525b2f22e2506b98da4c0b4d9676da58 Mon Sep 17 00:00:00 2001 From: Yong Tang Date: Tue, 1 Nov 2016 10:12:29 -0700 Subject: [PATCH] Add `--cpus` flag to control cpu resources This fix tries to address the proposal raised in 27921 and add `--cpus` flag for `docker run/create`. Basically, `--cpus` will allow user to specify a number (possibly partial) about how many CPUs the container will use. For example, on a 2-CPU system `--cpus 1.5` means the container will take 75% (1.5/2) of the CPU share. This fix adds a `NanoCPUs` field to `HostConfig` since swarmkit alreay have a concept of NanoCPUs for tasks. The `--cpus` flag will translate the number into reused `NanoCPUs` to be consistent. This fix adds integration tests to cover the changes. Related docs (`docker run` and Remote APIs) have been updated. This fix fixes 27921. Signed-off-by: Yong Tang Upstream-commit: 17e9503bbb5922279692f4d5f8bcb942f7657455 Component: cli --- components/cli/opts/opts.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/components/cli/opts/opts.go b/components/cli/opts/opts.go index f8bb3ba745..e452943ffc 100644 --- a/components/cli/opts/opts.go +++ b/components/cli/opts/opts.go @@ -2,6 +2,7 @@ package opts import ( "fmt" + "math/big" "net" "regexp" "strings" @@ -319,3 +320,35 @@ func (o *FilterOpt) Type() string { func (o *FilterOpt) Value() filters.Args { return o.filter } + +// NanoCPUs is a type for fixed point fractional number. +type NanoCPUs int64 + +// String returns the string format of the number +func (c *NanoCPUs) String() string { + return big.NewRat(c.Value(), 1e9).FloatString(3) +} + +// Set sets the value of the NanoCPU by passing a string +func (c *NanoCPUs) Set(value string) error { + cpu, ok := new(big.Rat).SetString(value) + if !ok { + return fmt.Errorf("Failed to parse %v as a rational number", value) + } + nano := cpu.Mul(cpu, big.NewRat(1e9, 1)) + if !nano.IsInt() { + return fmt.Errorf("value is too precise") + } + *c = NanoCPUs(nano.Num().Int64()) + return nil +} + +// Type returns the type +func (c *NanoCPUs) Type() string { + return "NanoCPUs" +} + +// Value returns the value in int64 +func (c *NanoCPUs) Value() int64 { + return int64(*c) +}