-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrun.go
More file actions
377 lines (326 loc) · 11.2 KB
/
run.go
File metadata and controls
377 lines (326 loc) · 11.2 KB
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package controller
import (
"context"
"fmt"
"net/http"
"net/http/pprof"
"os"
"strings"
"time"
"github.com/bombsimon/logrusr/v4"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apiserver/pkg/server/healthz"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
"k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2"
"github.com/castai/cluster-controller/cmd/utils"
"github.com/castai/cluster-controller/health"
"github.com/castai/cluster-controller/internal/actions"
"github.com/castai/cluster-controller/internal/actions/csr"
"github.com/castai/cluster-controller/internal/castai"
"github.com/castai/cluster-controller/internal/config"
"github.com/castai/cluster-controller/internal/controller"
"github.com/castai/cluster-controller/internal/controller/logexporter"
"github.com/castai/cluster-controller/internal/controller/metricexporter"
"github.com/castai/cluster-controller/internal/helm"
"github.com/castai/cluster-controller/internal/k8sversion"
"github.com/castai/cluster-controller/internal/metrics"
"github.com/castai/cluster-controller/internal/monitor"
"github.com/castai/cluster-controller/internal/waitext"
)
const (
maxRequestTimeout = 5 * time.Minute
)
func run(ctx context.Context) error {
log := logrus.WithFields(logrus.Fields{})
cfg := config.Get()
binVersion := ctx.Value(utils.ClusterControllerVersionKey).(*config.ClusterControllerVersion)
log.Infof("running castai-cluster-controller version %v", binVersion)
logger := logexporter.NewLogger(cfg.Log.Level)
cl, err := castai.NewRestyClient(cfg.API.URL, cfg.API.Key, cfg.TLS.CACert, logger.Level, binVersion, maxRequestTimeout)
if err != nil {
log.Fatalf("failed to create castai client: %v", err)
}
client := castai.NewClient(logger, cl, cfg.ClusterID, cfg.SelfPod.Name)
logexporter.SetupLogExporter(logger, client)
return runController(ctx, client, logger.WithFields(logrus.Fields{
"cluster_id": cfg.ClusterID,
"version": binVersion.String(),
"autoscaling_disabled": cfg.AutoscalingDisabled,
}), cfg, binVersion)
}
func runController(
ctx context.Context,
client castai.CastAIClient,
logger *logrus.Entry,
cfg config.Config,
binVersion *config.ClusterControllerVersion,
) (reterr error) {
fields := logrus.Fields{}
defer func() {
if reterr == nil {
return
}
reterr = &logContextError{
err: reterr,
fields: fields,
}
}()
restConfig, err := config.RetrieveKubeConfig(logger)
if err != nil {
return err
}
restConfigLeader := rest.CopyConfig(restConfig)
restConfigDynamic := rest.CopyConfig(restConfig)
restConfig.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(float32(cfg.KubeClient.QPS), cfg.KubeClient.Burst)
restConfigLeader.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(float32(cfg.KubeClient.QPS), cfg.KubeClient.Burst)
restConfigDynamic.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(float32(cfg.KubeClient.QPS), cfg.KubeClient.Burst)
helmClient := helm.NewClient(logger, helm.NewChartLoader(logger), restConfig)
clientset, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return err
}
clientSetLeader, err := kubernetes.NewForConfig(restConfigLeader)
if err != nil {
return err
}
dynamicClient, err := dynamic.NewForConfig(restConfigDynamic)
if err != nil {
return err
}
k8sVer, err := k8sversion.Get(clientset)
if err != nil {
return fmt.Errorf("getting kubernetes version: %w", err)
}
log := logger.WithFields(logrus.Fields{
"version": binVersion.Version,
"k8s_version": k8sVer.Full(),
"running_on": cfg.SelfPod.Node,
"ctrl_pod_name": cfg.SelfPod.Name,
})
// Set logr/klog to logrus adapter so all logging goes through logrus
logr := logrusr.New(log)
klog.SetLogger(logr)
log.Infof("running castai-cluster-controller version %v, log-level: %v", binVersion, logger.Level)
actionHandlers := actions.NewDefaultActionHandlers(
k8sVer.Full(),
cfg.SelfPod.Namespace,
log,
clientset,
dynamicClient,
helmClient,
)
actionsConfig := controller.Config{
PollWaitInterval: 5 * time.Second,
PollTimeout: maxRequestTimeout,
AckTimeout: 30 * time.Second,
AckRetriesCount: 3,
AckRetryWait: 1 * time.Second,
ClusterID: cfg.ClusterID,
Version: binVersion.Version,
Namespace: cfg.SelfPod.Namespace,
MaxActionsInProgress: cfg.MaxActionsInProgress,
}
healthzAction := health.NewHealthzProvider(health.HealthzCfg{HealthyPollIntervalLimit: (actionsConfig.PollWaitInterval + actionsConfig.PollTimeout) * 2, StartTimeLimit: 2 * time.Minute}, log)
svc := controller.NewService(
log,
actionsConfig,
k8sVer.Full(),
client,
healthzAction,
actionHandlers,
)
defer func() {
if err := svc.Close(); err != nil {
log.Errorf("failed to close controller service: %v", err)
}
}()
if cfg.Metrics.ExportEnabled {
metricExporter := metricexporter.New(log, client, cfg.Metrics.ExportInterval)
go metricExporter.Run(ctx)
}
httpMux := http.NewServeMux()
var checks []healthz.HealthChecker
checks = append(checks, healthzAction)
var leaderHealthCheck *leaderelection.HealthzAdaptor
if cfg.LeaderElection.Enabled {
leaderHealthCheck = leaderelection.NewLeaderHealthzAdaptor(time.Minute)
checks = append(checks, leaderHealthCheck)
}
healthz.InstallHandler(httpMux, checks...)
installPprofHandlers(httpMux)
// Start http server for pprof and health checks handlers.
go func() {
addr := fmt.Sprintf(":%d", cfg.PprofPort)
log.Infof("starting pprof server on %s", addr)
// https://deepsource.com/directory/go/issues/GO-S2114
// => This is not a public API and runs in customer cluster; risk should be OK.
//nolint:gosec
if err := http.ListenAndServe(addr, httpMux); err != nil {
log.Errorf("failed to start pprof http server: %v", err)
}
}()
// Start http server for metrics
go func() {
addr := fmt.Sprintf(":%d", cfg.Metrics.Port)
log.Infof("starting metrics on %s", addr)
metrics.RegisterCustomMetrics()
metricsMux := metrics.NewMetricsMux()
// https://deepsource.com/directory/go/issues/GO-S2114
// => This is not a public API and runs in customer cluster; risk should be OK.
//nolint:gosec
if err := http.ListenAndServe(addr, metricsMux); err != nil {
log.Errorf("failed to start metrics http server: %v", err)
}
}()
if err := saveMetadata(cfg.ClusterID, cfg, log); err != nil {
return err
}
runSvc := func(ctx context.Context) {
isGKE, err := runningOnGKE(clientset, cfg)
if err != nil {
log.Fatalf("failed to determine if running on GKE: %v", err)
}
log.Infof("Running on GKE is: %v", isGKE)
if isGKE && !cfg.AutoscalingDisabled {
csrMgr := csr.NewApprovalManager(log, clientset)
if err := csrMgr.Start(ctx); err != nil {
log.WithError(err).Fatal("failed to start approval manager")
}
log.Info("auto approve csr started as running on GKE")
}
svc.Run(ctx)
}
if cfg.LeaderElection.Enabled {
// Run actions service with leader election. Blocks.
return runWithLeaderElection(ctx, log, clientSetLeader, leaderHealthCheck, &cfg, runSvc)
}
// Run action service. Blocks.
runSvc(ctx)
return nil
}
func runWithLeaderElection(
ctx context.Context,
log logrus.FieldLogger,
clientset kubernetes.Interface,
watchDog *leaderelection.HealthzAdaptor,
cfg *config.Config,
runFunc func(ctx context.Context),
) error {
id, err := os.Hostname()
if err != nil {
return fmt.Errorf("failed to determine hostname used in leader ID: %w", err)
}
id = id + "_" + uuid.New().String()
// Start the leader election code loop
leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
Lock: &resourcelock.LeaseLock{
LeaseMeta: metav1.ObjectMeta{
Name: cfg.LeaderElection.LockName,
Namespace: cfg.SelfPod.Namespace,
},
Client: clientset.CoordinationV1(),
LockConfig: resourcelock.ResourceLockConfig{
Identity: id,
},
},
// IMPORTANT: you MUST ensure that any code you have that
// is protected by the lease must terminate **before**
// you call cancel. Otherwise, you could have a background
// loop still running and another process could
// get elected before your background loop finished, violating
// the stated goal of the lease.
ReleaseOnCancel: true,
LeaseDuration: cfg.LeaderElection.LeaseDuration,
RenewDeadline: cfg.LeaderElection.LeaseRenewDeadline,
RetryPeriod: 3 * time.Second,
WatchDog: watchDog,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: func(ctx context.Context) {
log.WithFields(logrus.Fields{
"leaseDuration": cfg.LeaderElection.LeaseDuration.String(),
"leaseRenewDuration": cfg.LeaderElection.LeaseRenewDeadline.String(),
}).Infof("leader elected: %s", id)
runFunc(ctx)
},
OnStoppedLeading: func() {
// This method is always called(even if it was not a leader):
// - when controller shuts dow (for example because of SIGTERM)
// - we actually lost leader
// So we need to check what whas reason of acutally stopping.
if err := ctx.Err(); err != nil {
log.Infof("main context done, stopping controller: %v", err)
return
}
log.Infof("leader lost: %s", id)
// We don't need to exit here.
// Leader "on started leading" receive a context that gets cancelled when you're no longer the leader.
},
OnNewLeader: func(identity string) {
// We're notified when new leader elected.
if identity == id {
// I just got the lock.
return
}
log.Infof("new leader elected: %s", identity)
},
},
})
return nil
}
func installPprofHandlers(mux *http.ServeMux) {
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
}
type logContextError struct {
err error
fields logrus.Fields
}
func (e *logContextError) Error() string {
return e.err.Error()
}
func (e *logContextError) Unwrap() error {
return e.err
}
func runningOnGKE(clientset *kubernetes.Clientset, cfg config.Config) (isGKE bool, err error) {
// When running locally, there is no node.
if cfg.SelfPod.Node == "" {
return false, nil
}
err = waitext.Retry(context.Background(), waitext.DefaultExponentialBackoff(), 3, func(ctx context.Context) (bool, error) {
node, err := clientset.CoreV1().Nodes().Get(ctx, cfg.SelfPod.Node, metav1.GetOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return true, fmt.Errorf("getting node: %w", err)
}
for k := range node.Labels {
if strings.HasPrefix(k, "cloud.google.com/") {
isGKE = true
return false, nil
}
}
return false, nil
}, func(err error) {
})
return
}
func saveMetadata(clusterID string, cfg config.Config, log *logrus.Entry) error {
metadata := monitor.Metadata{
ClusterID: clusterID,
LastStart: time.Now().UnixNano(),
}
log.Infof("saving metadata: %v to file: %v", metadata, cfg.MonitorMetadataPath)
if err := metadata.Save(cfg.MonitorMetadataPath); err != nil {
return fmt.Errorf("saving metadata: %w", err)
}
return nil
}