nodeclientconfig.go 2.0 KB

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