status.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package manager
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strconv"
  7. "time"
  8. . "github.com/tuna/tunasync/internal"
  9. )
  10. type mirrorStatus struct {
  11. Name string
  12. Worker string
  13. IsMaster bool
  14. Status SyncStatus
  15. LastUpdate time.Time
  16. Upstream string
  17. Size string // approximate size
  18. }
  19. func (s mirrorStatus) MarshalJSON() ([]byte, error) {
  20. m := map[string]interface{}{
  21. "name": s.Name,
  22. "worker": s.Worker,
  23. "is_master": s.IsMaster,
  24. "status": s.Status,
  25. "last_update": s.LastUpdate.Format("2006-01-02 15:04:05"),
  26. "last_update_ts": fmt.Sprintf("%d", s.LastUpdate.Unix()),
  27. "size": s.Size,
  28. "upstream": s.Upstream,
  29. }
  30. return json.Marshal(m)
  31. }
  32. func (s *mirrorStatus) UnmarshalJSON(v []byte) error {
  33. var m map[string]interface{}
  34. err := json.Unmarshal(v, &m)
  35. if err != nil {
  36. return err
  37. }
  38. if name, ok := m["name"]; ok {
  39. if s.Name, ok = name.(string); !ok {
  40. return errors.New("name should be a string")
  41. }
  42. } else {
  43. return errors.New("key `name` does not exist in the json")
  44. }
  45. if upstream, ok := m["upstream"]; ok {
  46. if s.Upstream, ok = upstream.(string); !ok {
  47. return errors.New("upstream should be a string")
  48. }
  49. } else {
  50. return errors.New("key `upstream` does not exist in the json")
  51. }
  52. if size, ok := m["size"]; ok {
  53. if s.Size, ok = size.(string); !ok {
  54. return errors.New("size should be a string")
  55. }
  56. } else {
  57. return errors.New("key `size` does not exist in the json")
  58. }
  59. // tricky: status
  60. if status, ok := m["status"]; ok {
  61. if ss, ok := status.(string); ok {
  62. err := json.Unmarshal([]byte(`"`+ss+`"`), &(s.Status))
  63. if err != nil {
  64. return err
  65. }
  66. } else {
  67. return errors.New("status should be a string")
  68. }
  69. } else {
  70. return errors.New("key `status` does not exist in the json")
  71. }
  72. // tricky: last update
  73. if lastUpdate, ok := m["last_update_ts"]; ok {
  74. if sts, ok := lastUpdate.(string); ok {
  75. ts, err := strconv.Atoi(sts)
  76. if err != nil {
  77. return fmt.Errorf("last_update_ts should be a interger, got: %s", sts)
  78. }
  79. s.LastUpdate = time.Unix(int64(ts), 0)
  80. } else {
  81. return fmt.Errorf("last_update_ts should be a string of integer, got: %s", lastUpdate)
  82. }
  83. } else {
  84. return errors.New("key `last_update_ts` does not exist in the json")
  85. }
  86. return nil
  87. }