-
Notifications
You must be signed in to change notification settings - Fork 93
/
server_list_command.go
289 lines (244 loc) · 7.23 KB
/
server_list_command.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright 2020 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"regexp"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/dustin/go-humanize"
"github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats.go"
"github.com/xlab/tablewriter"
"gopkg.in/alecthomas/kingpin.v2"
)
type SrvLsCmd struct {
expect uint32
json bool
filter string
sort string
reverse bool
compact bool
}
type srvListCluster struct {
name string
nodes []string
gwOut int
gwIn int
conns int
}
func configureServerListCommand(srv *kingpin.CmdClause) {
c := &SrvLsCmd{}
ls := srv.Command("list", "List known servers").Alias("ls").Action(c.list)
ls.Arg("expect", "How many servers to expect").Uint32Var(&c.expect)
ls.Flag("json", "Produce JSON output").Short('j').BoolVar(&c.json)
ls.Flag("filter", "Regular expression filter on server name").Short('f').StringVar(&c.filter)
ls.Flag("sort", "Sort servers by a specific key (conns,subs,routes,gws,mem,cpu,slow,uptime,rtt").Default("rtt").EnumVar(&c.sort, strings.Split("conns,conn,subs,sub,routes,route,gw,mem,cpu,slow,uptime,rtt", ",")...)
ls.Flag("reverse", "Reverse sort servers").Short('R').Default("false").BoolVar(&c.reverse)
ls.Flag("compact", "Compact server names").Default("true").BoolVar(&c.compact)
}
func (c *SrvLsCmd) list(_ *kingpin.ParseContext) error {
nc, err := newNatsConn("", natsOpts()...)
if err != nil {
return err
}
defer nc.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
seen := uint32(0)
mu := sync.Mutex{}
type result struct {
*server.ServerStatsMsg
rtt time.Duration
}
filter, err := regexp.Compile(c.filter)
if err != nil {
return err
}
var (
results []*result
names []string
clusters = make(map[string]*srvListCluster)
servers = 0
connections = 0
memory int64 = 0
slow int64 = 0
subs uint32 = 0
js = 0
start = time.Now()
)
sub, err := nc.Subscribe(nc.NewRespInbox(), func(msg *nats.Msg) {
if msg.Header != nil && msg.Header.Get("Status") != "" {
fmt.Printf("%s status from $SYS.REQ.SERVER.PING, ensure a system account is used with appropriate permissions\n", msg.Header.Get("Status"))
os.Exit(1)
}
ssm := &server.ServerStatsMsg{}
err = json.Unmarshal(msg.Data, ssm)
if err != nil {
log.Printf("Could not decode response: %s", err)
os.Exit(1)
}
mu.Lock()
defer mu.Unlock()
last := atomic.AddUint32(&seen, 1)
if !filter.MatchString(ssm.Server.Name) {
return
}
servers++
connections += ssm.Stats.Connections
memory += ssm.Stats.Mem
slow += ssm.Stats.SlowConsumers
subs += ssm.Stats.NumSubs
if ssm.Server.JetStream {
js++
}
cluster := ssm.Server.Cluster
if cluster != "" {
_, ok := clusters[cluster]
if !ok {
clusters[cluster] = &srvListCluster{cluster, []string{}, 0, 0, 0}
}
clusters[cluster].conns += ssm.Stats.Connections
clusters[cluster].nodes = append(clusters[cluster].nodes, ssm.Server.Name)
clusters[cluster].gwOut += len(ssm.Stats.Gateways)
for _, g := range ssm.Stats.Gateways {
clusters[cluster].gwIn += g.NumInbound
}
}
results = append(results, &result{
ServerStatsMsg: ssm,
rtt: time.Since(start),
})
if last == c.expect {
cancel()
}
})
if err != nil {
return err
}
err = nc.PublishRequest("$SYS.REQ.SERVER.PING", sub.Subject, nil)
if err != nil {
return err
}
nc.Flush()
ic := make(chan os.Signal, 1)
signal.Notify(ic, os.Interrupt)
select {
case <-ic:
cancel()
case <-ctx.Done():
}
sub.Drain()
if len(results) == 0 {
return fmt.Errorf("no results received, ensure the account used has system privileges and appropriate permissions")
}
if c.json {
printJSON(results)
return nil
}
// we reverse sort by default now, setting reverse=true means
// do not reverse, so this function seems really weird but its right
rev := func(v bool) bool {
if !c.reverse {
return !v
}
return v
}
sort.Slice(results, func(i int, j int) bool {
stati := results[i].Stats
statj := results[j].Stats
switch c.sort {
case "conns", "conn":
return rev(stati.Connections < statj.Connections)
case "subs", "sub":
return rev(stati.NumSubs < statj.NumSubs)
case "routes", "route":
return rev(len(stati.Routes) < len(statj.Routes))
case "gws", "gw":
return rev(len(stati.Gateways) < len(statj.Gateways))
case "mem":
return rev(stati.Mem < statj.Mem)
case "cpu":
return rev(stati.CPU < statj.CPU)
case "slow":
return rev(stati.SlowConsumers < statj.SlowConsumers)
case "uptime":
return rev(stati.Start.UnixNano() > statj.Start.UnixNano())
default:
return rev(results[i].rtt < results[j].rtt)
}
})
table := tablewriter.CreateTable()
table.AddTitle("Server Overview")
table.AddHeaders("Name", "Cluster", "IP", "Version", "JS", "Conns", "Subs", "Routes", "GWs", "Mem", "CPU", "Slow", "Uptime", "RTT")
// here so its after the sort
for _, ssm := range results {
names = append(names, ssm.Server.Name)
}
cNames := names
if c.compact {
cNames = compactStrings(names)
}
for i, ssm := range results {
jsEnabled := "no"
if ssm.Server.JetStream {
jsEnabled = "yes"
}
table.AddRow(cNames[i], ssm.Server.Cluster, ssm.Server.Host, ssm.Server.Version, jsEnabled, ssm.Stats.Connections, ssm.Stats.NumSubs, len(ssm.Stats.Routes), len(ssm.Stats.Gateways), humanize.IBytes(uint64(ssm.Stats.Mem)), fmt.Sprintf("%.1f", ssm.Stats.CPU), ssm.Stats.SlowConsumers, humanizeTime(ssm.Stats.Start), ssm.rtt)
}
table.AddSeparator()
table.AddRow("", fmt.Sprintf("%d Clusters", len(clusters)), fmt.Sprintf("%d Servers", servers), "", js, connections, subs, "", "", humanize.IBytes(uint64(memory)), "", slow, "", "")
fmt.Print(table.Render())
if c.expect != 0 && c.expect != seen {
fmt.Printf("\nMissing %d server(s)\n", c.expect-atomic.LoadUint32(&seen))
}
if len(clusters) > 0 {
c.showClusters(clusters)
}
return nil
}
func (c *SrvLsCmd) showClusters(cl map[string]*srvListCluster) {
fmt.Println()
table := tablewriter.CreateTable()
table.AddTitle("Cluster Overview")
table.AddHeaders("Cluster", "Node Count", "Outgoing Gateways", "Incoming Gateways", "Connections")
var clusters []*srvListCluster
for c := range cl {
clusters = append(clusters, cl[c])
}
sort.Slice(clusters, func(i, j int) bool {
return len(clusters[i].nodes) > len(clusters[j].nodes)
})
in := 0
out := 0
nodes := 0
conns := 0
for _, c := range clusters {
in += c.gwIn
out += c.gwOut
nodes += len(c.nodes)
conns += c.conns
table.AddRow(c.name, len(c.nodes), c.gwOut, c.gwIn, c.conns)
}
table.AddSeparator()
table.AddRow("", nodes, out, in, conns)
fmt.Print(table.Render())
}