lookup_vid_cache.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package operation
  2. import (
  3. "errors"
  4. "strconv"
  5. "sync"
  6. "time"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. )
  9. type VidInfo struct {
  10. Locations []Location
  11. NextRefreshTime time.Time
  12. }
  13. type VidCache struct {
  14. sync.RWMutex
  15. cache []VidInfo
  16. }
  17. func (vc *VidCache) Get(vid string) ([]Location, error) {
  18. id, err := strconv.Atoi(vid)
  19. if err != nil {
  20. glog.V(1).Infof("Unknown volume id %s", vid)
  21. return nil, err
  22. }
  23. vc.RLock()
  24. defer vc.RUnlock()
  25. if 0 < id && id <= len(vc.cache) {
  26. if vc.cache[id-1].Locations == nil {
  27. return nil, errors.New("Not Set")
  28. }
  29. if vc.cache[id-1].NextRefreshTime.Before(time.Now()) {
  30. return nil, errors.New("Expired")
  31. }
  32. return vc.cache[id-1].Locations, nil
  33. }
  34. return nil, errors.New("Not Found")
  35. }
  36. func (vc *VidCache) Set(vid string, locations []Location, duration time.Duration) {
  37. id, err := strconv.Atoi(vid)
  38. if err != nil {
  39. glog.V(1).Infof("Unknown volume id %s", vid)
  40. return
  41. }
  42. vc.Lock()
  43. defer vc.Unlock()
  44. if id > len(vc.cache) {
  45. for i := id - len(vc.cache); i > 0; i-- {
  46. vc.cache = append(vc.cache, VidInfo{})
  47. }
  48. }
  49. if id > 0 {
  50. vc.cache[id-1].Locations = locations
  51. vc.cache[id-1].NextRefreshTime = time.Now().Add(duration)
  52. }
  53. }