datasource_cache.go 2.2 KB

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