forked from rancher/cli
/
host.go
119 lines (105 loc) · 2.67 KB
/
host.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
118
119
package cmd
import (
"bytes"
"strings"
"github.com/rancher/go-rancher/v2"
"github.com/urfave/cli"
)
func HostCommand() cli.Command {
hostLsFlags := []cli.Flag{
listAllFlag(),
cli.BoolFlag{
Name: "quiet,q",
Usage: "Only display IDs",
},
cli.StringFlag{
Name: "format",
Usage: "'json' or Custom format: {{.Id}} {{.Name}}",
},
}
return cli.Command{
Name: "hosts",
ShortName: "host",
Usage: "Operations on hosts",
Action: defaultAction(hostLs),
Flags: hostLsFlags,
Subcommands: []cli.Command{
cli.Command{
Name: "ls",
Usage: "List hosts",
Description: "\nLists all hosts in the current $RANCHER_ENVIRONMENT. Use `--env <envID>` or `--env <envName>` to select a different environment.\n\nExample:\n\t$ rancher hosts ls\n\t$ rancher --env 1a5 hosts ls\n",
ArgsUsage: "None",
Action: hostLs,
Flags: hostLsFlags,
},
cli.Command{
Name: "create",
Usage: "Create a host",
Description: "\nCreates a host in the $RANCHER_ENVIRONMENT. Use `--env <envID>` or `--env <envName>` to select a different environment.\n\nExample:\n\t$ rancher --env k8slab host create newHostName\n",
ArgsUsage: "[NEWHOSTNAME...]",
SkipFlagParsing: true,
Action: hostCreate,
},
},
}
}
type HostsData struct {
ID string
Host client.Host
State string
ContainerCount int
Labels string
}
func getHostState(host *client.Host) string {
state := host.State
if state == "active" && host.AgentState != "" {
state = host.AgentState
}
return state
}
func getLabels(host *client.Host) string {
var buffer bytes.Buffer
it := 0
for key, value := range host.Labels {
if strings.HasPrefix(key, "io.rancher") {
continue
} else if it > 0 {
buffer.WriteString(",")
}
buffer.WriteString(key)
buffer.WriteString("=")
buffer.WriteString(value.(string))
it++
}
return buffer.String()
}
func hostLs(ctx *cli.Context) error {
c, err := GetClient(ctx)
if err != nil {
return err
}
collection, err := c.Host.List(defaultListOpts(ctx))
if err != nil {
return err
}
writer := NewTableWriter([][]string{
{"ID", "Host.Id"},
{"HOSTNAME", "Host.Hostname"},
{"STATE", "State"},
{"CONTAINERS", "ContainerCount"},
{"IP", "Host.AgentIpAddress"},
{"LABELS", "Labels"},
{"DETAIL", "Host.TransitioningMessage"},
}, ctx)
defer writer.Close()
for _, item := range collection.Data {
writer.Write(&HostsData{
ID: item.Id,
Host: item,
State: getHostState(&item),
ContainerCount: len(item.InstanceIds),
Labels: getLabels(&item),
})
}
return writer.Err()
}