filer_server_handlers_proxy.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package weed_server
  2. import (
  3. "github.com/seaweedfs/seaweedfs/weed/glog"
  4. "github.com/seaweedfs/seaweedfs/weed/security"
  5. util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
  6. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  7. "io"
  8. "math/rand/v2"
  9. "net/http"
  10. )
  11. func (fs *FilerServer) maybeAddVolumeJwtAuthorization(r *http.Request, fileId string, isWrite bool) {
  12. encodedJwt := fs.maybeGetVolumeJwtAuthorizationToken(fileId, isWrite)
  13. if encodedJwt == "" {
  14. return
  15. }
  16. r.Header.Set("Authorization", "BEARER "+string(encodedJwt))
  17. }
  18. func (fs *FilerServer) maybeGetVolumeJwtAuthorizationToken(fileId string, isWrite bool) string {
  19. var encodedJwt security.EncodedJwt
  20. if isWrite {
  21. encodedJwt = security.GenJwtForVolumeServer(fs.volumeGuard.SigningKey, fs.volumeGuard.ExpiresAfterSec, fileId)
  22. } else {
  23. encodedJwt = security.GenJwtForVolumeServer(fs.volumeGuard.ReadSigningKey, fs.volumeGuard.ReadExpiresAfterSec, fileId)
  24. }
  25. return string(encodedJwt)
  26. }
  27. func (fs *FilerServer) proxyToVolumeServer(w http.ResponseWriter, r *http.Request, fileId string) {
  28. urlStrings, err := fs.filer.MasterClient.GetLookupFileIdFunction()(fileId)
  29. if err != nil {
  30. glog.Errorf("locate %s: %v", fileId, err)
  31. w.WriteHeader(http.StatusInternalServerError)
  32. return
  33. }
  34. if len(urlStrings) == 0 {
  35. w.WriteHeader(http.StatusNotFound)
  36. return
  37. }
  38. proxyReq, err := http.NewRequest(r.Method, urlStrings[rand.IntN(len(urlStrings))], r.Body)
  39. if err != nil {
  40. glog.Errorf("NewRequest %s: %v", urlStrings[0], err)
  41. w.WriteHeader(http.StatusInternalServerError)
  42. return
  43. }
  44. proxyReq.Header.Set("Host", r.Host)
  45. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  46. for header, values := range r.Header {
  47. for _, value := range values {
  48. proxyReq.Header.Add(header, value)
  49. }
  50. }
  51. proxyResponse, postErr := util_http.GetGlobalHttpClient().Do(proxyReq)
  52. if postErr != nil {
  53. glog.Errorf("post to filer: %v", postErr)
  54. w.WriteHeader(http.StatusInternalServerError)
  55. return
  56. }
  57. defer util_http.CloseResponse(proxyResponse)
  58. for k, v := range proxyResponse.Header {
  59. w.Header()[k] = v
  60. }
  61. w.WriteHeader(proxyResponse.StatusCode)
  62. buf := mem.Allocate(128 * 1024)
  63. defer mem.Free(buf)
  64. io.CopyBuffer(w, proxyResponse.Body, buf)
  65. }