-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
117 lines (99 loc) · 2.17 KB
/
list.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package stack
import (
"fmt"
"io"
"strconv"
"text/tabwriter"
"golang.org/x/net/context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/cli"
"github.com/docker/docker/cli/command"
"github.com/docker/docker/client"
"github.com/spf13/cobra"
)
const (
listItemFmt = "%s\t%s\n"
)
type listOptions struct {
}
func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
opts := listOptions{}
cmd := &cobra.Command{
Use: "ls",
Aliases: []string{"list"},
Short: "List stacks",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runList(dockerCli, opts)
},
}
return cmd
}
func runList(dockerCli *command.DockerCli, opts listOptions) error {
client := dockerCli.Client()
ctx := context.Background()
stacks, err := getStacks(ctx, client)
if err != nil {
return err
}
out := dockerCli.Out()
printTable(out, stacks)
return nil
}
func printTable(out io.Writer, stacks []*stack) {
writer := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
// Ignore flushing errors
defer writer.Flush()
fmt.Fprintf(writer, listItemFmt, "NAME", "SERVICES")
for _, stack := range stacks {
fmt.Fprintf(
writer,
listItemFmt,
stack.Name,
strconv.Itoa(stack.Services),
)
}
}
type stack struct {
// Name is the name of the stack
Name string
// Services is the number of the services
Services int
}
func getStacks(
ctx context.Context,
apiclient client.APIClient,
) ([]*stack, error) {
filter := filters.NewArgs()
filter.Add("label", labelNamespace)
services, err := apiclient.ServiceList(
ctx,
types.ServiceListOptions{Filters: filter})
if err != nil {
return nil, err
}
m := make(map[string]*stack, 0)
for _, service := range services {
labels := service.Spec.Labels
name, ok := labels[labelNamespace]
if !ok {
return nil, fmt.Errorf("cannot get label %s for service %s",
labelNamespace, service.ID)
}
ztack, ok := m[name]
if !ok {
m[name] = &stack{
Name: name,
Services: 1,
}
} else {
ztack.Services++
}
}
var stacks []*stack
for _, stack := range m {
stacks = append(stacks, stack)
}
return stacks, nil
}