datasource_cache.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. DualStack: true,
  47. }).Dial,
  48. TLSHandshakeTimeout: 10 * time.Second,
  49. ExpectContinueTimeout: 1 * time.Second,
  50. MaxIdleConns: 100,
  51. IdleConnTimeout: 90 * time.Second,
  52. }
  53. var tlsAuth, tlsAuthWithCACert bool
  54. if ds.JsonData != nil {
  55. tlsAuth = ds.JsonData.Get("tlsAuth").MustBool(false)
  56. tlsAuthWithCACert = ds.JsonData.Get("tlsAuthWithCACert").MustBool(false)
  57. }
  58. if tlsAuth {
  59. transport.TLSClientConfig.InsecureSkipVerify = false
  60. decrypted := ds.SecureJsonData.Decrypt()
  61. if tlsAuthWithCACert && len(decrypted["tlsCACert"]) > 0 {
  62. caPool := x509.NewCertPool()
  63. ok := caPool.AppendCertsFromPEM([]byte(decrypted["tlsCACert"]))
  64. if ok {
  65. transport.TLSClientConfig.RootCAs = caPool
  66. }
  67. }
  68. cert, err := tls.X509KeyPair([]byte(decrypted["tlsClientCert"]), []byte(decrypted["tlsClientKey"]))
  69. if err != nil {
  70. return nil, err
  71. }
  72. transport.TLSClientConfig.Certificates = []tls.Certificate{cert}
  73. }
  74. ptc.cache[ds.Id] = cachedTransport{
  75. Transport: transport,
  76. updated: ds.Updated,
  77. }
  78. return transport, nil
  79. }