datasource_cache.go 2.0 KB

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