proxy.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package handler
  15. import (
  16. "context"
  17. "net/http"
  18. "net/url"
  19. "yunion.io/x/pkg/util/httputils"
  20. "yunion.io/x/onecloud/pkg/apis"
  21. "yunion.io/x/onecloud/pkg/apis/identity"
  22. "yunion.io/x/onecloud/pkg/appsrv"
  23. "yunion.io/x/onecloud/pkg/mcclient/auth"
  24. "yunion.io/x/onecloud/pkg/proxy"
  25. )
  26. type InfluxdbProxyHandler struct {
  27. prefix string
  28. serviceName string
  29. }
  30. func NewInfluxdbProxyHandler(prefix string) *InfluxdbProxyHandler {
  31. return NewProxyHandlerWithService(prefix, apis.SERVICE_TYPE_INFLUXDB)
  32. }
  33. func NewProxyHandlerWithService(prefix string, serviceName string) *InfluxdbProxyHandler {
  34. return &InfluxdbProxyHandler{
  35. prefix: prefix,
  36. serviceName: serviceName,
  37. }
  38. }
  39. func requestManipulator(ctx context.Context, r *http.Request) (*http.Request, error) {
  40. token, _, _ := fetchAuthInfo(ctx, r)
  41. if token != nil {
  42. r.Header.Set("X-Auth-Token", token.GetTokenString())
  43. }
  44. return r, nil
  45. }
  46. func (h *InfluxdbProxyHandler) Bind(app *appsrv.Application) {
  47. app.AddReverseProxyHandler(h.prefix, fetchReverseEndpoint(h.serviceName), requestManipulator)
  48. }
  49. func getEndpointSchemeHost(endpoint string) (string, error) {
  50. u, err := url.Parse(endpoint)
  51. if err != nil {
  52. return "", err
  53. }
  54. nu := &url.URL{
  55. Host: u.Host,
  56. Scheme: u.Scheme,
  57. }
  58. return nu.String(), nil
  59. }
  60. func fetchReverseEndpoint(serviceName string) *proxy.SEndpointFactory {
  61. f := func(ctx context.Context, r *http.Request) (string, error) {
  62. session := auth.GetAdminSession(ctx, FetchRegion(r))
  63. ep, err := session.GetServiceURL(serviceName, identity.EndpointInterfaceInternal, httputils.THttpMethod(r.Method))
  64. if err != nil {
  65. return "", err
  66. }
  67. return getEndpointSchemeHost(ep)
  68. }
  69. return proxy.NewEndpointFactory(f, serviceName)
  70. }