-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathredisinfo.go
344 lines (316 loc) · 12.4 KB
/
redisinfo.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package redisinfo
import (
"fmt"
"reflect"
"sort"
"strconv"
"strings"
)
// Parse returns an Info struct from the provided content string
func Parse(content string) (Info, error) {
info := &Info{}
err := info.fromString(content)
if err != nil {
return Info{}, err
}
return *info, nil
}
// Info describes the INFO data returned by Redis
type Info struct {
Server Server `json:"server"`
Clients Client `json:"clients"`
Memory Memory `json:"memory"`
Persistence Persistence `json:"persistence"`
Stats Stats `json:"stats"`
Replication Replication `json:"replication"`
CPU CPU `json:"cpu"`
Cluster Cluster `json:"cluster"`
Keyspace []Keyspace `json:"keyspace"`
}
type category interface {
fromString(string) error
}
func (i *Info) fromString(content string) error {
content = strings.Replace(content, "\r", "", -1) // remove all \r that are in the file
lines := strings.Split(content, "\n")
contentPerCategory := make(map[string][]string, 0)
currentCategory := ""
for _, line := range lines {
if line == "" {
continue
} else if strings.HasPrefix(line, "# ") {
currentCategory = strings.ToLower(line[2:])
contentPerCategory[currentCategory] = make([]string, 0)
} else {
contentPerCategory[currentCategory] = append(contentPerCategory[currentCategory], line)
}
}
val := reflect.ValueOf(i).Elem()
for idx := 0; idx < val.NumField(); idx++ {
field := val.Type().Field(idx)
if categoryName := field.Tag.Get("json"); categoryName != "-" && categoryName != "" {
if contentPerCategory[categoryName] == nil || len(contentPerCategory[categoryName]) == 0 {
// empty category
continue
}
fieldVal := val.Field(idx)
fieldValue := reflect.New(fieldVal.Type())
if categoryValue, ok := fieldValue.Interface().(category); ok {
if err := categoryValue.fromString(strings.Join(contentPerCategory[categoryName], "\n")); err != nil {
return fmt.Errorf("cannot parse category %s: %w", categoryName, err)
}
valueToSet := reflect.Indirect(reflect.ValueOf(categoryValue))
if !fieldVal.CanSet() {
return fmt.Errorf("cannot set value for field %s", categoryName)
}
fieldVal.Set(valueToSet)
} else if fieldVal.Kind() == reflect.Slice {
parsed, err := sep(strings.Join(contentPerCategory[categoryName], "\n"), "\n", ":")
if err != nil {
return err
}
if err := parseSlice(parsed, fieldVal, "db"); err != nil {
return err
}
} else {
return fmt.Errorf("cannot parse kind %s for field %s", fieldVal.Kind(), categoryName)
}
}
}
return nil
}
type Server struct {
RedisVersion string `json:"redis_version"`
RedisGitSha1 string `json:"redis_git_sha1"`
RedisGitDirty bool `json:"redis_git_dirty"`
RedisBuildID string `json:"redis_build_id"`
RedisMode string `json:"redis_mode"`
OS string `json:"os"`
ArchBits uint8 `json:"arch_bits"`
MultiplexingAPI string `json:"multiplexing_api"`
GCCVersion string `json:"gcc_version"`
ProcessID uint16 `json:"process_id"`
RunID string `json:"run_id"`
TCPPort uint16 `json:"tcp_port"`
UptimeInSeconds uint64 `json:"uptime_in_seconds"`
UptimeInDays uint64 `json:"uptime_in_days"`
HZ uint64 `json:"hz"`
LRUClock int64 `json:"lru_clock"`
Executable string `json:"executable"`
ConfigFile string `json:"config_file"`
}
func (s *Server) fromString(content string) error { return parseStruct(s, content) }
type Client struct {
ConnectedClients int64 `json:"connected_clients"`
ClientLongestOutputList int64 `json:"client_longest_output_list"`
ClientBiggestInputBuf int64 `json:"client_biggest_input_buf"`
BlockedClients int64 `json:"blocked_clients"`
}
func (s *Client) fromString(content string) error { return parseStruct(s, content) }
type Memory struct {
UsedMemory int64 `json:"used_memory"`
UsedMemoryHuman string `json:"used_memory_human"`
UsedMemoryRss int64 `json:"used_memory_rss"`
UsedMemoryRssHuman string `json:"used_memory_rss_human"`
UsedMemoryPeak int64 `json:"used_memory_peak"`
UsedMemoryPeakHuman string `json:"used_memory_peak_human"`
TotalSystemMemory int64 `json:"total_system_memory"`
TotalSystemMemoryHuman string `json:"total_system_memory_human"`
UsedMemoryLua int64 `json:"used_memory_lua"`
UsedMemoryLuaHuman string `json:"used_memory_lua_human"`
Maxmemory int64 `json:"maxmemory"`
MaxmemoryHuman string `json:"maxmemory_human"`
MaxmemoryPolicy string `json:"maxmemory_policy"`
MemFragmentationRatio float64 `json:"mem_fragmentation_ratio"`
MemAllocator string `json:"mem_allocator"`
}
func (s *Memory) fromString(content string) error { return parseStruct(s, content) }
type Persistence struct {
Loading bool `json:"loading"`
RdbChangesSinceLastSave int64 `json:"rdb_changes_since_last_save"`
RdbBgsaveInProgress bool `json:"rdb_bgsave_in_progress"`
RdbLastSaveTime int64 `json:"rdb_last_save_time"`
RdbLastBgsaveStatus string `json:"rdb_last_bgsave_status"`
RdbLastBgsaveTimeSec int64 `json:"rdb_last_bgsave_time_sec"`
RdbCurrentBgsaveTimeSec int64 `json:"rdb_current_bgsave_time_sec"`
AofEnabled bool `json:"aof_enabled"`
AofRewriteInProgress bool `json:"aof_rewrite_in_progress"`
AofRewriteScheduled bool `json:"aof_rewrite_scheduled"`
AofLastRewriteTimeSec int64 `json:"aof_last_rewrite_time_sec"`
AofCurrentRewriteTimeSec int64 `json:"aof_current_rewrite_time_sec"`
AofLastBgrewriteStatus string `json:"aof_last_bgrewrite_status"`
AofLastWriteStatus string `json:"aof_last_write_status"`
}
func (s *Persistence) fromString(content string) error { return parseStruct(s, content) }
type Stats struct {
TotalConnectionsReceived int64 `json:"total_connections_received"`
TotalCommandsProcessed int64 `json:"total_commands_processed"`
InstantaneousOpsPerSec int64 `json:"instantaneous_ops_per_sec"`
TotalNetInputBytes int64 `json:"total_net_input_bytes"`
TotalNetOutputBytes int64 `json:"total_net_output_bytes"`
InstantaneousInputKbps float64 `json:"instantaneous_input_kbps"`
InstantaneousOutputKbps float64 `json:"instantaneous_output_kbps"`
RejectedConnections int64 `json:"rejected_connections"`
SyncFull int64 `json:"sync_full"`
SyncPartialOk int64 `json:"sync_partial_ok"`
SyncPartialErr int64 `json:"sync_partial_err"`
ExpiredKeys int64 `json:"expired_keys"`
EvictedKeys int64 `json:"evicted_keys"`
KeyspaceHits int64 `json:"keyspace_hits"`
KeyspaceMisses int64 `json:"keyspace_misses"`
PubsubChannels int64 `json:"pubsub_channels"`
PubsubPatterns int64 `json:"pubsub_patterns"`
LatestForkUsec int64 `json:"latest_fork_usec"`
MigrateCachedSockets bool `json:"migrate_cached_sockets"`
}
func (s *Stats) fromString(content string) error { return parseStruct(s, content) }
type Replication struct {
Role string `json:"role"`
ConnectedSlaves uint64 `json:"connected_slaves"`
Slaves []ReplicationSlave `json:"slave"`
MasterReplOffset int64 `json:"master_repl_offset"`
ReplBacklogActive bool `json:"repl_backlog_active"`
ReplBacklogSize uint64 `json:"repl_backlog_size"`
ReplBacklogFirstByteOffset uint64 `json:"repl_backlog_first_byte_offset"`
ReplBacklogHistLen uint64 `json:"repl_backlog_histlen"`
}
type ReplicationSlave struct {
ID int64 `json:"id,omitempty" index:"true"`
IP string `json:"ip"`
Port uint16 `json:"port"`
State string `json:"state"`
Offset int64 `json:"offset"`
Lag int64 `json:"lag"`
}
func (rs *ReplicationSlave) fromString(content string) error { return parseStruct(rs, content) }
func (s *Replication) fromString(content string) error { return parseStruct(s, content) }
type CPU struct {
UsedCPUSys float64 `json:"used_cpu_sys"`
UsedCPUUser float64 `json:"used_cpu_user"`
UsedCPUSysChildren float64 `json:"used_cpu_sys_children"`
UsedCPUUserChildren float64 `json:"used_cpu_user_children"`
}
func (s *CPU) fromString(content string) error { return parseStruct(s, content) }
type Cluster struct {
ClusterEnabled bool `json:"cluster_enabled"`
}
func (s *Cluster) fromString(content string) error { return parseStruct(s, content) }
type Keyspace struct {
DB int64 `json:"db,omitempty" index:"true"`
Keys uint64 `json:"keys"`
Expires uint64 `json:"expires"`
AvgTTL uint64 `json:"avg_ttl"`
}
func (s *Keyspace) fromString(content string) error { return parseStruct(s, content) }
func sep(content string, lineSep string, keySep string) (map[string]string, error) {
parsed := map[string]string{}
lines := strings.Split(content, lineSep)
for nbr, line := range lines {
lineContent := strings.Split(line, keySep)
if len(lineContent) != 2 {
return nil, fmt.Errorf("invalid line %d: '%s'", nbr, line)
}
parsed[lineContent[0]] = lineContent[1]
}
return parsed, nil
}
func parseStruct(c category, content string) error {
parsed, err := sep(content, "\n", ":")
if err != nil {
return err
}
val := reflect.ValueOf(c).Elem()
for idx := 0; idx < val.NumField(); idx++ {
field := val.Type().Field(idx)
if jsonTag := field.Tag.Get("json"); jsonTag != "-" && jsonTag != "" {
splitJSONTag := strings.Split(jsonTag, ",")
fieldName := splitJSONTag[0]
stringVal := parsed[fieldName]
if len(splitJSONTag) == 2 && splitJSONTag[1] == "omitempty" && stringVal == "" {
continue
}
fieldVal := val.Field(idx)
switch field.Type.Kind() {
case reflect.String:
fieldVal.Set(reflect.ValueOf(stringVal))
case reflect.Bool:
fieldVal.Set(reflect.ValueOf(stringVal == "1"))
case reflect.Uint8:
val, err := strconv.ParseUint(stringVal, 10, 8)
if err != nil {
return fmt.Errorf("cannot parse uint8 for %s: %w", fieldName, err)
}
fieldVal.Set(reflect.ValueOf(uint8(val)))
case reflect.Uint16:
val, err := strconv.ParseUint(stringVal, 10, 16)
if err != nil {
return fmt.Errorf("cannot parse uint16 for %s: %w", fieldName, err)
}
fieldVal.Set(reflect.ValueOf(uint16(val)))
case reflect.Uint64:
val, err := strconv.ParseUint(stringVal, 10, 64)
if err != nil {
return fmt.Errorf("cannot parse uint64 for %s: %w", fieldName, err)
}
fieldVal.Set(reflect.ValueOf(uint64(val)))
case reflect.Int64:
val, err := strconv.ParseInt(stringVal, 10, 64)
if err != nil {
return fmt.Errorf("cannot parse int64 for %s: %w", fieldName, err)
}
fieldVal.Set(reflect.ValueOf(int64(val)))
case reflect.Float64:
val, err := strconv.ParseFloat(stringVal, 64)
if err != nil {
return fmt.Errorf("cannot parse float64 for %s: %w", fieldName, err)
}
fieldVal.Set(reflect.ValueOf(val))
case reflect.Slice:
if err := parseSlice(parsed, fieldVal, fieldName); err != nil {
return err
}
default:
return fmt.Errorf("unhandled type %s for %s", field.Type.Kind(), fieldName)
}
}
}
return nil
}
func parseSlice(dict map[string]string, fieldVal reflect.Value, prefix string) error {
toUse := make([]int64, 0)
for fieldName := range dict {
if strings.HasPrefix(fieldName, prefix) {
index, err := strconv.ParseInt(fieldName[len(prefix):], 10, 64)
if err != nil {
return fmt.Errorf("cannot parse index from field name %s: %w", fieldName, err)
}
toUse = append(toUse, index)
}
}
sort.SliceStable(toUse, func(i, j int) bool { return toUse[i] < toUse[j] })
slice := reflect.MakeSlice(fieldVal.Type(), 0, 0)
for _, fieldIndex := range toUse {
fieldName := fmt.Sprintf("%s%d", prefix, fieldIndex)
parsed, err := sep(dict[fieldName], ",", "=")
if err != nil {
return err
}
content := make([]string, 0)
for key, value := range parsed {
content = append(content, fmt.Sprintf("%s:%s", key, value))
}
v := reflect.New(fieldVal.Type().Elem())
if err := v.Interface().(category).fromString(strings.Join(content, "\n")); err != nil {
return err
}
for idx := 0; idx < v.Elem().NumField(); idx++ {
field := v.Elem().Type().Field(idx)
if field.Tag.Get("index") == "true" {
v.Elem().Field(idx).SetInt(fieldIndex)
}
}
slice = reflect.Append(slice, reflect.Indirect(v))
}
fieldVal.Set(slice)
return nil
}