-
Notifications
You must be signed in to change notification settings - Fork 143
/
controller.go
335 lines (294 loc) · 9.08 KB
/
controller.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
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
package main
import (
"context"
"fmt"
"sync"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
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/manager"
"sigs.k8s.io/controller-runtime/pkg/metrics/server"
kargoapi "github.com/akuity/kargo/api/v1alpha1"
"github.com/akuity/kargo/internal/api/kubernetes"
libargocd "github.com/akuity/kargo/internal/argocd"
"github.com/akuity/kargo/internal/controller"
argocd "github.com/akuity/kargo/internal/controller/argocd/api/v1alpha1"
"github.com/akuity/kargo/internal/controller/promotions"
rollouts "github.com/akuity/kargo/internal/controller/rollouts/api/v1alpha1"
"github.com/akuity/kargo/internal/controller/stages"
"github.com/akuity/kargo/internal/controller/warehouses"
"github.com/akuity/kargo/internal/credentials"
"github.com/akuity/kargo/internal/os"
"github.com/akuity/kargo/internal/types"
versionpkg "github.com/akuity/kargo/internal/version"
_ "github.com/akuity/kargo/internal/gitprovider/github"
)
type controllerOptions struct {
ShardName string
KubeConfig string
ArgoCDEnabled bool
ArgoCDKubeConfig string
ArgoCDNamespaceOnly bool
Logger *log.Logger
}
func newControllerCommand() *cobra.Command {
cmdOpts := &controllerOptions{
Logger: log.StandardLogger(),
}
cmd := &cobra.Command{
Use: "controller",
DisableAutoGenTag: true,
SilenceErrors: true,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, _ []string) error {
cmdOpts.complete()
return cmdOpts.run(cmd.Context())
},
}
return cmd
}
func (o *controllerOptions) complete() {
o.ShardName = os.GetEnv("SHARD_NAME", "")
o.KubeConfig = os.GetEnv("KUBECONFIG", "")
o.ArgoCDEnabled = types.MustParseBool(os.GetEnv("ARGOCD_INTEGRATION_ENABLED", "true"))
o.ArgoCDKubeConfig = os.GetEnv("ARGOCD_KUBECONFIG", "")
o.ArgoCDNamespaceOnly = types.MustParseBool(os.GetEnv("ARGOCD_WATCH_ARGOCD_NAMESPACE_ONLY", "false"))
}
func (o *controllerOptions) run(ctx context.Context) error {
version := versionpkg.GetVersion()
startupLogEntry := o.Logger.WithFields(log.Fields{
"version": version.Version,
"commit": version.GitCommit,
})
if o.ShardName != "" {
startupLogEntry = startupLogEntry.WithField("shard", o.ShardName)
}
startupLogEntry.Info("Starting Kargo Controller")
promotionsReconcilerCfg := promotions.ReconcilerConfigFromEnv()
stagesReconcilerCfg := stages.ReconcilerConfigFromEnv()
kargoMgr, err := o.setupKargoManager(ctx, stagesReconcilerCfg)
if err != nil {
return fmt.Errorf("error initializing Kargo controller manager: %w", err)
}
argocdMgr, err := o.setupArgoCDManager(ctx)
if err != nil {
return fmt.Errorf("error initializing Argo CD Application controller manager: %w", err)
}
credentialsDB := credentials.NewKubernetesDatabase(
kargoMgr.GetClient(),
credentials.KubernetesDatabaseConfigFromEnv(),
)
if err := o.setupReconcilers(
ctx,
kargoMgr,
argocdMgr,
credentialsDB,
promotionsReconcilerCfg,
stagesReconcilerCfg,
); err != nil {
return fmt.Errorf("error setting up reconcilers: %w", err)
}
return o.startManagers(ctx, kargoMgr, argocdMgr)
}
func (o *controllerOptions) setupKargoManager(
ctx context.Context,
stagesReconcilerCfg stages.ReconcilerConfig,
) (manager.Manager, error) {
// If the env var is undefined, this will resolve to kubeconfig for the
// cluster the controller is running in.
//
// It is typically defined if this controller is running somewhere other
// than where the Kargo resources live. One example of this would be a
// sharded topology wherein Kargo controllers run on application
// clusters, with Kargo resources hosted in a centralized management
// cluster.
restCfg, err := kubernetes.GetRestConfig(ctx, o.KubeConfig)
if err != nil {
return nil, fmt.Errorf("error loading REST config for Kargo controller manager: %w", err)
}
restCfg.ContentType = runtime.ContentTypeJSON
scheme := runtime.NewScheme()
if err = corev1.AddToScheme(scheme); err != nil {
return nil, fmt.Errorf(
"error adding Kubernetes core API to Kargo controller manager scheme: %w",
err,
)
}
if err = kargoapi.AddToScheme(scheme); err != nil {
return nil, fmt.Errorf(
"error adding Kargo API to Kargo controller manager scheme: %w",
err,
)
}
if stagesReconcilerCfg.RolloutsIntegrationEnabled {
if argoRolloutsExists(ctx, restCfg) {
log.Info("Argo Rollouts integration is enabled")
if err = rollouts.AddToScheme(scheme); err != nil {
return nil, fmt.Errorf(
"error adding Argo Rollouts API to Kargo controller manager scheme: %w",
err,
)
}
} else {
log.Warn(
"Argo Rollouts integration was enabled, but no Argo Rollouts " +
"CRDs were found. Proceeding without Argo Rollouts integration.",
)
}
}
secretReq, err := controller.GetCredentialsRequirement()
if err != nil {
return nil, fmt.Errorf("error getting label requirement for credentials Secrets: %w", err)
}
cacheOpts := cache.Options{
ByObject: map[client.Object]cache.ByObject{
// Only watch Secrets matching the label requirements
// for credentials.
&corev1.Secret{}: {
Label: labels.NewSelector().Add(*secretReq),
},
},
}
return ctrl.NewManager(
restCfg,
ctrl.Options{
Scheme: scheme,
Metrics: server.Options{
BindAddress: "0",
},
Cache: cacheOpts,
},
)
}
func (o *controllerOptions) setupArgoCDManager(ctx context.Context) (manager.Manager, error) {
if !o.ArgoCDEnabled {
o.Logger.Info("Argo CD integration is disabled")
return nil, nil
}
// If the env var is undefined, this will resolve to kubeconfig for the
// cluster the controller is running in.
//
// It is typically defined if this controller is running somewhere other
// than where the Argo CD resources live. Two examples of this would
// involve topologies wherein Kargo controllers run EITHER sharded
// across application clusters OR in a centralized management cluster,
// but with Argo CD deployed to a different management cluster.
restCfg, err := kubernetes.GetRestConfig(ctx, o.ArgoCDKubeConfig)
if err != nil {
return nil, fmt.Errorf("error loading REST config for Argo CD controller manager: %w", err)
}
restCfg.ContentType = runtime.ContentTypeJSON
argocdNamespace := libargocd.Namespace()
// There's a chance there is only permission to interact with Argo CD
// Application resources in a single namespace, so we will use that
// namespace when attempting to determine if Argo CD CRDs are installed.
if !argoCDExists(ctx, restCfg, argocdNamespace) {
o.Logger.Warn(
"Argo CD integration was enabled, but no Argo CD CRDs were found. " +
"Proceeding without Argo CD integration.",
)
return nil, nil
}
o.Logger.Info("Argo CD integration is enabled")
scheme := runtime.NewScheme()
if err = corev1.AddToScheme(scheme); err != nil {
return nil, fmt.Errorf(
"error adding Kubernetes core API to Argo CD controller manager scheme: %w",
err,
)
}
if err = argocd.AddToScheme(scheme); err != nil {
return nil, fmt.Errorf(
"error adding Argo CD API to Argo CD controller manager scheme: %w",
err,
)
}
cacheOpts := cache.Options{} // Watches all namespaces by default
if o.ArgoCDNamespaceOnly {
cacheOpts.DefaultNamespaces = map[string]cache.Config{
argocdNamespace: {},
}
}
return ctrl.NewManager(
restCfg,
ctrl.Options{
Scheme: scheme,
Metrics: server.Options{
BindAddress: "0",
},
Cache: cacheOpts,
},
)
}
func (o *controllerOptions) setupReconcilers(
ctx context.Context,
kargoMgr, argocdMgr manager.Manager,
credentialsDB credentials.Database,
promotionsReconcilerCfg promotions.ReconcilerConfig,
stagesReconcilerCfg stages.ReconcilerConfig,
) error {
if err := promotions.SetupReconcilerWithManager(
ctx,
kargoMgr,
argocdMgr,
credentialsDB,
promotionsReconcilerCfg,
); err != nil {
return fmt.Errorf("error setting up Promotions reconciler: %w", err)
}
if err := stages.SetupReconcilerWithManager(
ctx,
kargoMgr,
argocdMgr,
stagesReconcilerCfg,
); err != nil {
return fmt.Errorf("error setting up Stages reconciler: %w", err)
}
if err := warehouses.SetupReconcilerWithManager(
kargoMgr,
credentialsDB,
o.ShardName,
); err != nil {
return fmt.Errorf("error setting up Warehouses reconciler: %w", err)
}
return nil
}
func (o *controllerOptions) startManagers(ctx context.Context, kargoMgr, argocdMgr manager.Manager) error {
var (
errChan = make(chan error)
wg = sync.WaitGroup{}
)
if argocdMgr != nil {
wg.Add(1)
go func() {
defer wg.Done()
if err := argocdMgr.Start(ctx); err != nil {
errChan <- fmt.Errorf("error starting argo cd manager: %w", err)
}
}()
}
wg.Add(1)
go func() {
defer wg.Done()
if err := kargoMgr.Start(ctx); err != nil {
errChan <- fmt.Errorf("error starting kargo manager: %w", err)
}
}()
// Adapt wg to a channel that can be used in a select
doneCh := make(chan struct{})
go func() {
wg.Wait()
close(doneCh)
}()
select {
case err := <-errChan:
return err
case <-doneCh:
return nil
}
}