You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.1 KiB

  1. package operation
  2. import (
  3. "code.google.com/p/weed-fs/go/util"
  4. "encoding/json"
  5. "errors"
  6. _ "fmt"
  7. "math/rand"
  8. "net/url"
  9. "strings"
  10. "time"
  11. )
  12. type Location struct {
  13. Url string `json:"url,omitempty"`
  14. PublicUrl string `json:"publicUrl,omitempty"`
  15. }
  16. type LookupResult struct {
  17. VolumeId string `json:"volumeId,omitempty"`
  18. Locations []Location `json:"locations,omitempty"`
  19. Error string `json:"error,omitempty"`
  20. }
  21. var (
  22. vc VidCache
  23. )
  24. func Lookup(server string, vid string) (ret *LookupResult, err error) {
  25. locations, cache_err := vc.Get(vid)
  26. if cache_err != nil {
  27. if ret, err = do_lookup(server, vid); err == nil {
  28. vc.Set(vid, ret.Locations, 1*time.Minute)
  29. }
  30. } else {
  31. ret = &LookupResult{VolumeId: vid, Locations: locations}
  32. }
  33. return
  34. }
  35. func do_lookup(server string, vid string) (*LookupResult, error) {
  36. values := make(url.Values)
  37. values.Add("volumeId", vid)
  38. jsonBlob, err := util.Post("http://"+server+"/dir/lookup", values)
  39. if err != nil {
  40. return nil, err
  41. }
  42. var ret LookupResult
  43. err = json.Unmarshal(jsonBlob, &ret)
  44. if err != nil {
  45. return nil, err
  46. }
  47. if ret.Error != "" {
  48. return nil, errors.New(ret.Error)
  49. }
  50. return &ret, nil
  51. }
  52. func LookupFileId(server string, fileId string) (fullUrl string, err error) {
  53. parts := strings.Split(fileId, ",")
  54. if len(parts) != 2 {
  55. return "", errors.New("Invalid fileId " + fileId)
  56. }
  57. lookup, lookupError := Lookup(server, parts[0])
  58. if lookupError != nil {
  59. return "", lookupError
  60. }
  61. if len(lookup.Locations) == 0 {
  62. return "", errors.New("File Not Found")
  63. }
  64. return "http://" + lookup.Locations[rand.Intn(len(lookup.Locations))].PublicUrl + "/" + fileId, nil
  65. }
  66. func LookupVolumeIds(server string, vids []string) (map[string]LookupResult, error) {
  67. values := make(url.Values)
  68. for _, vid := range vids {
  69. values.Add("volumeId", vid)
  70. }
  71. jsonBlob, err := util.Post("http://"+server+"/vol/lookup", values)
  72. if err != nil {
  73. return nil, err
  74. }
  75. ret := make(map[string]LookupResult)
  76. err = json.Unmarshal(jsonBlob, &ret)
  77. if err != nil {
  78. return nil, errors.New(err.Error() + " " + string(jsonBlob))
  79. }
  80. return ret, nil
  81. }