Fix k8s target discovery when not running inside k8s

When using Kubernetes service discovery on a Prometheus instance that's
not running inside Kubernetes, the creation of the service discovery
fails with a "no such file or directory" error as the special
`/var/run/secrets/kubernetes.io/serviceaccount/namespace` file is not
there.  This commit moves the code that reads this file into the
if-branch where no `APIServer.URL` is given (that one basically makes
Prometheus assume it is running inside of a Kubernetes cluster).

Signed-off-by: Georg Gadinger <nilsding@nilsding.org>
This commit is contained in:
Georg Gadinger 2022-02-01 10:20:03 +01:00
parent 3c9faa25bf
commit 4663f814d6

View file

@ -263,7 +263,7 @@ func (d *Discovery) getNamespaces() []string {
return []string{apiv1.NamespaceAll} return []string{apiv1.NamespaceAll}
} }
if includeOwnNamespace { if includeOwnNamespace && d.ownNamespace != "" {
return append(namespaces, d.ownNamespace) return append(namespaces, d.ownNamespace)
} }
@ -276,8 +276,9 @@ func New(l log.Logger, conf *SDConfig) (*Discovery, error) {
l = log.NewNopLogger() l = log.NewNopLogger()
} }
var ( var (
kcfg *rest.Config kcfg *rest.Config
err error err error
ownNamespace string
) )
if conf.KubeConfig != "" { if conf.KubeConfig != "" {
kcfg, err = clientcmd.BuildConfigFromFlags("", conf.KubeConfig) kcfg, err = clientcmd.BuildConfigFromFlags("", conf.KubeConfig)
@ -291,6 +292,13 @@ func New(l log.Logger, conf *SDConfig) (*Discovery, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
ownNamespaceContents, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
if err != nil {
return nil, fmt.Errorf("could not determine the pod's namespace: %w", err)
}
ownNamespace = string(ownNamespaceContents)
level.Info(l).Log("msg", "Using pod service account via in-cluster config") level.Info(l).Log("msg", "Using pod service account via in-cluster config")
} else { } else {
rt, err := config.NewRoundTripperFromConfig(conf.HTTPClientConfig, "kubernetes_sd") rt, err := config.NewRoundTripperFromConfig(conf.HTTPClientConfig, "kubernetes_sd")
@ -310,11 +318,6 @@ func New(l log.Logger, conf *SDConfig) (*Discovery, error) {
return nil, err return nil, err
} }
ownNamespace, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
if err != nil {
return nil, fmt.Errorf("could not determine the pod's namespace: %w", err)
}
return &Discovery{ return &Discovery{
client: c, client: c,
logger: l, logger: l,
@ -322,7 +325,7 @@ func New(l log.Logger, conf *SDConfig) (*Discovery, error) {
namespaceDiscovery: &conf.NamespaceDiscovery, namespaceDiscovery: &conf.NamespaceDiscovery,
discoverers: make([]discovery.Discoverer, 0), discoverers: make([]discovery.Discoverer, 0),
selectors: mapSelector(conf.Selectors), selectors: mapSelector(conf.Selectors),
ownNamespace: string(ownNamespace), ownNamespace: ownNamespace,
}, nil }, nil
} }