From 5a7b3c78e06081fb2d44b6f4296cb416ab91aaff Mon Sep 17 00:00:00 2001 From: Zhang Wei Date: Tue, 7 Feb 2017 10:27:40 +0800 Subject: [PATCH] Fix panic of "docker stats --format {{.Name}} --all" This commit fixes panic when execute stats command: * use --format {{.Name}} with --all when there're exited containers. * use --format {{.Name}} while stating exited container. The root cause is when stating an exited container, the result from the api didn't contain the Name and ID field, which will make format process panic. Panic log is like this: ``` panic: runtime error: slice bounds out of range [recovered] panic: runtime error: slice bounds out of range goroutine 1 [running]: panic(0xb20f80, 0xc420014110) /usr/local/go/src/runtime/panic.go:500 +0x1a1 text/template.errRecover(0xc4201773e8) /usr/local/go/src/text/template/exec.go:140 +0x2ad panic(0xb20f80, 0xc420014110) /usr/local/go/src/runtime/panic.go:458 +0x243 github.com/docker/docker/cli/command/formatter.(*containerStatsContext).Name(0xc420430160, 0x0, 0x0) /go/src/github.com/docker/docker/cli/command/formatter/stats.go:148 +0x86 reflect.Value.call(0xb9a3a0, 0xc420430160, 0x2213, 0xbe3657, 0x4, 0x11bc9f8, 0x0, 0x0, 0x4d75b3, 0x1198940, ...) /usr/local/go/src/reflect/value.go:434 +0x5c8 reflect.Value.Call(0xb9a3a0, 0xc420430160, 0x2213, 0x11bc9f8, 0x0, 0x0, 0xc420424028, 0xb, 0xb) /usr/local/go/src/reflect/value.go:302 +0xa4 text/template.(*state).evalCall(0xc420177368, 0xb9a3a0, 0xc420430160, 0x16, 0xb9a3a0, 0xc420430160, 0x2213, 0x1178fa0, 0xc4203ea330, 0xc4203de283, ...) /usr/local/go/src/text/template/exec.go:658 +0x530 ``` Signed-off-by: Zhang Wei --- cli/command/formatter/stats.go | 6 ++++-- cli/command/formatter/stats_test.go | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/cli/command/formatter/stats.go b/cli/command/formatter/stats.go index a37e9d7923..0e31792c4f 100644 --- a/cli/command/formatter/stats.go +++ b/cli/command/formatter/stats.go @@ -149,8 +149,10 @@ func (c *containerStatsContext) Container() string { func (c *containerStatsContext) Name() string { c.AddHeader(nameHeader) - name := c.s.Name[1:] - return name + if len(c.s.Name) > 1 { + return c.s.Name[1:] + } + return "--" } func (c *containerStatsContext) ID() string { diff --git a/cli/command/formatter/stats_test.go b/cli/command/formatter/stats_test.go index d5a17cc70e..f5c6cae0c3 100644 --- a/cli/command/formatter/stats_test.go +++ b/cli/command/formatter/stats_test.go @@ -69,6 +69,12 @@ func TestContainerStatsContextWrite(t *testing.T) { `MEM USAGE / LIMIT 20 B / 20 B -- / -- +`, + }, + { + Context{Format: "{{.Container}} {{.ID}} {{.Name}}"}, + `container1 abcdef foo +container2 -- `, }, { @@ -83,6 +89,8 @@ container2 -- stats := []StatsEntry{ { Container: "container1", + ID: "abcdef", + Name: "/foo", CPUPercentage: 20, Memory: 20, MemoryLimit: 20,