filer_server_handlers_proxy.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package weed_server
  2. import (
  3. "github.com/seaweedfs/seaweedfs/weed/glog"
  4. "github.com/seaweedfs/seaweedfs/weed/util"
  5. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  6. "io"
  7. "math/rand"
  8. "net/http"
  9. )
  10. var (
  11. client *http.Client
  12. )
  13. func init() {
  14. client = &http.Client{Transport: &http.Transport{
  15. MaxIdleConns: 1024,
  16. MaxIdleConnsPerHost: 1024,
  17. }}
  18. }
  19. func (fs *FilerServer) proxyToVolumeServer(w http.ResponseWriter, r *http.Request, fileId string) {
  20. urlStrings, err := fs.filer.MasterClient.GetLookupFileIdFunction()(fileId)
  21. if err != nil {
  22. glog.Errorf("locate %s: %v", fileId, err)
  23. w.WriteHeader(http.StatusInternalServerError)
  24. return
  25. }
  26. if len(urlStrings) == 0 {
  27. w.WriteHeader(http.StatusNotFound)
  28. return
  29. }
  30. proxyReq, err := http.NewRequest(r.Method, urlStrings[rand.Intn(len(urlStrings))], r.Body)
  31. if err != nil {
  32. glog.Errorf("NewRequest %s: %v", urlStrings[0], err)
  33. w.WriteHeader(http.StatusInternalServerError)
  34. return
  35. }
  36. proxyReq.Header.Set("Host", r.Host)
  37. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  38. for header, values := range r.Header {
  39. for _, value := range values {
  40. proxyReq.Header.Add(header, value)
  41. }
  42. }
  43. proxyResponse, postErr := client.Do(proxyReq)
  44. if postErr != nil {
  45. glog.Errorf("post to filer: %v", postErr)
  46. w.WriteHeader(http.StatusInternalServerError)
  47. return
  48. }
  49. defer util.CloseResponse(proxyResponse)
  50. for k, v := range proxyResponse.Header {
  51. w.Header()[k] = v
  52. }
  53. w.WriteHeader(proxyResponse.StatusCode)
  54. buf := mem.Allocate(128 * 1024)
  55. defer mem.Free(buf)
  56. io.CopyBuffer(w, proxyResponse.Body, buf)
  57. }