-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
operator_usage.go
324 lines (263 loc) · 7.69 KB
/
operator_usage.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package command
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/hashicorp/vault/api"
"github.com/mitchellh/cli"
"github.com/posener/complete"
"github.com/ryanuber/columnize"
)
var (
_ cli.Command = (*OperatorUsageCommand)(nil)
_ cli.CommandAutocomplete = (*OperatorUsageCommand)(nil)
)
type OperatorUsageCommand struct {
*BaseCommand
flagStartTime time.Time
flagEndTime time.Time
}
func (c *OperatorUsageCommand) Synopsis() string {
return "Lists historical client counts"
}
func (c *OperatorUsageCommand) Help() string {
helpText := `
Usage: vault operator usage
List the client counts for the default reporting period.
$ vault operator usage
List the client counts for a specific time period.
$ vault operator usage -start-time=2020-10 -end-time=2020-11
` + c.Flags().Help()
return strings.TrimSpace(helpText)
}
func (c *OperatorUsageCommand) Flags() *FlagSets {
set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
f.TimeVar(&TimeVar{
Name: "start-time",
Usage: "Start of report period. Defaults to 'default_reporting_period' before end time.",
Target: &c.flagStartTime,
Completion: complete.PredictNothing,
Default: time.Time{},
Formats: TimeVar_TimeOrDay | TimeVar_Month,
})
f.TimeVar(&TimeVar{
Name: "end-time",
Usage: "End of report period. Defaults to end of last month.",
Target: &c.flagEndTime,
Completion: complete.PredictNothing,
Default: time.Time{},
Formats: TimeVar_TimeOrDay | TimeVar_Month,
})
return set
}
func (c *OperatorUsageCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *OperatorUsageCommand) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *OperatorUsageCommand) Run(args []string) int {
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
data := make(map[string][]string)
if !c.flagStartTime.IsZero() {
data["start_time"] = []string{c.flagStartTime.Format(time.RFC3339)}
}
if !c.flagEndTime.IsZero() {
data["end_time"] = []string{c.flagEndTime.Format(time.RFC3339)}
}
client, err := c.Client()
if err != nil {
c.UI.Error(err.Error())
return 2
}
resp, err := client.Logical().ReadWithData("sys/internal/counters/activity", data)
if err != nil {
c.UI.Error(fmt.Sprintf("Error retrieving client counts: %v", err))
return 2
}
if resp == nil || resp.Data == nil {
if c.noReportAvailable(client) {
c.UI.Warn("Vault does not have any usage data available. A report will be available\n" +
"after the first calendar month in which monitoring is enabled.")
} else {
c.UI.Warn("No data is available for the given time range.")
}
// No further output
return 0
}
switch Format(c.UI) {
case "table":
default:
// Handle JSON, YAML, etc.
return OutputData(c.UI, resp)
}
// Show this before the headers
c.outputTimestamps(resp.Data)
out := []string{
"Namespace path | Distinct entities | Non-Entity tokens | Active clients",
}
out = append(out, c.namespacesOutput(resp.Data)...)
out = append(out, c.totalOutput(resp.Data)...)
colConfig := columnize.DefaultConfig()
colConfig.Empty = " " // Do not show n/a on intentional blank lines
colConfig.Glue = " "
c.UI.Output(tableOutput(out, colConfig))
return 0
}
// noReportAvailable checks whether we can definitively say that no
// queries can be answered; if there's an error, just fall back to
// reporting that the response is empty.
func (c *OperatorUsageCommand) noReportAvailable(client *api.Client) bool {
if c.flagOutputCurlString {
// Don't mess up the original query string
return false
}
resp, err := client.Logical().Read("sys/internal/counters/config")
if err != nil || resp == nil || resp.Data == nil {
c.UI.Warn("bad response from config")
return false
}
qaRaw, ok := resp.Data["queries_available"]
if !ok {
c.UI.Warn("no queries_available key")
return false
}
qa, ok := qaRaw.(bool)
if !ok {
c.UI.Warn("wrong type")
return false
}
return !qa
}
func (c *OperatorUsageCommand) outputTimestamps(data map[string]interface{}) {
c.UI.Output(fmt.Sprintf("Period start: %v\nPeriod end: %v\n",
data["start_time"].(string),
data["end_time"].(string)))
}
type UsageCommandNamespace struct {
formattedLine string
sortOrder string
// Sort order:
// -- root first
// -- namespaces in lexicographic order
// -- deleted namespace "xxxxx" last
}
type UsageResponse struct {
namespacePath string
entityCount int64
// As per 1.9, the tokenCount field will contain the distinct non-entity
// token clients instead of each individual token.
tokenCount int64
clientCount int64
}
func jsonNumberOK(m map[string]interface{}, key string) (int64, bool) {
val, ok := m[key].(json.Number)
if !ok {
return 0, false
}
intVal, err := val.Int64()
if err != nil {
return 0, false
}
return intVal, true
}
// TODO: provide a function in the API module for doing this conversion?
func (c *OperatorUsageCommand) parseNamespaceCount(rawVal interface{}) (UsageResponse, error) {
var ret UsageResponse
val, ok := rawVal.(map[string]interface{})
if !ok {
return ret, errors.New("value is not a map")
}
ret.namespacePath, ok = val["namespace_path"].(string)
if !ok {
return ret, errors.New("bad namespace path")
}
counts, ok := val["counts"].(map[string]interface{})
if !ok {
return ret, errors.New("missing counts")
}
ret.entityCount, ok = jsonNumberOK(counts, "distinct_entities")
if !ok {
return ret, errors.New("missing distinct_entities")
}
ret.tokenCount, ok = jsonNumberOK(counts, "non_entity_tokens")
if !ok {
return ret, errors.New("missing non_entity_tokens")
}
ret.clientCount, ok = jsonNumberOK(counts, "clients")
if !ok {
return ret, errors.New("missing clients")
}
return ret, nil
}
func (c *OperatorUsageCommand) namespacesOutput(data map[string]interface{}) []string {
byNs, ok := data["by_namespace"].([]interface{})
if !ok {
c.UI.Error("missing namespace breakdown in response")
return nil
}
nsOut := make([]UsageCommandNamespace, 0, len(byNs))
for _, rawVal := range byNs {
val, err := c.parseNamespaceCount(rawVal)
if err != nil {
c.UI.Error(fmt.Sprintf("malformed namespace in response: %v", err))
continue
}
sortOrder := "1" + val.namespacePath
if val.namespacePath == "" {
val.namespacePath = "[root]"
sortOrder = "0"
} else if strings.HasPrefix(val.namespacePath, "deleted namespace") {
sortOrder = "2" + val.namespacePath
}
formattedLine := fmt.Sprintf("%s | %d | %d | %d",
val.namespacePath, val.entityCount, val.tokenCount, val.clientCount)
nsOut = append(nsOut, UsageCommandNamespace{
formattedLine: formattedLine,
sortOrder: sortOrder,
})
}
sort.Slice(nsOut, func(i, j int) bool {
return nsOut[i].sortOrder < nsOut[j].sortOrder
})
out := make([]string, len(nsOut))
for i := range nsOut {
out[i] = nsOut[i].formattedLine
}
return out
}
func (c *OperatorUsageCommand) totalOutput(data map[string]interface{}) []string {
// blank line separating it from namespaces
out := []string{" | | | "}
total, ok := data["total"].(map[string]interface{})
if !ok {
c.UI.Error("missing total in response")
return out
}
entityCount, ok := jsonNumberOK(total, "distinct_entities")
if !ok {
c.UI.Error("missing distinct_entities in total")
return out
}
tokenCount, ok := jsonNumberOK(total, "non_entity_tokens")
if !ok {
c.UI.Error("missing non_entity_tokens in total")
return out
}
clientCount, ok := jsonNumberOK(total, "clients")
if !ok {
c.UI.Error("missing clients in total")
return out
}
out = append(out, fmt.Sprintf("Total | %d | %d | %d",
entityCount, tokenCount, clientCount))
return out
}