datasource_cache.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package models
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "net"
  6. "net/http"
  7. "sync"
  8. "time"
  9. )
  10. type proxyTransportCache struct {
  11. cache map[int64]cachedTransport
  12. sync.Mutex
  13. }
  14. type cachedTransport struct {
  15. updated time.Time
  16. *http.Transport
  17. }
  18. var ptc = proxyTransportCache{
  19. cache: make(map[int64]cachedTransport),
  20. }
  21. func (ds *DataSource) GetHttpClient() (*http.Client, error) {
  22. transport, err := ds.GetHttpTransport()
  23. if err != nil {
  24. return nil, err
  25. }
  26. return &http.Client{
  27. Timeout: time.Duration(30 * time.Second),
  28. Transport: transport,
  29. }, nil
  30. }
  31. func (ds *DataSource) GetHttpTransport() (*http.Transport, error) {
  32. ptc.Lock()
  33. defer ptc.Unlock()
  34. if t, present := ptc.cache[ds.Id]; present && ds.Updated.Equal(t.updated) {
  35. return t.Transport, nil
  36. }
  37. transport := &http.Transport{
  38. TLSClientConfig: &tls.Config{
  39. InsecureSkipVerify: true,
  40. Renegotiation: tls.RenegotiateFreelyAsClient,
  41. },
  42. Proxy: http.ProxyFromEnvironment,
  43. Dial: (&net.Dialer{
  44. Timeout: 30 * time.Second,
  45. KeepAlive: 30 * time.Second,
  46. }).Dial,
  47. TLSHandshakeTimeout: 10 * time.Second,
  48. ExpectContinueTimeout: 1 * time.Second,
  49. MaxIdleConns: 100,
  50. IdleConnTimeout: 90 * time.Second,
  51. }
  52. var tlsAuth, tlsAuthWithCACert bool
  53. if ds.JsonData != nil {
  54. tlsAuth = ds.JsonData.Get("tlsAuth").MustBool(false)
  55. tlsAuthWithCACert = ds.JsonData.Get("tlsAuthWithCACert").MustBool(false)
  56. }
  57. if tlsAuth {
  58. transport.TLSClientConfig.InsecureSkipVerify = false
  59. decrypted := ds.SecureJsonData.Decrypt()
  60. if tlsAuthWithCACert && len(decrypted["tlsCACert"]) > 0 {
  61. caPool := x509.NewCertPool()
  62. ok := caPool.AppendCertsFromPEM([]byte(decrypted["tlsCACert"]))
  63. if ok {
  64. transport.TLSClientConfig.RootCAs = caPool
  65. }
  66. }
  67. cert, err := tls.X509KeyPair([]byte(decrypted["tlsClientCert"]), []byte(decrypted["tlsClientKey"]))
  68. if err != nil {
  69. return nil, err
  70. }
  71. transport.TLSClientConfig.Certificates = []tls.Certificate{cert}
  72. }
  73. ptc.cache[ds.Id] = cachedTransport{
  74. Transport: transport,
  75. updated: ds.Updated,
  76. }
  77. return transport, nil
  78. }