Skip to content

Commit fec1fa4

Browse files
authored
Merge pull request #5310 from cvas22/feat/compose-stats
compose: add stats command
2 parents 5ca0bab + e347eda commit fec1fa4

4 files changed

Lines changed: 248 additions & 1 deletion

File tree

‎cmd/nerdctl/compose/compose.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ func Command() *cobra.Command {
6464
pauseCommand(),
6565
unpauseCommand(),
6666
topCommand(),
67+
statsCommand(),
6768
createCommand(),
6869
waitCommand(),
6970
scaleCommand(),
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/*
2+
Copyright The containerd Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package compose
18+
19+
import (
20+
"github.com/spf13/cobra"
21+
22+
containerd "github.com/containerd/containerd/v2/client"
23+
24+
"github.com/containerd/nerdctl/v2/cmd/nerdctl/helpers"
25+
"github.com/containerd/nerdctl/v2/pkg/api/types"
26+
"github.com/containerd/nerdctl/v2/pkg/clientutil"
27+
"github.com/containerd/nerdctl/v2/pkg/cmd/compose"
28+
"github.com/containerd/nerdctl/v2/pkg/cmd/container"
29+
"github.com/containerd/nerdctl/v2/pkg/composer"
30+
"github.com/containerd/nerdctl/v2/pkg/containerutil"
31+
)
32+
33+
func statsCommand() *cobra.Command {
34+
var cmd = &cobra.Command{
35+
Use: "stats [flags] [SERVICE...]",
36+
Short: "Display a live stream of resource usage statistics of service containers",
37+
RunE: statsAction,
38+
SilenceUsage: true,
39+
SilenceErrors: true,
40+
DisableFlagsInUseLine: true,
41+
}
42+
cmd.Flags().BoolP("all", "a", false, "Show all containers (default shows just running)")
43+
cmd.Flags().String("format", "", "Pretty-print stats using a Go template, e.g, '{{json .}}'")
44+
cmd.Flags().Bool("no-stream", false, "Disable streaming stats and only pull the first result")
45+
cmd.Flags().Bool("no-trunc", false, "Do not truncate output")
46+
return cmd
47+
}
48+
49+
func statsAction(cmd *cobra.Command, args []string) error {
50+
globalOptions, err := helpers.ProcessRootCmdFlags(cmd)
51+
if err != nil {
52+
return err
53+
}
54+
all, err := cmd.Flags().GetBool("all")
55+
if err != nil {
56+
return err
57+
}
58+
format, err := cmd.Flags().GetString("format")
59+
if err != nil {
60+
return err
61+
}
62+
noStream, err := cmd.Flags().GetBool("no-stream")
63+
if err != nil {
64+
return err
65+
}
66+
noTrunc, err := cmd.Flags().GetBool("no-trunc")
67+
if err != nil {
68+
return err
69+
}
70+
71+
client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), globalOptions.Namespace, globalOptions.Address)
72+
if err != nil {
73+
return err
74+
}
75+
defer cancel()
76+
options, err := getComposeOptions(cmd, globalOptions.DebugFull, globalOptions.Experimental)
77+
if err != nil {
78+
return err
79+
}
80+
c, err := compose.New(client, globalOptions, options, cmd.OutOrStdout(), cmd.ErrOrStderr())
81+
if err != nil {
82+
return err
83+
}
84+
serviceNames, err := c.ServiceNames(args...)
85+
if err != nil {
86+
return err
87+
}
88+
containers, err := c.Containers(ctx, serviceNames...)
89+
if err != nil {
90+
return err
91+
}
92+
93+
var containerIDs []string
94+
for _, c := range containers {
95+
if !all {
96+
cStatus, err := containerutil.ContainerStatus(ctx, c)
97+
if err != nil {
98+
return err
99+
}
100+
if cStatus.Status != containerd.Running {
101+
continue
102+
}
103+
}
104+
containerIDs = append(containerIDs, c.ID())
105+
}
106+
// container.Stats shows every container on the host when it gets no IDs,
107+
// so stop here when the project has no matching containers.
108+
if len(containerIDs) == 0 {
109+
return nil
110+
}
111+
112+
// Like compose logs, release the compose lock before streaming. Stats don't need it, and holding
113+
// it until the command exits would block every other compose command in the meantime.
114+
if err := composer.Unlock(); err != nil {
115+
return err
116+
}
117+
118+
return container.Stats(ctx, client, containerIDs, types.ContainerStatsOptions{
119+
Stdout: cmd.OutOrStdout(),
120+
Stderr: cmd.ErrOrStderr(),
121+
GOptions: globalOptions,
122+
All: all,
123+
Format: format,
124+
NoStream: noStream,
125+
NoTrunc: noTrunc,
126+
})
127+
}
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/*
2+
Copyright The containerd Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package compose
18+
19+
import (
20+
"fmt"
21+
"testing"
22+
23+
"github.com/containerd/nerdctl/mod/tigron/expect"
24+
"github.com/containerd/nerdctl/mod/tigron/require"
25+
"github.com/containerd/nerdctl/mod/tigron/test"
26+
27+
"github.com/containerd/nerdctl/v2/pkg/testutil"
28+
"github.com/containerd/nerdctl/v2/pkg/testutil/nerdtest"
29+
)
30+
31+
func TestComposeStats(t *testing.T) {
32+
var dockerComposeYAML = fmt.Sprintf(`
33+
services:
34+
svc0:
35+
image: %s
36+
command: "sleep infinity"
37+
svc1:
38+
image: %s
39+
command: "sleep infinity"
40+
`, testutil.CommonImage, testutil.CommonImage)
41+
42+
testCase := nerdtest.Setup()
43+
44+
testCase.Require = require.All(nerdtest.CgroupsAccessible)
45+
46+
testCase.Setup = func(data test.Data, helpers test.Helpers) {
47+
data.Temp().Save(dockerComposeYAML, "compose.yaml")
48+
data.Labels().Set("yamlPath", data.Temp().Path("compose.yaml"))
49+
data.Labels().Set("project", data.Identifier())
50+
helpers.Ensure("compose", "-f", data.Temp().Path("compose.yaml"), "-p", data.Identifier(), "up", "-d")
51+
}
52+
53+
testCase.Cleanup = func(data test.Data, helpers test.Helpers) {
54+
helpers.Anyhow("compose", "-f", data.Temp().Path("compose.yaml"), "-p", data.Identifier(), "down")
55+
}
56+
57+
compose := func(data test.Data, helpers test.Helpers, args ...string) test.TestableCommand {
58+
return helpers.Command(append([]string{"compose", "-f", data.Labels().Get("yamlPath"), "-p", data.Labels().Get("project")}, args...)...)
59+
}
60+
61+
testCase.SubTests = []*test.Case{
62+
{
63+
Description: "all services",
64+
NoParallel: true,
65+
Command: func(data test.Data, helpers test.Helpers) test.TestableCommand {
66+
return compose(data, helpers, "stats", "--no-stream", "--no-trunc", "--format", "{{.Name}}")
67+
},
68+
Expected: func(data test.Data, helpers test.Helpers) *test.Expected {
69+
return &test.Expected{
70+
Output: expect.All(
71+
expect.Contains(data.Labels().Get("project")+"-svc0-1"),
72+
expect.Contains(data.Labels().Get("project")+"-svc1-1"),
73+
),
74+
}
75+
},
76+
},
77+
{
78+
Description: "one service",
79+
NoParallel: true,
80+
Command: func(data test.Data, helpers test.Helpers) test.TestableCommand {
81+
return compose(data, helpers, "stats", "--no-stream", "--no-trunc", "--format", "{{.Name}}", "svc0")
82+
},
83+
Expected: func(data test.Data, helpers test.Helpers) *test.Expected {
84+
return &test.Expected{
85+
Output: expect.All(
86+
expect.Contains(data.Labels().Get("project")+"-svc0-1"),
87+
expect.DoesNotContain(data.Labels().Get("project")+"-svc1-1"),
88+
),
89+
}
90+
},
91+
},
92+
{
93+
Description: "stopped service is skipped",
94+
NoParallel: true,
95+
Setup: func(data test.Data, helpers test.Helpers) {
96+
helpers.Ensure("compose", "-f", data.Labels().Get("yamlPath"), "-p", data.Labels().Get("project"), "stop", "svc1")
97+
},
98+
Command: func(data test.Data, helpers test.Helpers) test.TestableCommand {
99+
return compose(data, helpers, "stats", "--no-stream", "--no-trunc", "--format", "{{.Name}}", "svc1")
100+
},
101+
Expected: test.Expects(0, nil, expect.Equals("")),
102+
},
103+
}
104+
105+
testCase.Run(t)
106+
}

‎docs/command-reference.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@
130130
- [:whale: nerdctl compose restart](#whale-nerdctl-compose-restart)
131131
- [:whale: nerdctl compose rm](#whale-nerdctl-compose-rm)
132132
- [:whale: nerdctl compose run](#whale-nerdctl-compose-run)
133+
- [:whale: nerdctl compose stats](#whale-nerdctl-compose-stats)
133134
- [:whale: nerdctl compose top](#whale-nerdctl-compose-top)
134135
- [:whale: nerdctl compose ls](#whale-nerdctl-compose-ls)
135136
- [:whale: nerdctl compose version](#whale-nerdctl-compose-version)
@@ -2013,6 +2014,19 @@ Unimplemented `docker-compose run` (V1) flags: `--use-aliases`, `--no-TTY`
20132014

20142015
Unimplemented `docker compose run` (V2) flags: `--use-aliases`, `--no-TTY`, `--tty`
20152016

2017+
### :whale: nerdctl compose stats
2018+
2019+
Display a live stream of resource usage statistics of service containers
2020+
2021+
Usage: `nerdctl compose stats [OPTIONS] [SERVICE...]`
2022+
2023+
Flags:
2024+
2025+
- :whale: `-a, --all`: Show all containers (default shows just running)
2026+
- :whale: `--format`: Pretty-print stats using a Go template, e.g, `{{json .}}`
2027+
- :whale: `--no-stream`: Disable streaming stats and only pull the first result
2028+
- :whale: `--no-trunc`: Do not truncate output
2029+
20162030
### :whale: nerdctl compose top
20172031

20182032
Display the running processes of service containers
@@ -2130,7 +2144,6 @@ Compose:
21302144

21312145
- `docker compose attach`
21322146
- `docker compose events`
2133-
- `docker compose stats`
21342147
- `docker compose watch`
21352148

21362149
Builder:

0 commit comments

Comments
 (0)