-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
139 lines (114 loc) · 3.98 KB
/
main.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package main
import (
"context"
"fmt"
"net/http"
"dario.cat/mergo"
"github.com/go-co-op/gocron/v2"
"github.com/mitchellh/hashstructure/v2"
"github.com/nccloud/watchtower/pkg"
"github.com/nccloud/watchtower/pkg/apis/v1alpha1"
"github.com/nccloud/watchtower/pkg/common"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/yaml"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/metrics/server"
)
var (
metricPort = 8083
healthPort = 8084
logger = zap.New()
config = common.NewConfig()
scheme = runtime.NewScheme()
interruptCtx = ctrl.SetupSignalHandler()
restartCtx context.Context
restart context.CancelFunc
kubeClient client.Client
watchers []v1alpha1.Watcher
)
func main() {
ctrl.SetLogger(logger)
common.Must(clientgoscheme.AddToScheme(scheme))
common.Must(v1alpha1.AddToScheme(scheme))
scheduler := common.MustReturn(gocron.NewScheduler())
kubeClient = common.MustReturn(client.New(ctrl.GetConfigOrDie(), client.Options{
Scheme: scheme,
}))
common.Must(RefreshWatchers(context.Background(), kubeClient))
common.MustReturn(scheduler.NewJob(gocron.DurationJob(config.WatcherRefreshPeriod), gocron.NewTask(func() {
hash := common.MustReturn(hashstructure.Hash(watchers, hashstructure.FormatV2, nil))
if refreshErr := RefreshWatchers(interruptCtx, kubeClient); refreshErr != nil {
logger.Error(refreshErr, "An error occurred while refreshing watchers.")
return
}
if hash != common.MustReturn(hashstructure.Hash(watchers, hashstructure.FormatV2, nil)) {
logger.Info("Watchers updated, restarting")
restart()
}
}), gocron.WithSingletonMode(gocron.LimitModeReschedule)))
scheduler.Start()
for interruptCtx.Err() == nil {
restartCtx, restart = context.WithCancel(interruptCtx)
StartManager(restartCtx, watchers)
}
_ = scheduler.Shutdown()
}
func RefreshWatchers(ctx context.Context, kubeClient client.Reader) error {
watcherList := v1alpha1.WatcherList{}
if listErr := kubeClient.List(ctx, &watcherList); listErr != nil {
return listErr
}
watchers = []v1alpha1.Watcher{}
for _, watcher := range watcherList.Items {
for _, secretKeySelector := range watcher.Spec.ValuesFrom.Secrets {
var (
secret v1.Secret
specFromSecret v1alpha1.WatcherSpec
)
if getErr := kubeClient.Get(ctx, types.NamespacedName{
Name: secretKeySelector.Name, Namespace: secretKeySelector.Namespace,
}, &secret); getErr != nil {
return getErr
}
if unmarshallErr := yaml.Unmarshal(secret.Data[secretKeySelector.Key],
&specFromSecret); unmarshallErr != nil {
return unmarshallErr
}
if mergeErr := mergo.Merge(&watcher, v1alpha1.Watcher{Spec: specFromSecret},
mergo.WithOverride, mergo.WithAppendSlice); mergeErr != nil {
return mergeErr
}
}
watchers = append(watchers, watcher)
}
return nil
}
func StartManager(ctx context.Context, watchers []v1alpha1.Watcher) {
manager := common.MustReturn(ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
Logger: logger,
Cache: cache.Options{
SyncPeriod: &config.SyncPeriod,
},
Metrics: server.Options{
BindAddress: fmt.Sprintf(":%d", metricPort),
},
HealthProbeBindAddress: fmt.Sprintf(":%d", healthPort),
LeaderElection: config.EnableLeaderElection,
LeaderElectionID: "watchtower.cloud.spaceship.com",
LeaderElectionReleaseOnCancel: true,
}))
for _, watcher := range watchers {
common.Must(pkg.NewController(manager.GetClient(), &http.Client{}, watcher.Compile()).SetupWithManager(manager))
}
common.Must(manager.AddHealthzCheck("healthz", healthz.Ping))
common.Must(manager.AddReadyzCheck("readyz", healthz.Ping))
common.Must(manager.Start(ctx))
}