forked from wangaoone/redeo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
info.go
332 lines (270 loc) · 8.14 KB
/
info.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
package redeo
import (
cryptorand "crypto/rand"
"encoding/hex"
"fmt"
"github.com/cornelk/hashmap"
mathrand "math/rand"
"os"
"sort"
"strconv"
"sync"
"time"
"github.com/wangaoone/redeo/info"
)
// CommandDescription describes supported commands
type CommandDescription struct {
// Name is the command name, returned as a lowercase string.
Name string
// Arity is the command arity specification.
// https://redis.io/commands/command#command-arity.
// It follows a simple pattern:
// positive if command has fixed number of required arguments.
// negative if command has minimum number of required arguments, but may have more.
Arity int64
// Flags is an enumeration of command flags.
// https://redis.io/commands/command#flags.
Flags []string
// FirstKey is the position of first key in argument list.
// https://redis.io/commands/command#first-key-in-argument-list
FirstKey int64
// LastKey is the position of last key in argument list.
// https://redis.io/commands/command#last-key-in-argument-list
LastKey int64
// KeyStepCount is the step count for locating repeating keys.
// https://redis.io/commands/command#step-count
KeyStepCount int64
}
// --------------------------------------------------------------------
// ClientInfo contains client stats
type ClientInfo struct {
client *Client
// ID is the internal client ID
ID uint64
// RemoteAddr is the remote address string
RemoteAddr string
// LastCmd is the last command called by this client
LastCmd string
// CreateTime returns the time at which the client has
// connected to the server
CreateTime time.Time
// AccessTime returns the time of the last access
AccessTime time.Time
}
func newClientInfo(c *Client, now time.Time) *ClientInfo {
return &ClientInfo{
client: c,
ID: c.id,
RemoteAddr: c.RemoteAddr().String(),
CreateTime: now,
AccessTime: now,
}
}
// String generates an info string
func (i *ClientInfo) String() string {
now := time.Now()
return fmt.Sprintf("id=%d addr=%s age=%d idle=%d cmd=%s",
i.ID,
i.RemoteAddr,
now.Sub(i.CreateTime)/time.Second,
now.Sub(i.AccessTime)/time.Second,
i.LastCmd,
)
}
// --------------------------------------------------------------------
// ServerInfo contains server stats
type ServerInfo struct {
registry *info.Registry
startTime time.Time
port string
socket string
pid int
clients *clientReadStats
connections *info.IntValue
commands *info.IntValue
}
// newServerInfo creates a new server info container
func newServerInfo() *ServerInfo {
info := &ServerInfo{
registry: info.New(),
startTime: time.Now(),
connections: info.NewIntValue(0),
commands: info.NewIntValue(0),
// clients: clientStats{stats: make(map[uint64]*ClientInfo)},
clients: &clientReadStats{ stats: &hashmap.HashMap{} },
}
info.initDefaults()
return info
}
// ------------------------------------------------------------------------
// Fetch finds or creates an info section. This method is not thread-safe.
func (i *ServerInfo) Fetch(name string) *info.Section { return i.registry.FetchSection(name) }
// Find finds an info section by name.
func (i *ServerInfo) Find(name string) *info.Section { return i.registry.FindSection(name) }
// String generates an info string
func (i *ServerInfo) String() string { return i.registry.String() }
// NumClients returns the number of connected clients
func (i *ServerInfo) NumClients() int { return i.clients.Len() }
// ClientInfo returns details about connected clients
func (i *ServerInfo) ClientInfo() []*ClientInfo { return i.clients.Stats() }
// Clients returns all connected clients
func (i *ServerInfo) Clients() []*Client { return i.clients.All() }
// Client returns connected clients by id
func (i *ServerInfo) Client(clientID uint64) (*Client, bool) { return i.clients.Client(clientID) }
// TotalConnections returns the total number of connections made since the
// start of the server.
func (i *ServerInfo) TotalConnections() int64 { return i.connections.Value() }
// TotalCommands returns the total number of commands executed since the start
// of the server.
func (i *ServerInfo) TotalCommands() int64 { return i.commands.Value() }
// Apply default info
func (i *ServerInfo) initDefaults() {
runID := make([]byte, 20)
if _, err := cryptorand.Read(runID); err != nil {
_, _ = mathrand.Read(runID)
}
server := i.Fetch("Server")
server.Register("process_id", info.StaticInt(int64(os.Getpid())))
server.Register("run_id", info.StaticString(hex.EncodeToString(runID)))
server.Register("uptime_in_seconds", info.Callback(func() string {
d := time.Since(i.startTime) / time.Second
return strconv.FormatInt(int64(d), 10)
}))
server.Register("uptime_in_days", info.Callback(func() string {
d := time.Since(i.startTime) / time.Hour / 24
return strconv.FormatInt(int64(d), 10)
}))
clients := i.Fetch("Clients")
clients.Register("connected_clients", info.Callback(func() string {
return strconv.Itoa(i.NumClients())
}))
stats := i.Fetch("Stats")
stats.Register("total_connections_received", i.connections)
stats.Register("total_commands_processed", i.commands)
}
func (i *ServerInfo) register(c *Client) {
i.clients.Add(c)
i.connections.Inc(1)
}
func (i *ServerInfo) deregister(clientID uint64) {
i.clients.Del(clientID)
}
func (i *ServerInfo) command(clientID uint64, cmd string) {
i.clients.Cmd(clientID, cmd)
i.commands.Inc(1)
}
// --------------------------------------------------------------------
type clientStats struct {
stats map[uint64]*ClientInfo
mu sync.RWMutex
}
func (s *clientStats) Add(c *Client) {
info := newClientInfo(c, time.Now())
s.mu.Lock()
s.stats[c.id] = info
s.mu.Unlock()
}
func (s *clientStats) Cmd(clientID uint64, cmd string) {
s.mu.Lock()
if info, ok := s.stats[clientID]; ok {
info.AccessTime = time.Now()
info.LastCmd = cmd
}
s.mu.Unlock()
}
func (s *clientStats) Del(clientID uint64) {
s.mu.Lock()
// Release client reference
if info, exist := s.stats[clientID]; exist {
info.client = nil
delete(s.stats, clientID)
}
s.mu.Unlock()
}
func (s *clientStats) Client(clientID uint64) (*Client, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
info, exist := s.stats[clientID]
if exist {
return info.client, exist
} else {
return nil, exist
}
}
func (s *clientStats) Len() int {
s.mu.RLock()
n := len(s.stats)
s.mu.RUnlock()
return n
}
func (s *clientStats) Stats() []*ClientInfo {
s.mu.RLock()
defer s.mu.RUnlock()
res := make(clientInfoSlice, 0, len(s.stats))
for _, info := range s.stats {
i := *info
i.client = nil
res = append(res, &i)
}
sort.Sort(res)
return res
}
func (s *clientStats) All() []*Client {
s.mu.RLock()
defer s.mu.RUnlock()
res := make([]*Client, 0, len(s.stats))
for _, info := range s.stats {
res = append(res, info.client)
}
return res
}
// Client stats optimized for read operation
type clientReadStats struct {
stats *hashmap.HashMap
}
func (s *clientReadStats) Add(c *Client) {
s.stats.Set(c.id, newClientInfo(c, time.Now()))
}
func (s *clientReadStats) Cmd(clientID uint64, cmd string) {
if info, ok := s.stats.Get(clientID); ok {
info.(*ClientInfo).AccessTime = time.Now()
info.(*ClientInfo).LastCmd = cmd
}
}
func (s *clientReadStats) Del(clientID uint64) {
s.stats.Del(clientID)
}
func (s *clientReadStats) Client(clientID uint64) (*Client, bool) {
info, exist := s.stats.Get(clientID)
if exist {
return info.(*ClientInfo).client, exist
} else {
return nil, false
}
}
func (s *clientReadStats) Len() int {
return s.stats.Len()
}
func (s *clientReadStats) Stats() []*ClientInfo {
iter := s.stats.Iter()
res := make(clientInfoSlice, 0, len(iter))
for keyVal := range iter {
info := *keyVal.Value.(*ClientInfo)
info.client = nil
res = append(res, &info)
}
sort.Sort(res)
return res
}
func (s *clientReadStats) All() []*Client {
iter := s.stats.Iter()
res := make([]*Client, 0, len(iter))
for keyVal := range iter {
res = append(res, keyVal.Value.(*ClientInfo).client)
}
return res
}
type clientInfoSlice []*ClientInfo
func (p clientInfoSlice) Len() int { return len(p) }
func (p clientInfoSlice) Less(i, j int) bool { return p[i].ID < p[j].ID }
func (p clientInfoSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }