online.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. // package online manage device online state and store it in redis.
  2. package online
  3. import (
  4. "errors"
  5. "github.com/garyburd/redigo/redis"
  6. "sparrow/pkg/redispool"
  7. "sparrow/pkg/serializer"
  8. )
  9. const (
  10. OnlineStatusKeyPrefix = "device:onlinestatus:"
  11. )
  12. type Status struct {
  13. ClientIP string
  14. AccessRPCHost string
  15. HeartbeatInterval uint32
  16. }
  17. type Manager struct {
  18. redishost string
  19. }
  20. func NewManager(host string) *Manager {
  21. mgr := &Manager{
  22. redishost: host,
  23. }
  24. return mgr
  25. }
  26. func (mgr *Manager) GetStatus(id string) (*Status, error) {
  27. key := OnlineStatusKeyPrefix + id
  28. conn, err := redispool.GetClient(mgr.redishost)
  29. if err != nil {
  30. return nil, err
  31. }
  32. status := &Status{}
  33. // get status from redis
  34. bufferStr, err := redis.String(conn.Do("GET", key))
  35. if err != nil {
  36. return nil, err
  37. }
  38. err = serializer.String2Struct(bufferStr, status)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return status, nil
  43. }
  44. func (mgr *Manager) GetOnline(id string, status Status) error {
  45. key := OnlineStatusKeyPrefix + id
  46. conn, err := redispool.GetClient(mgr.redishost)
  47. if err != nil {
  48. return err
  49. }
  50. // serialize and store the device's online status info in redis
  51. bufferStr, err := serializer.Struct2String(status)
  52. if err != nil {
  53. return err
  54. }
  55. _, err = conn.Do("SET", key, bufferStr)
  56. if err != nil {
  57. return err
  58. }
  59. _, err = conn.Do("EXPIRE", key, status.HeartbeatInterval+status.HeartbeatInterval/2)
  60. if err != nil {
  61. return err
  62. }
  63. return nil
  64. }
  65. func (mgr *Manager) SetHeartbeat(id string) error {
  66. status, err := mgr.GetStatus(id)
  67. if err != nil {
  68. return err
  69. }
  70. if status == nil {
  71. return errors.New("device offline.")
  72. }
  73. key := OnlineStatusKeyPrefix + id
  74. conn, err := redispool.GetClient(mgr.redishost)
  75. if err != nil {
  76. return err
  77. }
  78. _, err = conn.Do("EXPIRE", key, status.HeartbeatInterval+status.HeartbeatInterval/2)
  79. if err != nil {
  80. return err
  81. }
  82. return nil
  83. }
  84. func (mgr *Manager) GetOffline(id string) error {
  85. key := OnlineStatusKeyPrefix + id
  86. conn, err := redispool.GetClient(mgr.redishost)
  87. if err != nil {
  88. return err
  89. }
  90. _, err = conn.Do("DEL", key)
  91. if err != nil {
  92. return err
  93. }
  94. return nil
  95. }