nodeclientconfig.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. },
  35. }
  36. } else {
  37. pemData, err := os.ReadFile(serviceAccountCaCert)
  38. if err != nil {
  39. log.Fatalf("Could not load CA certificate: %v", err)
  40. }
  41. caCertPool := x509.NewCertPool()
  42. caCertPool.AppendCertsFromPEM(pemData)
  43. var tlsConfig *tls.Config
  44. if certFile != "" && keyFile != "" {
  45. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  46. if err != nil {
  47. log.Fatalf("Unable to load cert: %s key: %s error: %v", certFile, keyFile, err)
  48. }
  49. tlsConfig = &tls.Config{
  50. Certificates: []tls.Certificate{cert},
  51. RootCAs: caCertPool,
  52. }
  53. transport = &http.Transport{TLSClientConfig: tlsConfig}
  54. } else {
  55. tlsConfig := &tls.Config{
  56. RootCAs: caCertPool,
  57. }
  58. transport = &http.Transport{TLSClientConfig: tlsConfig}
  59. }
  60. }
  61. return &nodes.NodeClientConfig{
  62. ClusterId: clusterId,
  63. ConcurrentPollers: concurrentPollers,
  64. Transport: transport,
  65. ProxyConfig: nodes.NodeClientProxyConfig{
  66. ForceKubeProxy: forceKubeProxy,
  67. LocalProxy: localProxy,
  68. },
  69. }, nil
  70. }