/
stats.go
754 lines (573 loc) · 26.2 KB
/
stats.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
package memcachey
import (
"bufio"
"bytes"
"fmt"
"net"
"reflect"
"strconv"
"strings"
"time"
)
// Statistics contains general-purpose statistics about a Memcached server.
type Statistics struct {
// ProcessID is the process id of the server process
ProcessID uint32 `proto:"pid"`
// Uptime is the time since the server started
Uptime time.Duration `proto:"uptime"`
// Time is the current UNIX time according to the server
Time uint64 `proto:"time"`
// Version is the version string reported by the server
Version string `proto:"version"`
// PointerSize on the host OS, generally either 32 or 64.
PointerSize uint32 `proto:"pointer_size"`
// CurrentItems is the current number of items stored
CurrentItems uint64 `proto:"curr_items"`
// TotalItems is the total number of items stored since the server started
TotalItems uint64 `proto:"total_items"`
// Bytes is the current number of bytes used to store items
Bytes uint64 `proto:"bytes"`
// Max number of simultaneous connections
MaxConnections uint32 `proto:"max_connections"`
// Total number of connections opened since the server started running
TotalConnections uint32 `proto:"total_connections"`
// CurrentConenctions is the current number of open connections
CurrentConnnections uint32 `proto:"curr_connections"`
// RejectedConnections is the connections rejected in maxconns_fast mode
RejectedConnections uint64 `proto:"rejected_connections"`
// ConnectionStructures is the number of connection structures allocated by the server
ConnectionStructures uint32 `proto:"connection_structures"`
// Number of misc fds used internally
ReservedFileDescriptors uint32 `proto:"reserved_fds"`
// Cumulative number of retrieval reqs
TotalGetCommands uint64 `proto:"cmd_get"`
// Cumulative number of storage reqs
TotalSetCommands uint64 `proto:"cmd_set"`
// Cumulative number of flush reqs
TotalFlushCommands uint64 `proto:"cmd_flush"`
// Cumulative number of touch reqs
TotalTotalCommands uint64 `proto:"cmd_touch"`
// Number of keys that have been requested and found present
GetHits uint64 `proto:"get_hits"`
// Number of items that have been requested and not found
GetMisses uint64 `proto:"get_misses"`
// Number of items that have been requested but had already expired
GetExpired uint64 `proto:"get_expired"`
// Number of items that have been requested but have been flushed via flush_all
GetFlushed uint64 `proto:"get_flushed"`
// Number of deletion reqs resulting in an item being removed
DeleteHits uint64 `proto:"delete_hits"`
// Number of deletions reqs for missing keys
DeleteMisses uint64 `proto:"delete_misses"`
// Number of incr reqs against missing keys
IncrementMisses uint64 `proto:"incr_misses"`
// Number of successful incr reqs
IncrementHits uint64 `proto:"incr_hits"`
// Number of decr reqs against missing keys
DecrementMisses uint64 `proto:"decr_misses"`
// Number of successful decr reqs
DecrementHits uint64 `proto:"decr_hits"`
// Number of CAS reqs against missing keys
CheckAndSetMisses uint64 `proto:"cas_misses"`
// Number of successful CAS reqs
CheckAndSetHits uint64 `proto:"cas_hits"`
// Number of CAS reqs for which a key was found, but the CAS value did not match
CheckAndSetBadValue uint64 `proto:"cas_badval"`
// Number of keys that have been touched with a new expiration time
TouchHits uint64 `proto:"touch_hits"`
// Number of items that have been touched and not found
TouchMisses uint64 `proto:"touch_misses"`
// Number of authentication commands handled, success or failure
AuthenticationCommands uint64 `proto:"auth_cmds"`
// Number of failed authentications
AuthenticationErrors uint64 `proto:"auth_errors"`
}
/*
| idle_kicks | 64u | Number of connections closed due to |
| | | reaching their idle timeout. |
| evictions | 64u | Number of valid items removed from cache |
| | | to free memory for new items |
| reclaimed | 64u | Number of times an entry was stored using |
| | | memory from an expired entry |
| bytes_read | 64u | Total number of bytes read by this server |
| | | from network |
| bytes_written | 64u | Total number of bytes sent by this server |
| | | to network |
| limit_maxbytes | size_t | Number of bytes this server is allowed to |
| | | use for storage. |
| accepting_conns | bool | Whether or not server is accepting conns |
| listen_disabled_num | 64u | Number of times server has stopped |
| | | accepting new connections (maxconns). |
| time_in_listen_disabled_us |
| | 64u | Number of microseconds in maxconns. |
| threads | 32u | Number of worker threads requested. |
| | | (see doc/threads.txt) |
| conn_yields | 64u | Number of times any connection yielded to |
| | | another due to hitting the -R limit. |
| hash_power_level | 32u | Current size multiplier for hash table |
| hash_bytes | 64u | Bytes currently used by hash tables |
| hash_is_expanding | bool | Indicates if the hash table is being |
| | | grown to a new size |
| expired_unfetched | 64u | Items pulled from LRU that were never |
| | | touched by get/incr/append/etc before |
| | | expiring |
| evicted_unfetched | 64u | Items evicted from LRU that were never |
| | | touched by get/incr/append/etc. |
| evicted_active | 64u | Items evicted from LRU that had been hit |
| | | recently but did not jump to top of LRU |
| slab_reassign_running | bool | If a slab page is being moved |
| slabs_moved | 64u | Total slab pages moved |
| crawler_reclaimed | 64u | Total items freed by LRU Crawler |
| crawler_items_checked | 64u | Total items examined by LRU Crawler |
| lrutail_reflocked | 64u | Times LRU tail was found with active ref. |
| | | Items can be evicted to avoid OOM errors. |
| moves_to_cold | 64u | Items moved from HOT/WARM to COLD LRU's |
| moves_to_warm | 64u | Items moved from COLD to WARM LRU |
| moves_within_lru | 64u | Items reshuffled within HOT or WARM LRU's |
| direct_reclaims | 64u | Times worker threads had to directly |
| | | reclaim or evict items. |
| lru_crawler_starts | 64u | Times an LRU crawler was started |
| lru_maintainer_juggles |
| | 64u | Number of times the LRU bg thread woke up |
| slab_global_page_pool | 32u | Slab pages returned to global pool for |
| | | reassignment to other slab classes. |
| slab_reassign_rescues | 64u | Items rescued from eviction in page move |
| slab_reassign_evictions_nomem |
| | 64u | Valid items evicted during a page move |
| | | (due to no free memory in slab) |
| slab_reassign_chunk_rescues |
| | 64u | Individual sections of an item rescued |
| | | during a page move. |
| slab_reassign_inline_reclaim |
| | 64u | Internal stat counter for when the page |
| | | mover clears memory from the chunk |
| | | freelist when it wasn't expecting to. |
| slab_reassign_busy_items |
| | 64u | Items busy during page move, requiring a |
| | | retry before page can be moved. |
| slab_reassign_busy_deletes |
| | 64u | Items busy during page move, requiring |
| | | deletion before page can be moved. |
| log_worker_dropped | 64u | Logs a worker never wrote due to full buf |
| log_worker_written | 64u | Logs written by a worker, to be picked up |
| log_watcher_skipped | 64u | Logs not sent to slow watchers. |
| log_watcher_sent | 64u | Logs written to watchers. |
| rusage_user | 32u.32u | Accumulated user time for this process |
| | | (seconds:microseconds) |
| rusage_system | 32u.32u | Accumulated system time for this process |
| | | (seconds:microseconds) |
*/
// StatisticsForAddress returns general-purpose statistics about the specified host.
func (c *Client) StatisticsForAddress(address string) (*Statistics, error) {
connection, err := c.cp.ForAddress(address)
if err != nil {
return nil, err
}
defer connection.Close()
if _, err := fmt.Fprint(connection, "stats\r\n"); err != nil {
return nil, err
}
settings := &Statistics{}
if err := parseSettingsResponse(connection, func(prefix string) interface{} {
return settings
}); err != nil {
return nil, err
}
return settings, nil
}
// SettingsStatistics contains details of the settings of the running memcached
type SettingsStatistics struct {
// MaxBytes represents the maximum number of bytes allowed in the cache.
MaxBytes uint64 `proto:"maxbytes"`
// MaxConnections is the maximum number of clients allowed
MaxConnections uint32 `proto:"maxconns"`
// TCPPort is the TCP port to listen on.
TCPPort uint32 `proto:"tcpport"`
// TCPPort is the UDP port to listen on.
UDPPort uint32 `proto:"udpport"`
// The Interface to listen on.
Interface string `proto:"inter"`
// Verbosity level
Verbosity uint32 `proto:"verbosity"`
// Oldest is the age of the oldest honored object
Oldest time.Duration `proto:"oldest"`
// When off, LRU evictions are disabled
LRUEvictionsEnabled bool `proto:"evictions"`
// Path to the domain socket (if any).
DomainSocket string `proto:"domain_socket"`
// umask for the creation of the domain socket
Umask uint32 `proto:"umask"`
// Chunk size growth factor
ChunkSizeGrowthFactor float64 `proto:"growth_factor"`
// Minimum space allocated for key+value+flags
InitialChunkSize uint32 `proto:"chunk_size"`
// Number of threads (including dispatch)
NumberOfThreads uint32 `proto:"num_threads"`
// Stats prefix separator character
StatsPrefixSeperatorCharacter string `proto:"stat_key_prefix"`
// If yes, stats detail is enabled
StatisticsDetailEnabled bool `proto:"detail_enabled"`
// Max num IO ops processed within an event
RequestsPerEvent uint32 `proto:"reqs_per_event"`
// When no, CAS is not enabled for this server
CheckAndSetEnabled bool `proto:"cas_enabled"`
// TCP listen
TCPBacklog uint32 `proto:"tcp_backlog"`
// SASL auth requested and enabled
SASLAuthenticationEnabled bool `proto:"auth_enabled_sasl"`
// maximum item size
MaximumItemSize uint32 `proto:"item_size_max"`
// If fast disconnects are enabled
FastMaximumConnectionsEnabled bool `proto:"maxconns_fast"`
// Starting size multiplier for hash table
InitialHashPower uint32 `proto:"hashpower_init"`
// SlabReassignAllowed represents whether slab page reassignment is allowed
SlabReassignAllowed bool `proto:"slab_reassign"`
// SlabAutomoverMode represents the current mode.
SlabAutomoverMode SlabsAutomoveMode `proto:"slab_automove"`
// SlabAutomoverRatio is the ratio limit between young/old slab classes
SlabAutomoverRatio float64 `proto:"slab_automove_ratio"`
// SlabAutomoverWindow is an internal algo tunable for automove
SlabAutomoverWindow uint32 `proto:"slab_automove_window"`
// MaximumSlabChunkSize is the maximum slab class size (avoid unless necessary)
MaximumSlabChunkSize uint32 `proto:"slab_chunk_max"`
// HashAlgorithm is the hash algorithm used for the hash table.
HashAlgorithm string `proto:"hash_algorithm"`
// LRUCrawlerEnabled represents whether the background thread running the LRU crawler is running.
LRUCrawlerEnabled bool `proto:"lru_crawler"`
// Microseconds to sleep between LRU crawls
LRUCrawlerSleep uint32 `proto:"lru_crawler_sleep"`
// Max items to crawl per slab per run
LRUCrawlerMaximumItems uint32 `proto:"lru_crawler_tocrawl"`
// Split LRU mode and background threads
LRUMaintainerThread bool `proto:"lru_maintainer_thread"`
// Pct of slab memory reserved for HOT LRU
HotLRUPct uint32 `proto:"hot_lru_pct"`
// Pct of slab memory reserved for WARM LRU
WarmLRUPct uint32 `proto:"warm_lru_pct"`
// Set idle age of HOT LRU to COLD age * this
MaximumHotFactor float64 `proto:"hot_max_factor"`
// Set idle age of WARM LRU to COLD age * this
MaximumWarmFactor float64 `proto:"warm_max_factor"`
// If yes, items < temporary_ttl use TEMP_LRU
TemporaryLRUEnabled bool `proto:"temp_lru"`
// Items with TTL < this are marked temporary
TemporaryTTL uint32 `proto:"temporary_ttl"`
// Drop connections that are idle this many seconds (0 disables)
ConnectionMaximumIdleTime time.Duration `proto:"idle_time"`
// Size of internal (not socket) write buffer per active watcher connected.
WatcherWriteBufferSize uint32 `proto:"watcher_logbuf_size"`
// Size of internal per-worker-thread buffer which the background thread reads from.
WorkerWriteBufferSize uint32 `proto:"worker_logbuf_size"`
// If yes, a "stats sizes" histogram is being dynamically tracked.
TrackingSizesEnabled bool `proto:"track_sizes"`
// If yes, and available, drop unused syscalls (see seccomp on Linux, pledge on OpenBSD)
DropPriviliges bool `proto:"drop_privileges"`
}
// SettingsStatisticsForAddress returns details of the settings of the running memcached.
// This is primarily made up of the results of processing commandline options.
func (c *Client) SettingsStatisticsForAddress(address string) (*SettingsStatistics, error) {
connection, err := c.cp.ForAddress(address)
if err != nil {
return nil, err
}
defer connection.Close()
if _, err := fmt.Fprint(connection, "stats settings\r\n"); err != nil {
return nil, err
}
settings := &SettingsStatistics{}
if err := parseSettingsResponse(connection, func(prefix string) interface{} {
return settings
}); err != nil {
return nil, err
}
return settings, nil
}
// ConnectionStatistics contains information about a specific connection.
type ConnectionStatistics struct {
// Address is the the address of the remote side. For listening
// sockets this is the listen address. Note that some socket types
// (such as UNIX-domain) don't have meaningful remote addresses.
Address string `proto:"addr"`
// The address of the server. This field is absent for listening sockets.
ListenAddress string `proto:"listen_addr"`
// The current state of the connection.
State string `proto:"state"`
// The number of seconds since the most recently issued command on the connection.
// This measures the time since the start of the command, so if "state" indicates a
// command is currently executing, this will be the number of seconds the current
// command has been running.
TimeSinceLastCommand time.Duration `proto:"secs_since_last_cmd"`
}
// ConnectionStatisticsForAddress returns per-connection statistics.
func (c *Client) ConnectionStatisticsForAddress(address string) (map[string]*ConnectionStatistics, error) {
connection, err := c.cp.ForAddress(address)
if err != nil {
return nil, err
}
defer connection.Close()
if _, err := fmt.Fprint(connection, "stats conns\r\n"); err != nil {
return nil, err
}
statistics := map[string]*ConnectionStatistics{}
// STAT <file descriptor>:<stat> <value>\r\n
if err := parseSettingsResponse(connection, func(prefix string) interface{} {
if stats, ok := statistics[prefix]; ok {
return stats
}
stats := &ConnectionStatistics{}
statistics[prefix] = stats
return stats
}); err != nil {
return nil, err
}
return statistics, nil
}
// ItemStatistics contains information about item storage per slab class.
type ItemStatistics struct {
// Number of items presently stored in this class. Expired items are not excluded.
Number uint64 `proto:"number"`
//Number of times an entry was stored using memory from an expired entry.
ReclaimedTimes uint64 `proto:"reclaimed"`
// NumberOfHotItems is the number of items presently stored in the HOT LRU.
NumberOfHotItems uint64 `proto:"number_hot"`
// NumberOfWarmItems is the number of items presently stored in the WARM LRU.
NumberOfWarmItems uint64 `proto:"number_warm"`
// NumberOfColdItems is the number of items presently stored in the COLD LRU.
NumberOfColdItems uint64 `proto:"number_cold"`
// NumberOfTemporaryItems is the number of items presently stored in the TEMPORARY LRU.
NumberOfTemporaryItems uint64 `proto:"number_temp"`
// OldestHotItem is the age of the oldest item in the hot lru.
OldestHotItem time.Duration `proto:"age_hot"`
// OldestWarmItem is the age of the oldest item in the warm lru.
OldestWarmItem time.Duration `proto:"age_warm"`
// OldestItem is the age of the oldest item in the lru.
OldestItem time.Duration `proto:"age"`
// Number of bytes requested to be stored in this LRU[*]
MemoryRequested uint64 `proto:"mem_requested"`
// Number of times an item had to be evicted from the LRU before it expired.
EvictedItems uint64 `proto:"evicted"`
// Number of times an item which had an explicit expire time set had
// to be evicted from the LRU before it expired.
EvictedItemsWithExpireTime uint64 `proto:"evicted_nonzero"`
// Seconds since the last access for the most recent item
// evicted from this class. Use this to judge how
// recently active your evicted data is.
EvictedTime time.Duration `proto:"evicted_time"`
// Number of times the underlying slab class was unable to
// store a new item. This means you are running with -M or
// an eviction failed.
ItemsDeniedDueToOutOfMemory uint64 `proto:"outofmemory"`
// Number of times we self-healed a slab with a refcount
// leak. If this counter is increasing a lot, please
// report your situation to the developers.
TailRepairs uint64 `proto:"tailrepairs"`
// Number of expired items reclaimed from the LRU which
// were never touched after being set.
ExpiredUnfetchedItems uint64 `proto:"expired_unfetched"`
// Number of valid items evicted from the LRU which were
// never touched after being set.
EvictedUnfetchedItems uint64 `proto:"evicted_unfetched"`
// Number of valid items evicted from the LRU which were
// recently touched but were evicted before being moved to
// the top of the LRU again.
EvictedActiveItems uint64 `proto:"evicted_active"`
// Number of items freed by the LRU Crawler.
CrawlerReclaimedItems uint64 `proto:"crawler_reclaimed"`
// Number of items found to be refcount locked in the LRU tail.
LRUTailReflockedItems uint64 `proto:"lrutail_reflocked"`
// Number of items moved from HOT or WARM into COLD.
ItemsMovedToCold uint64 `proto:"moves_to_cold"`
// Number of items moved from COLD to WARM.
ItemsMovedToWarm uint64 `proto:"moves_to_warm"`
// Number of times active items were bumped within HOT or WARM.
ItemsMovedWithinLRU uint64 `proto:"moves_within_lru"`
// Number of times worker threads had to directly pull LRU
// tails to find memory for a new item.
DirectReclaims uint64 `proto:"direct_reclaims"`
HotHits uint64 `proto:"hits_to_hot"`
WarmHits uint64 `proto:"hits_to_warm"`
ColdHits uint64 `proto:"hits_to_cold"`
// Number of get_hits to each sub-LRU.
TemporaryHits uint64 `proto:"hits_to_temp"`
}
// ItemStatisticsForAddress returns information about item storage per slab class.
func (c *Client) ItemStatisticsForAddress(address string) (map[string]*ItemStatistics, error) {
connection, err := c.cp.ForAddress(address)
if err != nil {
return nil, err
}
defer connection.Close()
if _, err := fmt.Fprint(connection, "stats items\r\n"); err != nil {
return nil, err
}
statistics := map[string]*ItemStatistics{}
// STAT items:<slabclass>:<stat> <value>\r\n
if err := parseSettingsResponse(connection, func(prefix string) interface{} {
prefix = prefix[6:]
if stats, ok := statistics[prefix]; ok {
return stats
}
stats := &ItemStatistics{}
statistics[prefix] = stats
return stats
}); err != nil {
return nil, err
}
return statistics, nil
}
// PerSlabStatistics contains about statistics about a single slab.
type PerSlabStatistics struct {
// The amount of space each chunk uses. One item will use one
// chunk of the appropriate size
ChunkSize uint64 `proto:"chunk_size"`
// How many chunks exist within one page. A page by default
// is less than or equal to one megabyte in size
ChunksPerPage uint64 `proto:"chunks_per_page"`
// Total number of pages allocated to the slab class
TotalPages uint64 `proto:"total_pages"`
// Total number of chunks allocated to the slab class
TotalChunks uint64 `proto:"total_chunks"`
// Total number of get requests serviced by this class
GetHits uint64 `proto:"get_hits"`
// Total number of set requests storing data in this class
SetCommands uint64 `proto:"cmd_set"`
// Total number of successful deletes from this class
DeleteHits uint64 `proto:"delete_hits"`
// Total number of incrs modifying this class
IncrementHits uint64 `proto:"incr_hits"`
// Total number of decrs modifying this class
DecrementHits uint64 `proto:"decr_hits"`
// Total number of CAS commands modifying this class
CheckAndSetHits uint64 `proto:"cas_hits"`
// Total number of CAS commands that failed to modify a value due to a bad CAS id.
CheckAndSetBadValue uint64 `proto:"cas_badval"`
// Total number of touches serviced by this class
TouchHits uint64 `proto:"touch_hits"`
// How many chunks have been allocated to items
UsedChunks uint64 `proto:"used_chunks"`
// Chunks not yet allocated to items, or freed via delete
FreeChunks uint64 `proto:"free_chunks"`
// Number of free chunks at the end of the last allocated page
FreeChecksEnd uint64 `proto:"free_chunks_end"`
}
// SlabStatistics contains statistics about the server's slabs.
type SlabStatistics struct {
// Total number of slab classes allocated
ActiveSlabs uint64 `proto:"active_slabs"`
// Total amount of memory allocated to slab pages
TotalMalloced uint64 `proto:"total_malloced"`
// PerSlabStatistics contains detailed statistics on a per-chunk basis.
PerSlabStatistics map[uint]*PerSlabStatistics
}
// SlabsStatisticsForAddress returns per-slab statistics for the specified memcached server.
func (c *Client) SlabsStatisticsForAddress(address string) (*SlabStatistics, error) {
connection, err := c.cp.ForAddress(address)
if err != nil {
return nil, err
}
defer connection.Close()
if _, err := fmt.Fprint(connection, "stats slabs\r\n"); err != nil {
return nil, err
}
statistics := &SlabStatistics{
PerSlabStatistics: map[uint]*PerSlabStatistics{},
}
if err := parseSettingsResponse(connection, func(prefix string) interface{} {
n, err := strconv.ParseUint(prefix, 10, 64)
if err != nil {
return statistics
}
if stats, ok := statistics.PerSlabStatistics[uint(n)]; ok {
return stats
}
stats := &PerSlabStatistics{}
statistics.PerSlabStatistics[uint(n)] = stats
return stats
}); err != nil {
return nil, err
}
return statistics, nil
}
var statPrefix = []byte("STAT ")
func parseSettingsResponse(conn net.Conn, instanceGetter func(prefix string) interface{}) error {
reader := bufio.NewReader(conn)
for {
line, err := reader.ReadSlice('\n')
if err != nil {
return err
}
if bytes.Equal(line, resultEnd) {
return nil
}
if len(line) <= len(statPrefix) {
return fmt.Errorf("Unexpected response from Memcached, got %q", string(line))
}
returnedPrefix := line[0:len(statPrefix)]
if !bytes.Equal(returnedPrefix, statPrefix) {
return fmt.Errorf("Unexpected response from Memcached, got %q", string(line))
}
cleanedLine := string(line[len(statPrefix):])
cleanedLine = strings.Trim(cleanedLine, " \n\r")
parts := strings.Split(cleanedLine, " ")
if len(parts) != 2 {
return fmt.Errorf("Unexpected response from Memcached, got %q", cleanedLine)
}
prefix, key := splitKey(parts[0])
value := parts[1]
instance := instanceGetter(prefix)
instanceElem := reflect.ValueOf(instance).Elem()
instanceType := instanceElem.Type()
for i := 0; i < instanceType.NumField(); i++ {
field := instanceType.Field(i)
tag := field.Tag.Get("proto")
if tag == key {
switch field.Type.Name() {
case "uint64":
value, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return err
}
instanceElem.Field(i).SetUint(value)
case "uint32":
value, err := strconv.ParseUint(value, 10, 32)
if err != nil {
return err
}
instanceElem.Field(i).SetUint(value)
case "float64":
value, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
instanceElem.Field(i).SetFloat(value)
case "bool":
isTrue := value == "1" || value == "yes"
instanceElem.Field(i).SetBool(isTrue)
case "string":
instanceElem.Field(i).SetString(value)
case "Duration":
value, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return err
}
instanceElem.Field(i).Set(reflect.ValueOf(time.Duration(value)))
case "SlabsAutomoveMode":
value, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return err
}
instanceElem.Field(i).Set(reflect.ValueOf(SlabsAutomoveMode(value)))
default:
return fmt.Errorf("Found correct field for key %v but unsupported type %v", key, field.Type.Name())
}
}
}
}
}
func splitKey(completeKey string) (prefix, key string) {
if i := strings.LastIndex(completeKey, ":"); i != -1 {
return completeKey[0:i], completeKey[i+1 : len(completeKey)]
}
return completeKey, completeKey
}