-
Notifications
You must be signed in to change notification settings - Fork 64
/
cluster_config.go
91 lines (73 loc) · 2.04 KB
/
cluster_config.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
87
88
89
90
91
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/rs/zerolog/log"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
const (
typeAutoCluster = "auto"
typeInCluster = "in-cluster"
typeOutCluster = "out-cluster"
)
func getClusterConfig() (*rest.Config, error) {
var config *rest.Config
var err error
configType := strings.ToLower(os.Getenv("SENTRY_K8S_CLUSTER_CONFIG_TYPE"))
configType = strings.TrimSpace(configType)
if configType == "" {
configType = typeAutoCluster
}
if configType != typeAutoCluster &&
configType != typeInCluster &&
configType != typeOutCluster {
log.Fatal().Msgf(
"Infalid cluster configuration type provided in SENTRY_K8S_CLUSTER_CONFIG_TYPE: %s",
configType,
)
}
autoConfig := configType == typeAutoCluster
if autoConfig {
log.Info().Msg("Auto-detecting cluster configuration...")
}
if autoConfig || configType == typeInCluster {
log.Debug().Msg("Trying to initialize in-cluster config...")
config, err = rest.InClusterConfig()
if err == nil {
log.Info().Msg("Detected in-cluster configuration")
return config, nil
}
if autoConfig {
log.Warn().Msgf("Could not initialize in-cluster config")
} else {
return nil, err
}
}
if autoConfig || configType == typeOutCluster {
log.Debug().Msg("Initializing out-of-cluster config...")
kubeconfig := os.Getenv("SENTRY_K8S_KUBECONFIG_PATH")
if kubeconfig == "" {
log.Debug().Msg("Trying to read kubeconfig from home directory...")
if home := homedir.HomeDir(); home != "" {
kubeconfig = filepath.Join(home, ".kube", "config")
} else {
return nil, fmt.Errorf("cannot find the default kubeconfig")
}
}
log.Debug().Msgf("Kubeconfig path: %s", kubeconfig)
config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
if err == nil {
log.Info().Msg("Detected out-of-cluster configuration")
return config, nil
}
return nil, err
}
if config == nil {
return nil, fmt.Errorf("cannot initialize cluster config")
}
return config, nil
}