Skip to content

Commit

Permalink
k8s: don't exit if not running in a kubernetes cluster
Browse files Browse the repository at this point in the history
  • Loading branch information
apetruhin committed Jun 27, 2024
1 parent 85d1fc2 commit 809b176
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 15 deletions.
9 changes: 9 additions & 0 deletions discovery/k8s.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package discovery

import (
"errors"
"sync"

corev1 "k8s.io/api/core/v1"
Expand All @@ -9,6 +10,7 @@ import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/klog"
)

type PodEventType int
Expand Down Expand Up @@ -41,6 +43,10 @@ type K8S struct {
func NewK8S() (*K8S, error) {
config, err := rest.InClusterConfig()
if err != nil {
if errors.Is(err, rest.ErrNotInCluster) {
klog.Infoln("not running inside a kubernetes cluster")
return nil, nil
}
return nil, err
}

Expand All @@ -59,6 +65,9 @@ func NewK8S() (*K8S, error) {
}

func (k8s *K8S) Start() {
if len(k8s.subscribers) == 0 {
return
}
go k8s.start()
}

Expand Down
31 changes: 16 additions & 15 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,6 @@ func main() {
klog.Exitln(err)
}

k8s, err := discovery.NewK8S()
if err != nil {
klog.Exitln(err)
}

ms, err := metrics.NewMetrics()
if err != nil {
klog.Exitln(err)
Expand All @@ -51,20 +46,26 @@ func main() {
router.Handle("/metrics", ms.HttpHandler())
}

ps, err := profiles.NewProfiles()
cu.Start()
defer cu.Stop()

k8s, err := discovery.NewK8S()
if err != nil {
klog.Exitln(err)
}
if ps != nil {
k8s.Subscribe(ps)
ps.Start()
}

cu.Start()
defer cu.Stop()

k8s.Start()
defer k8s.Stop()
if k8s != nil {
ps, err := profiles.NewProfiles()
if err != nil {
klog.Exitln(err)
}
if ps != nil {
k8s.Subscribe(ps)
ps.Start()
}
k8s.Start()
defer k8s.Stop()
}

klog.Infoln("listening on", *flags.ListenAddress)
klog.Exitln(http.ListenAndServe(*flags.ListenAddress, router))
Expand Down

0 comments on commit 809b176

Please sign in to comment.