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.

87 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. ret, err = do_lookup(server, vid)
  28. vc.Set(vid, ret.Locations, 1*time.Minute)
  29. } else {
  30. ret = &LookupResult{VolumeId: vid, Locations: locations}
  31. }
  32. return
  33. }
  34. func do_lookup(server string, vid string) (*LookupResult, error) {
  35. values := make(url.Values)
  36. values.Add("volumeId", vid)
  37. jsonBlob, err := util.Post("http://"+server+"/dir/lookup", values)
  38. if err != nil {
  39. return nil, err
  40. }
  41. var ret LookupResult
  42. err = json.Unmarshal(jsonBlob, &ret)
  43. if err != nil {
  44. return nil, err
  45. }
  46. if ret.Error != "" {
  47. return nil, errors.New(ret.Error)
  48. }
  49. return &ret, nil
  50. }
  51. func LookupFileId(server string, fileId string) (fullUrl string, err error) {
  52. parts := strings.Split(fileId, ",")
  53. if len(parts) != 2 {
  54. return "", errors.New("Invalid fileId " + fileId)
  55. }
  56. lookup, lookupError := Lookup(server, parts[0])
  57. if lookupError != nil {
  58. return "", lookupError
  59. }
  60. if len(lookup.Locations) == 0 {
  61. return "", errors.New("File Not Found")
  62. }
  63. return "http://" + lookup.Locations[rand.Intn(len(lookup.Locations))].PublicUrl + "/" + fileId, nil
  64. }
  65. func LookupVolumeIds(server string, vids []string) (map[string]LookupResult, error) {
  66. values := make(url.Values)
  67. for _, vid := range vids {
  68. values.Add("volumeId", vid)
  69. }
  70. jsonBlob, err := util.Post("http://"+server+"/vol/lookup", values)
  71. if err != nil {
  72. return nil, err
  73. }
  74. ret := make(map[string]LookupResult)
  75. err = json.Unmarshal(jsonBlob, &ret)
  76. if err != nil {
  77. return nil, errors.New(err.Error() + " " + string(jsonBlob))
  78. }
  79. return ret, nil
  80. }