online_map.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package stats
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. // OnlineMap is an implementation of stats.OnlineMap.
  7. type OnlineMap struct {
  8. ipList map[string]time.Time
  9. access sync.RWMutex
  10. lastCleanup time.Time
  11. cleanupPeriod time.Duration
  12. }
  13. // NewOnlineMap creates a new instance of OnlineMap.
  14. func NewOnlineMap() *OnlineMap {
  15. return &OnlineMap{
  16. ipList: make(map[string]time.Time),
  17. lastCleanup: time.Now(),
  18. cleanupPeriod: 10 * time.Second,
  19. }
  20. }
  21. // Count implements stats.OnlineMap.
  22. func (c *OnlineMap) Count() int {
  23. c.access.RLock()
  24. defer c.access.RUnlock()
  25. return len(c.ipList)
  26. }
  27. // List implements stats.OnlineMap.
  28. func (c *OnlineMap) List() []string {
  29. return c.GetKeys()
  30. }
  31. // AddIP implements stats.OnlineMap.
  32. func (c *OnlineMap) AddIP(ip string) {
  33. if ip == "127.0.0.1" {
  34. return
  35. }
  36. c.access.Lock()
  37. c.ipList[ip] = time.Now()
  38. c.access.Unlock()
  39. if time.Since(c.lastCleanup) > c.cleanupPeriod {
  40. c.RemoveExpiredIPs()
  41. c.lastCleanup = time.Now()
  42. }
  43. }
  44. func (c *OnlineMap) GetKeys() []string {
  45. c.access.RLock()
  46. defer c.access.RUnlock()
  47. keys := []string{}
  48. for k := range c.ipList {
  49. keys = append(keys, k)
  50. }
  51. return keys
  52. }
  53. func (c *OnlineMap) RemoveExpiredIPs() {
  54. c.access.Lock()
  55. defer c.access.Unlock()
  56. now := time.Now()
  57. for k, t := range c.ipList {
  58. diff := now.Sub(t)
  59. if diff.Seconds() > 20 {
  60. delete(c.ipList, k)
  61. }
  62. }
  63. }
  64. func (c *OnlineMap) IpTimeMap() map[string]time.Time {
  65. if time.Since(c.lastCleanup) > c.cleanupPeriod {
  66. c.RemoveExpiredIPs()
  67. c.lastCleanup = time.Now()
  68. }
  69. return c.ipList
  70. }