2020-04-29 19:57:53 +02:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
2020-05-06 09:37:52 +02:00
|
|
|
"context"
|
2020-04-29 19:57:53 +02:00
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"text/tabwriter"
|
|
|
|
|
2020-05-18 12:21:27 +02:00
|
|
|
"github.com/docker/docker/pkg/stringid"
|
2020-04-29 19:57:53 +02:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/spf13/cobra"
|
2020-05-02 18:54:03 +02:00
|
|
|
|
2020-05-15 17:52:19 +02:00
|
|
|
"github.com/docker/api/cli/formatter"
|
2020-05-02 18:54:03 +02:00
|
|
|
"github.com/docker/api/client"
|
2020-04-29 19:57:53 +02:00
|
|
|
)
|
|
|
|
|
2020-05-06 09:37:52 +02:00
|
|
|
type psOpts struct {
|
2020-05-16 12:13:51 +02:00
|
|
|
all bool
|
2020-05-06 09:37:52 +02:00
|
|
|
quiet bool
|
|
|
|
}
|
|
|
|
|
2020-05-04 23:00:21 +02:00
|
|
|
// PsCommand lists containers
|
2020-05-06 09:37:52 +02:00
|
|
|
func PsCommand() *cobra.Command {
|
|
|
|
var opts psOpts
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "ps",
|
|
|
|
Short: "List containers",
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
|
|
return runPs(cmd.Context(), opts)
|
|
|
|
},
|
|
|
|
}
|
2020-04-29 19:57:53 +02:00
|
|
|
|
2020-05-06 09:37:52 +02:00
|
|
|
cmd.Flags().BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs")
|
2020-05-16 12:13:51 +02:00
|
|
|
cmd.Flags().BoolVarP(&opts.quiet, "all", "a", false, "Show all containers (default shows just running)")
|
2020-05-06 09:37:52 +02:00
|
|
|
|
|
|
|
return cmd
|
|
|
|
}
|
|
|
|
|
|
|
|
func runPs(ctx context.Context, opts psOpts) error {
|
|
|
|
c, err := client.New(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "cannot connect to backend")
|
|
|
|
}
|
|
|
|
|
2020-05-16 12:13:51 +02:00
|
|
|
containers, err := c.ContainerService().List(ctx, opts.all)
|
2020-05-06 09:37:52 +02:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "fetch containers")
|
|
|
|
}
|
2020-04-29 19:57:53 +02:00
|
|
|
|
2020-05-06 09:37:52 +02:00
|
|
|
if opts.quiet {
|
2020-04-29 19:57:53 +02:00
|
|
|
for _, c := range containers {
|
2020-05-06 09:37:52 +02:00
|
|
|
fmt.Println(c.ID)
|
2020-04-29 19:57:53 +02:00
|
|
|
}
|
2020-05-06 09:37:52 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-05-15 17:52:19 +02:00
|
|
|
w := tabwriter.NewWriter(os.Stdout, 0, 0, 8, ' ', 0)
|
|
|
|
fmt.Fprintf(w, "CONTAINER ID\tIMAGE\tCOMMAND\tSTATUS\tPORTS\n")
|
|
|
|
format := "%s\t%s\t%s\t%s\t%s\n"
|
2020-05-06 09:37:52 +02:00
|
|
|
for _, c := range containers {
|
2020-05-15 17:52:19 +02:00
|
|
|
fmt.Fprintf(w, format, stringid.TruncateID(c.ID), c.Image, c.Command, c.Status, formatter.PortsString(c.Ports))
|
2020-05-06 09:37:52 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return w.Flush()
|
2020-04-29 19:57:53 +02:00
|
|
|
}
|