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.

71 lines
1.7 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. )
  11. type Location struct {
  12. Url string `json:"url,omitempty"`
  13. PublicUrl string `json:"publicUrl,omitempty"`
  14. }
  15. type LookupResult struct {
  16. VolumeId string `json:"volumeId,omitempty"`
  17. Locations []Location `json:"locations,omitempty"`
  18. Error string `json:"error,omitempty"`
  19. }
  20. func Lookup(server string, vid string) (*LookupResult, error) {
  21. values := make(url.Values)
  22. values.Add("volumeId", vid)
  23. jsonBlob, err := util.Post("http://"+server+"/dir/lookup", values)
  24. if err != nil {
  25. return nil, err
  26. }
  27. var ret LookupResult
  28. err = json.Unmarshal(jsonBlob, &ret)
  29. if err != nil {
  30. return nil, err
  31. }
  32. if ret.Error != "" {
  33. return nil, errors.New(ret.Error)
  34. }
  35. return &ret, nil
  36. }
  37. func LookupFileId(server string, fileId string) (fullUrl string, err error) {
  38. parts := strings.Split(fileId, ",")
  39. if len(parts) != 2 {
  40. return "", errors.New("Invalid fileId " + fileId)
  41. }
  42. lookup, lookupError := Lookup(server, parts[0])
  43. if lookupError != nil {
  44. return "", lookupError
  45. }
  46. if len(lookup.Locations) == 0 {
  47. return "", errors.New("File Not Found")
  48. }
  49. return "http://" + lookup.Locations[rand.Intn(len(lookup.Locations))].PublicUrl + "/" + fileId, nil
  50. }
  51. func LookupVolumeIds(server string, vids []string) (map[string]LookupResult, error) {
  52. values := make(url.Values)
  53. for _, vid := range vids {
  54. values.Add("volumeId", vid)
  55. }
  56. jsonBlob, err := util.Post("http://"+server+"/vol/lookup", values)
  57. if err != nil {
  58. return nil, err
  59. }
  60. ret := make(map[string]LookupResult)
  61. err = json.Unmarshal(jsonBlob, &ret)
  62. if err != nil {
  63. return nil, errors.New(err.Error() + " " + string(jsonBlob))
  64. }
  65. return ret, nil
  66. }