-
Notifications
You must be signed in to change notification settings - Fork 485
/
kubernetes.go
86 lines (73 loc) · 2.61 KB
/
kubernetes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package kubernetes
import (
"fmt"
"reflect"
"github.com/go-kit/log"
commoncfg "github.com/grafana/agent/component/common/config"
"github.com/grafana/agent/internal/useragent"
"github.com/grafana/agent/pkg/flow/logging/level"
promconfig "github.com/prometheus/common/config"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
// ClientArguments controls how to connect to a Kubernetes cluster.
type ClientArguments struct {
APIServer commoncfg.URL `river:"api_server,attr,optional"`
KubeConfig string `river:"kubeconfig_file,attr,optional"`
HTTPClientConfig commoncfg.HTTPClientConfig `river:",squash"`
}
// DefaultClientArguments holds default values for Arguments.
var DefaultClientArguments = ClientArguments{
HTTPClientConfig: commoncfg.DefaultHTTPClientConfig,
}
// SetToDefault implements river.Defaulter.
func (args *ClientArguments) SetToDefault() {
*args = DefaultClientArguments
}
// Validate implements river.Validator.
func (args *ClientArguments) Validate() error {
if args.APIServer.URL != nil && args.KubeConfig != "" {
return fmt.Errorf("only one of api_server and kubeconfig_file can be set")
}
if args.KubeConfig != "" && !reflect.DeepEqual(args.HTTPClientConfig, commoncfg.DefaultHTTPClientConfig) {
return fmt.Errorf("custom HTTP client configuration is not allowed when kubeconfig_file is set")
}
if args.APIServer.URL == nil && !reflect.DeepEqual(args.HTTPClientConfig, commoncfg.DefaultHTTPClientConfig) {
return fmt.Errorf("api_server must be set when custom HTTP client configuration is provided")
}
// We must explicitly Validate because HTTPClientConfig is squashed and it won't run otherwise
return args.HTTPClientConfig.Validate()
}
// BuildRESTConfig converts ClientArguments to a Kubernetes REST config.
func (args *ClientArguments) BuildRESTConfig(l log.Logger) (*rest.Config, error) {
var (
cfg *rest.Config
err error
)
switch {
case args.KubeConfig != "":
cfg, err = clientcmd.BuildConfigFromFlags("", args.KubeConfig)
if err != nil {
return nil, err
}
case args.APIServer.URL == nil:
// Use in-cluster config.
cfg, err = rest.InClusterConfig()
if err != nil {
return nil, err
}
level.Info(l).Log("msg", "Using pod service account via in-cluster config")
default:
rt, err := promconfig.NewRoundTripperFromConfig(*args.HTTPClientConfig.Convert(), "component.common.kubernetes")
if err != nil {
return nil, err
}
cfg = &rest.Config{
Host: args.APIServer.String(),
Transport: rt,
}
}
cfg.UserAgent = useragent.Get()
cfg.ContentType = "application/vnd.kubernetes.protobuf"
return cfg, nil
}