nodeclientconfig.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package costmodel
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "strings"
  9. coreenv "github.com/opencost/opencost/core/pkg/env"
  10. "github.com/opencost/opencost/core/pkg/log"
  11. nodes "github.com/opencost/opencost/core/pkg/nodestats"
  12. "github.com/opencost/opencost/pkg/env"
  13. )
  14. const (
  15. defaultConcurrentPollers = 10
  16. serviceAccountCaCert = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
  17. )
  18. func NewNodeClientConfigFromEnv() (*nodes.NodeClientConfig, error) {
  19. clusterId := coreenv.GetClusterID()
  20. concurrentPollers := defaultConcurrentPollers
  21. insecure := env.IsNodeStatsInsecure()
  22. certFile := env.GetNodeStatsCertFile()
  23. keyFile := env.GetNodeStatsKeyFile()
  24. forceKubeProxy := env.IsNodeStatsForceKubeProxy()
  25. localProxy := env.GetNodeStatsLocalProxy()
  26. if strings.TrimSpace(clusterId) == "" {
  27. return nil, fmt.Errorf("cluster id is required and cannot be exclusively whitespace.")
  28. }
  29. var transport *http.Transport
  30. if insecure {
  31. transport = &http.Transport{
  32. TLSClientConfig: &tls.Config{
  33. InsecureSkipVerify: true,
  34. MinVersion: tls.VersionTLS12,
  35. },
  36. }
  37. } else {
  38. pemData, err := os.ReadFile(serviceAccountCaCert)
  39. if err != nil {
  40. log.Fatalf("Could not load CA certificate: %v", err)
  41. }
  42. caCertPool := x509.NewCertPool()
  43. caCertPool.AppendCertsFromPEM(pemData)
  44. var tlsConfig *tls.Config
  45. if certFile != "" && keyFile != "" {
  46. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  47. if err != nil {
  48. log.Fatalf("Unable to load cert: %s key: %s error: %v", certFile, keyFile, err)
  49. }
  50. tlsConfig = &tls.Config{
  51. Certificates: []tls.Certificate{cert},
  52. RootCAs: caCertPool,
  53. MinVersion: tls.VersionTLS12,
  54. }
  55. transport = &http.Transport{TLSClientConfig: tlsConfig}
  56. } else {
  57. tlsConfig := &tls.Config{
  58. RootCAs: caCertPool,
  59. MinVersion: tls.VersionTLS12,
  60. }
  61. transport = &http.Transport{TLSClientConfig: tlsConfig}
  62. }
  63. }
  64. return &nodes.NodeClientConfig{
  65. ClusterId: clusterId,
  66. ConcurrentPollers: concurrentPollers,
  67. Transport: transport,
  68. ProxyConfig: nodes.NodeClientProxyConfig{
  69. ForceKubeProxy: forceKubeProxy,
  70. LocalProxy: localProxy,
  71. },
  72. }, nil
  73. }